|
| 1 | +--- |
| 2 | +summary: "Deep dive: session store + transcripts, lifecycle, and (auto)compaction internals" |
| 3 | +read_when: |
| 4 | + - You need to debug session ids, transcript JSONL, or sessions.json fields |
| 5 | + - You are changing auto-compaction behavior or adding “pre-compaction” housekeeping |
| 6 | + - You want to implement memory flushes or silent system turns |
| 7 | +--- |
| 8 | +# Session Management & Compaction (Deep Dive) |
| 9 | + |
| 10 | +This document explains how Clawdbot manages sessions end-to-end: |
| 11 | + |
| 12 | +- **Session routing** (how inbound messages map to a `sessionKey`) |
| 13 | +- **Session store** (`sessions.json`) and what it tracks |
| 14 | +- **Transcript persistence** (`*.jsonl`) and its structure |
| 15 | +- **Context limits** (context window vs tracked tokens) |
| 16 | +- **Compaction** (manual + auto-compaction) and where to hook pre-compaction work |
| 17 | +- **Silent housekeeping** (e.g. memory writes that shouldn’t produce user-visible output) |
| 18 | + |
| 19 | +If you want a higher-level overview first, start with: |
| 20 | +- [/concepts/session](/concepts/session) |
| 21 | +- [/concepts/compaction](/concepts/compaction) |
| 22 | +- [/concepts/session-pruning](/concepts/session-pruning) |
| 23 | + |
| 24 | +--- |
| 25 | + |
| 26 | +## Source of truth: the Gateway |
| 27 | + |
| 28 | +Clawdbot is designed around a single **Gateway process** that owns session state. |
| 29 | + |
| 30 | +- UIs (macOS app, web Control UI, TUI) should query the Gateway for session lists and token counts. |
| 31 | +- In remote mode, session files are on the remote host; “checking your local Mac files” won’t reflect what the Gateway is using. |
| 32 | + |
| 33 | +--- |
| 34 | + |
| 35 | +## Two persistence layers |
| 36 | + |
| 37 | +Clawdbot persists sessions in two layers: |
| 38 | + |
| 39 | +1) **Session store (`sessions.json`)** |
| 40 | + - Key/value map: `sessionKey -> SessionEntry` |
| 41 | + - Small, mutable, safe to edit (or delete entries) |
| 42 | + - Tracks session metadata (current session id, last activity, toggles, token counters, etc.) |
| 43 | + |
| 44 | +2) **Transcript (`<sessionId>.jsonl`)** |
| 45 | + - Append-only transcript with tree structure (entries have `id` + `parentId`) |
| 46 | + - Stores the actual conversation + tool calls + compaction summaries |
| 47 | + - Used to rebuild the model context for future turns |
| 48 | + |
| 49 | +--- |
| 50 | + |
| 51 | +## On-disk locations |
| 52 | + |
| 53 | +Per agent, on the Gateway host: |
| 54 | + |
| 55 | +- Store: `~/.clawdbot/agents/<agentId>/sessions/sessions.json` |
| 56 | +- Transcripts: `~/.clawdbot/agents/<agentId>/sessions/<sessionId>.jsonl` |
| 57 | + - Telegram topic sessions: `.../<sessionId>-topic-<threadId>.jsonl` |
| 58 | + |
| 59 | +Clawdbot resolves these via `src/config/sessions.ts`. |
| 60 | + |
| 61 | +--- |
| 62 | + |
| 63 | +## Session keys (`sessionKey`) |
| 64 | + |
| 65 | +A `sessionKey` identifies *which conversation bucket* you’re in (routing + isolation). |
| 66 | + |
| 67 | +Common patterns: |
| 68 | + |
| 69 | +- Main/direct chat (per agent): `agent:<agentId>:<mainKey>` (default `main`) |
| 70 | +- Group: `agent:<agentId>:<provider>:group:<id>` |
| 71 | +- Room/channel (Discord/Slack): `agent:<agentId>:<provider>:channel:<id>` or `...:room:<id>` |
| 72 | +- Cron: `cron:<job.id>` |
| 73 | +- Webhook: `hook:<uuid>` (unless overridden) |
| 74 | + |
| 75 | +The canonical rules are documented at [/concepts/session](/concepts/session). |
| 76 | + |
| 77 | +--- |
| 78 | + |
| 79 | +## Session ids (`sessionId`) |
| 80 | + |
| 81 | +Each `sessionKey` points at a current `sessionId` (the transcript file that continues the conversation). |
| 82 | + |
| 83 | +Rules of thumb: |
| 84 | +- **Reset** (`/new`, `/reset`) creates a new `sessionId` for that `sessionKey`. |
| 85 | +- **Idle expiry** (`session.idleMinutes`) creates a new `sessionId` when a message arrives after the idle window. |
| 86 | + |
| 87 | +Implementation detail: the decision happens in `initSessionState()` in `src/auto-reply/reply/session.ts`. |
| 88 | + |
| 89 | +--- |
| 90 | + |
| 91 | +## Session store schema (`sessions.json`) |
| 92 | + |
| 93 | +The store’s value type is `SessionEntry` in `src/config/sessions.ts`. |
| 94 | + |
| 95 | +Key fields (not exhaustive): |
| 96 | + |
| 97 | +- `sessionId`: current transcript id (filename is derived from this unless `sessionFile` is set) |
| 98 | +- `updatedAt`: last activity timestamp |
| 99 | +- `sessionFile`: optional explicit transcript path override |
| 100 | +- `chatType`: `direct | group | room` (helps UIs and send policy) |
| 101 | +- `provider`, `subject`, `room`, `space`, `displayName`: metadata for group/channel labeling |
| 102 | +- Toggles: |
| 103 | + - `thinkingLevel`, `verboseLevel`, `reasoningLevel`, `elevatedLevel` |
| 104 | + - `sendPolicy` (per-session override) |
| 105 | +- Model selection: |
| 106 | + - `providerOverride`, `modelOverride`, `authProfileOverride` |
| 107 | +- Token counters (best-effort / provider-dependent): |
| 108 | + - `inputTokens`, `outputTokens`, `totalTokens`, `contextTokens` |
| 109 | +- `compactionCount`: how often auto-compaction completed for this session key |
| 110 | + |
| 111 | +The store is safe to edit, but the Gateway is the authority: it may rewrite or rehydrate entries as sessions run. |
| 112 | + |
| 113 | +--- |
| 114 | + |
| 115 | +## Transcript structure (`*.jsonl`) |
| 116 | + |
| 117 | +Transcripts are managed by `@mariozechner/pi-coding-agent`’s `SessionManager`. |
| 118 | + |
| 119 | +The file is JSONL: |
| 120 | +- First line: session header (`type: "session"`, includes `id`, `cwd`, `timestamp`, optional `parentSession`) |
| 121 | +- Then: session entries with `id` + `parentId` (tree) |
| 122 | + |
| 123 | +Notable entry types: |
| 124 | +- `message`: user/assistant/toolResult messages |
| 125 | +- `custom_message`: extension-injected messages that *do* enter model context (can be hidden from UI) |
| 126 | +- `custom`: extension state that does *not* enter model context |
| 127 | +- `compaction`: persisted compaction summary with `firstKeptEntryId` and `tokensBefore` |
| 128 | +- `branch_summary`: persisted summary when navigating a tree branch |
| 129 | + |
| 130 | +Clawdbot intentionally does **not** “fix up” transcripts; the Gateway uses `SessionManager` to read/write them. |
| 131 | + |
| 132 | +--- |
| 133 | + |
| 134 | +## Context windows vs tracked tokens |
| 135 | + |
| 136 | +Two different concepts matter: |
| 137 | + |
| 138 | +1) **Model context window**: hard cap per model (tokens visible to the model) |
| 139 | +2) **Session store counters**: rolling stats written into `sessions.json` (used for /status and dashboards) |
| 140 | + |
| 141 | +If you’re tuning limits: |
| 142 | +- The context window comes from the model catalog (and can be overridden via config). |
| 143 | +- `contextTokens` in the store is a runtime estimate/reporting value; don’t treat it as a strict guarantee. |
| 144 | + |
| 145 | +For more, see [/token-use](/token-use). |
| 146 | + |
| 147 | +--- |
| 148 | + |
| 149 | +## Compaction: what it is |
| 150 | + |
| 151 | +Compaction summarizes older conversation into a persisted `compaction` entry in the transcript and keeps recent messages intact. |
| 152 | + |
| 153 | +After compaction, future turns see: |
| 154 | +- The compaction summary |
| 155 | +- Messages after `firstKeptEntryId` |
| 156 | + |
| 157 | +Compaction is **persistent** (unlike session pruning). See [/concepts/session-pruning](/concepts/session-pruning). |
| 158 | + |
| 159 | +--- |
| 160 | + |
| 161 | +## When auto-compaction happens (Pi runtime) |
| 162 | + |
| 163 | +In the embedded Pi agent, auto-compaction triggers in two cases: |
| 164 | + |
| 165 | +1) **Overflow recovery**: the model returns a context overflow error → compact → retry. |
| 166 | +2) **Threshold maintenance**: after a successful turn, when: |
| 167 | + |
| 168 | +`contextTokens > contextWindow - reserveTokens` |
| 169 | + |
| 170 | +Where: |
| 171 | +- `contextWindow` is the model’s context window |
| 172 | +- `reserveTokens` is headroom reserved for prompts + the next model output |
| 173 | + |
| 174 | +These are Pi runtime semantics (Clawdbot consumes the events, but Pi decides when to compact). |
| 175 | + |
| 176 | +--- |
| 177 | + |
| 178 | +## Compaction settings (`reserveTokens`, `keepRecentTokens`) |
| 179 | + |
| 180 | +Pi’s compaction settings live in Pi settings: |
| 181 | + |
| 182 | +```json5 |
| 183 | +{ |
| 184 | + compaction: { |
| 185 | + enabled: true, |
| 186 | + reserveTokens: 16384, |
| 187 | + keepRecentTokens: 20000 |
| 188 | + } |
| 189 | +} |
| 190 | +``` |
| 191 | + |
| 192 | +Clawdbot also enforces a safety floor for embedded runs: |
| 193 | + |
| 194 | +- If `compaction.reserveTokens < 20000`, Clawdbot bumps it to 20000. |
| 195 | +- If it’s already higher, Clawdbot leaves it alone. |
| 196 | + |
| 197 | +Why: leave enough headroom for multi-turn “housekeeping” (like memory writes) before compaction becomes unavoidable. |
| 198 | + |
| 199 | +Implementation: `ensurePiCompactionReserveTokens()` in `src/agents/pi-settings.ts` (called from `src/agents/pi-embedded-runner.ts`). |
| 200 | + |
| 201 | +--- |
| 202 | + |
| 203 | +## User-visible surfaces |
| 204 | + |
| 205 | +You can observe compaction and session state via: |
| 206 | + |
| 207 | +- `/status` (in any chat session) |
| 208 | +- `clawdbot status` (CLI) |
| 209 | +- `clawdbot sessions` / `sessions --json` |
| 210 | +- Verbose mode: `🧹 Auto-compaction complete` + compaction count |
| 211 | + |
| 212 | +--- |
| 213 | + |
| 214 | +## Silent housekeeping (`NO_REPLY`) |
| 215 | + |
| 216 | +Clawdbot supports “silent” turns for background tasks where the user should not see intermediate output. |
| 217 | + |
| 218 | +Convention: |
| 219 | +- The assistant starts its output with `NO_REPLY` to indicate “do not deliver a reply to the user”. |
| 220 | +- Clawdbot strips/suppresses this in the delivery layer. |
| 221 | + |
| 222 | +As of `2026.1.10`, Clawdbot also suppresses **draft/typing streaming** when a partial chunk begins with `NO_REPLY`, so silent operations don’t leak partial output mid-turn. |
| 223 | + |
| 224 | +--- |
| 225 | + |
| 226 | +## Pre-compaction “memory flush” (design) |
| 227 | + |
| 228 | +Goal: before auto-compaction happens, run a short sequence of turns that writes durable state to disk (e.g. `memory/YYYY-MM-DD.md` in the agent workspace) so compaction can’t erase critical context. |
| 229 | + |
| 230 | +Two viable hooks: |
| 231 | + |
| 232 | +1) **Pre-threshold flush (Clawdbot-side)** |
| 233 | + - Monitor session context usage. |
| 234 | + - When it crosses a “soft threshold” (below Pi’s real compaction threshold), enqueue a silent “write memory now” directive to the agent. |
| 235 | + - Use `NO_REPLY` so the user sees nothing. |
| 236 | + |
| 237 | +2) **Pi extension hook (`session_before_compact`)** |
| 238 | + - Pi’s extension API exposes a `session_before_compact` event that receives compaction preparation details and can cancel or replace compaction. |
| 239 | + - Clawdbot can ship an extension that reacts here and performs housekeeping (and/or produces a custom compaction result). |
| 240 | + |
| 241 | +Clawdbot currently documents the *concept* of daily memory in the workspace template (see [/concepts/agent-workspace](/concepts/agent-workspace)) but does not yet ship an automated pre-compaction flush loop. |
| 242 | + |
| 243 | +--- |
| 244 | + |
| 245 | +## Troubleshooting checklist |
| 246 | + |
| 247 | +- Session key wrong? Start with [/concepts/session](/concepts/session) and confirm the `sessionKey` in `/status`. |
| 248 | +- Store vs transcript mismatch? Confirm the Gateway host and the store path from `clawdbot status`. |
| 249 | +- Compaction spam? Check: |
| 250 | + - model context window (too small) |
| 251 | + - compaction settings (`reserveTokens` too high for the model window can cause earlier compaction) |
| 252 | + - tool-result bloat: enable/tune session pruning |
| 253 | +- Silent turns leaking? Confirm the reply starts with `NO_REPLY` (exact token) and you’re on a build that includes the streaming suppression fix. |
| 254 | + |
0 commit comments