Docs
中文 EN

Sessions, Compaction & Trajectory Tracing

CONTENTS

Mizar logs every prompt, model message, and tool call/result as an append-only event stream (SessionEvent), powering tolerant JSONL persistence, crash recovery, /tree branching, hot-cache-aware compaction, and trajectory profiling.

FIG 03 JSONL Session Forking, Compaction & Trajectory Export
JSONL Append Log & /tree Fork mizar-session mizar-session-jsonl (cwd-bucket · Blob · Lazy) Single-Writer · non-silent errors · 0 version reject #1 USER (Turn 1) "Debug config merge" #2 ASST + TOOL read · edit · BASH!!(local) /tree Fork Session fork(id, up_to_seq=#2) • Atomic create (no overwrite) • parent_id + fork_seq • Auto-heal orphan calls #3' USER (Branch B) Try edits safely Mainline untouched #3 B-5 COMPACT + PRUNE Hot-cache · 8k tail · supersede B-5 Guard · FileGuardTracker #4 USER (Turn 2) Continue from summary #5 ASST · derive_messages() Projection Skips LogOnly trace events & !! local cmds Session Resume & Crash Recovery --continue / --resume <id> · prints cmd on exit Ctrl+T / /trace 3-Lane Profiler TRAJECTORY Timeline Hotspots [Axis: Duration / Seq / Actual] ① WaveBand Overview (Click bar to jump) ② Timeline 3-Lane Ledger (Lane 0 / 1 / 2) L0 In/Alert USER CTX ⚠ RepeatGuard L1 LLM Turn TTFT Decode 1.1s LLM T2 L2 Tool Run read bash err ③ Hotspots Latency Ranking (Tab) ▸ bash 4 calls 820ms grep 6 calls 74ms err:1 ④ Step Inspector & /export TTFT: 280ms · Total: 1,380ms · ↑12.4k ↓840 tokens Full tool args / result preview / RepeatGuard alerts /export → .jsonl · exec --trace-out → TrajectoryExport
FIG 03: Tolerant JSONL persistence and /tree forking (left) alongside Ctrl+T /trace and --trace-out profiling (right).

Tolerant JSONL Persistence & Content-Addressed Blobs

  • cwd-Bucketed Lazy Persistence (mizar-session-jsonl): Persists by default under ~/.mizar/sessions (override via MIZAR_SESSIONS_DIR or settings.json sessionsDir; disable via none / off / memory or --no-persist). Sessions bucket by canonicalized cwd into <sessions_dir>/<encoded-cwd>/<YYYYMMDDTHHMMSSZ>_<session_id>.jsonl (empty/missing cwd maps to _global; symlinks resolving to the same canonical path share one bucket). Lazy creation: empty sessions never create empty .jsonl files until the first non-empty append or fork, and empty TUI exits omit invalid --resume hints.
  • Tolerant Append-Only Format & Zero Version-Number Rejection: Uses "session", "entry", and "header-patch" records. The reader scans byte-wise lines, strips BOM/blank lines, safely skips truncated crash tails, unknown record kinds, or unknown event variants (still tracking max_persisted_seq so new seq numbers stay strictly greater, and inserting a leading \n before appending if needed), and never rejects by formatVersion (both 0 and higher integers like 999 open cleanly).
  • Content-Addressed Image Blobs (blobs/<sha256>): Inline base64 images are hashed with pure-Rust RFC 6234 SHA-256 and atomically written to sibling blobs/<sha256> ("blob:sha256:<hex>" in JSONL). Missing blobs during resume only drop the missing attachment with a warning log without crashing.
  • Single-Writer & Non-Silent Error Surfacing: Runs a startup directory write probe; a dedicated mizar-jsonl-writer thread handles mpsc appends + flush / flush_async barriers and exposes last_error(). Init, runtime write, or exit flush failures surface visibly in TUI (NoticeLevel::Error, flash banner, explicit exit error) and cause mizar exec to fail with reason="storage" and exit code 1.
  • Resume & Orphan Healing: Use -c / --continue to resume the latest workspace session or -r / --resume [id] for a specific session. Unpaired tool_call entries from past crashes are automatically healed during replay and /tree forking.

/tree Forking & Auto Titles

  • /tree Branching: fork(id, up_to_seq) copies prefix events into a new child session linked via parent_id and fork_seq. Both SessionStore::fork and JSONL exec_fork reject duplicate session IDs and refuse overwriting existing .jsonl files, keeping mainline and sibling branches intact.
  • Async Session Titles (mizar-session-title): Summarizes turns in MMDD|TYPE|Topic format (FIX, FEA, DOC, etc.) on Turn 1 and every 20 turns. Manual /rename <title> sets TitleSource::Manual and locks against auto-overwrites; /rename with no args triggers immediate LLM regeneration.

Context Compaction (B-5) & Hot-Cache-Aware Pruning

Long sessions stay accurate without thrashing provider Prompt Cache via a two-stage pipeline:

  1. Hot-Cache-Aware Tail Pruning (mizar-compaction/src/pruning.rs):
    • compaction.supersedeReads (default true): Prunes older read outputs superseded by a full re-read of the same path (including superseded image attachments and their context budget).
    • compaction.dropUseless (default true): Prunes zero-hit or superseded noise (SKILL.md reads are always protected).
    • Hot-Cache & 8k Warm-Suffix Protection: Sessions on cache-enabled OpenAI Responses, reasoning-capable Anthropic Messages, or containing Responses replay / signed thinking blocks keep their warm prefix untouched before threshold; unprotected sessions still preserve the newest 8,000 tokens (flushing only after 90 min idle). Prunes append SessionEvent::ToolResultPrune markers without mutating historical entries.
  2. Checkpoint Compaction (mizar-compaction B-5):
    • Window Precedence: --context-window > MIZAR_CONTEXT_WINDOW > model catalog contextWindow > compaction.defaultContextWindow > 128,000 (optionally capped by compaction.maxContextTokens).
    • Threshold & Recovery: Triggers at effective_window * triggerRatio (default 0.80, retaining keepRecentTokens = 20000 raw tokens) — hot-cache sessions first attempt full pruning before calling the summarizer, or run anytime via /compact [focus]. Summarization forces ReasoningEffort::Off and rejects truncated/empty wrappers. On L3 overflow recovery, mizar-agent-loop refreshes both system_prompt.build_for_session and tools.list_declared; FileGuardTracker on tools/pre-execute blocks blind whole-file write overwrites until re-read or edit.

/trace Profiler & --trace-out Export

  • Interactive 3-Lane Profiler (Ctrl+T / /trace):
    • WaveBand overview bar (click any pulse to jump).
    • Timeline with 3 parallel lanes: L0 Input/Alerts (USER, CTX, RepeatToolGuard), L1 LLM Turns (TTFT + Decode), and L2 Tool Execution (including nested codemode spans and individual tool latencies), switchable across Duration, Seq, and Actual axes.
    • Hotspots & Inspector for tool latency breakdowns, token usage, and full arguments/results.
  • Headless Structured Export (--trace-out <path> / MIZAR_TRACE_OUT): On completion, timeout, or error, mizar exec atomically writes a structured TrajectoryExport JSON file (CLI flag takes precedence over env var; in parallel batches tool_result.duration_ms and result.tool_ms record per-tool individual execution times). Interactively, /export [path] writes JSONL trajectory logs.

Search Mizar Docs