@foliox/transparent-compact-pi 0.8.9 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,88 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased — initial release preparation
3
+ ## 0.9.3
4
+
5
+ - Restore the `706b04b` advertisements for lookup, listing, and grep, including the
6
+ lookup question description; omit "authoritative" from grep attribution. Keep
7
+ the 0.9.2 `context_show_entry` advertisement and ref-free checkpoints unchanged.
8
+ This changes wording only; capping, retrieval behavior, the current lookup-call
9
+ limit, re-orientation, and the retrieval skill remain unchanged.
10
+ - consecutive context_lookups now default to a limit of 3 rather than 1
11
+
12
+ ## 0.9.2
13
+
14
+ - Remove inline checkpoint refs, their selection heuristics, stored locator/priority
15
+ fields, the ref-thinning cap stage, and associated prompting and replay metrics.
16
+ Keep compaction-aware, focused recovery tools and ENTRY ids returned by recovery
17
+ results for targeted follow-up. Keep output observations, head-only previews,
18
+ preview tightening, tool-only prefix folding, and destructive cap behavior.
19
+ No migration or compatibility handling for saved checkpoints is added.
20
+
21
+ ## 0.9.1
22
+
23
+ - Keep recovery tool advertisements explicitly compaction-aware while adding
24
+ question-led examples: exact earlier commands/results, provenance, conflicting
25
+ observations, and uncertainty about what was done, observed, or decided.
26
+ Distinguish locating an entry, finding a narrow passage, and reading
27
+ a specific detail at a known ENTRY id/ref. Make paging conditional on the missing
28
+ detail, including incomplete or ambiguous passages, and stop once the question
29
+ is answered; do not promote bulk expansion. Partial searches do not prove absence.
30
+ Ref locators are not verification. Retrieval code, payload limits, and defaults
31
+ are unchanged; this is a prompting experiment, not a bounded-return redesign.
32
+
33
+ - Restore the 0.8.9 lookup-first re-orientation and compaction-aware recovery
34
+ framing. Keep refs as raw-entry locators that may narrow a lookup question,
35
+ not citations or validation.
36
+ Restore explicit missing-detail cautions in the checkpoint boundary, tool
37
+ advertisements, and skill. Keep compact signatures, output observations, ref
38
+ selection, progressive capping, and paired-entry retrieval behavior unchanged.
39
+ - Return new bash previews to the first 160 encoded characters plus an omission
40
+ marker, with head-only 120/80-character cap stages. Store bounded prefixes in
41
+ version-2 tool-display records. No legacy rendering or upgrade logic is added.
42
+
43
+ ## 0.9.0
44
+
45
+ - Add progressive capping in the pure `extensions/lib/checkpoint-cap.ts` module.
46
+ Before omitting history, try 120/80-character previews, fewer lower-priority
47
+ refs, and folded adjacent tool-only prefixes, oldest first and only as needed.
48
+ Protect file paths, observed outcomes, and history-bearing refs. Preserve
49
+ independently trimmable calls after grouping. Distinguish `tools-tightened`
50
+ presentation changes from `trimmed` omissions.
51
+ - Persist versioned bounded tool-display records alongside uncapped span lines.
52
+ Later checkpoints can tighten earlier structured spans without editing stored
53
+ compactions or reinterpreting raw history. Budget increases/cap-off restore
54
+ normal rendering. Text-only legacy spans and invalid/future records remain
55
+ opaque. Retained startup reads, inherited bases, and cap-policy dialogs retain
56
+ their existing protection/behavior.
57
+
58
+ - Render compact `[Tools]:` signatures with complete file paths, requested read
59
+ ranges, payload sizes/counts, and 160-character head-and-tail bash previews.
60
+ Keep escaped newlines and shell syntax intact; omit tool-level timeout fields.
61
+ Replace new `[ok]` labels with conservative historical output observations;
62
+ retain explicit tool-error/unknown status. Recognized test/build summaries,
63
+ HTTP observations, tiny complete historical outputs, and commit hashes can
64
+ remain visible. Unlabelled calls do not imply success. Normal rendering keeps
65
+ messages separate; progressive capping may fold tool-only prefixes. No command
66
+ diffs, arbitrary output tails, or read folding.
67
+ - Add checkpoint `ref=ID` hints for write/edit payloads, truncated commands, and
68
+ likely historical observations. `context_show_entry` can open refs directly
69
+ with `includeRelated=true`, recovering matched calls and results together in
70
+ bounded pages. Ordinary single-entry retrieval stays unchanged; related-entry
71
+ indexing respects tool names, duplicate ambiguity, sequential reuse, and the
72
+ active branch. Refs do not depend on deletion inference; no ref makes no
73
+ reproducibility claim. Existing saved span lines are preserved.
74
+
75
+ - Add read-only compaction timing and headroom replays, including valid doubled
76
+ histories with remapped IDs. Record the first destructive cap at identical cut
77
+ points; keep reconstruction costs separate from timed compaction hooks. Baseline
78
+ snapshots preserve relative imports after modular source refactors. These are
79
+ local performance/evidence-retention checks, not live-model quality results.
80
+ - Known performance limitation: the final destructive fallback recounts remaining
81
+ rows after each deletion, so heavily capped histories can scale superlinearly.
82
+ Incremental size accounting is deferred; the presentation-only stages are not
83
+ subject to that repeated-recount path.
84
+
85
+ ## Earlier development notes
4
86
 
5
87
  - Raise the default lookup budget from 10 to 25 substantive search turns (75 total
6
88
  search-phase model calls, plus a final tool-free write-up). Keep the consecutive
@@ -158,4 +240,5 @@
158
240
  - Preliminary synthetic pilot figures are preserved as historical results from
159
241
  the earlier file-backed implementation, not measurements of the current implementation.
160
242
 
161
- No version has been published from this staging directory. Full evaluation is pending.
243
+ Full live-model evaluation remains pending; integration tests and local replay
244
+ benchmarks are not live-model quality measurements.
package/README.md CHANGED
@@ -72,6 +72,17 @@ earlier notes and new evidence. Prefer lookup for historical observations or to
72
72
  avoid repeating costly research; inspect project files for current contents.
73
73
  Cheap local rereads and recomputations remain reasonable.
74
74
 
75
+ Tool lines use compact signatures and head-only bash previews: the first 160
76
+ encoded characters, followed by an ellipsis when truncated. Selected historical
77
+ output observations (such as failing-test counts) replace misleading `[ok]` labels;
78
+ an unlabelled call is not proof of success. Most output and detailed payloads are
79
+ omitted. When you need details hidden by compaction, ask `context_lookup` a specific
80
+ historical question. Recovery results supply ENTRY ids for targeted follow-up;
81
+ `context_show_entry` can read a specific passage at a known ENTRY id. Start small
82
+ and continue only if the detail is missing, incomplete, or needs more context to
83
+ resolve ambiguity; stop once the question is answered. Do not expand surrounding
84
+ history by default. See [the rendering contract](docs/DESIGN.md#deterministic-checkpoint).
85
+
75
86
  File lists now distinguish source output retained in the recent tail, partial
76
87
  reads, and reads followed by tracked changes. Modified paths without retained
77
88
  read/write evidence are marked `no read-tool output in tail`; these annotations
@@ -114,14 +125,19 @@ New sessions default to verbatim.
114
125
 
115
126
  ### Control the compaction cap
116
127
 
117
- Capping of the context eventually applies to strip further elements from the checkpoint.
118
- See [how cap trimming works](docs/DESIGN.md#how-cap-trimming-works) for the removal order.
128
+ When the checkpoint exceeds its budget, capping first tightens tool presentation:
129
+ 160→120→80-character previews, then grouped tool-only prefixes. Only if those stages
130
+ cannot make it fit does it remove conversation content. `tools-tightened` marks presentation changes; `trimmed` marks actual
131
+ omissions. Earlier structured spans can be tightened in the new checkpoint without
132
+ editing their stored originals; disabling the cap restores their normal rendering.
133
+ Text-only legacy spans use a conservative fallback.
134
+ See [how cap trimming works](docs/DESIGN.md#how-cap-trimming-works) for the full order.
119
135
  This is meant as a fallback option for allowing compaction rounds to run far in excess of the intended use case, and should probably be used to allow work to be wrapped up before handing off to a new session.
120
136
  If you find that in normal usage you frequently work over the compaction cap, other compaction tools are likely to be more suitable.
121
137
 
122
138
  The default is **`warn 25%`**: a conversation-and-retained-reads budget estimated at 25% of
123
139
  the current model's context window, using **4 characters per token**, not an
124
- exact tokenizer. When content would actually be trimmed, choose **Apply trimming**,
140
+ exact tokenizer. When tightening or omission would be needed, choose **Apply trimming**,
125
141
  **Disable cap for this session**, **Change budget**, or **Cancel compaction**. Disabling persists as `off`, rather than
126
142
  bypassing just once.
127
143
 
package/docs/DESIGN.md CHANGED
@@ -12,33 +12,69 @@ extension builds a checkpoint without changing that boundary or calling a model:
12
12
  | Assistant prose | Kept, subject to the size guard. |
13
13
  | Tool calls | Short signatures with outcome labels; full arguments and outputs remain recoverable. |
14
14
  | Assistant thinking | Removed from the checkpoint; retained in the raw session. |
15
- | Tool outputs | Removed from the checkpoint except selected startup reads; all remain in the raw session. |
15
+ | Tool outputs | Mostly removed; selected bash observations and startup reads remain. All remain in raw history. |
16
16
  | Custom messages | Short type stubs marked `content removed`; bodies remain in the raw session. Managed re-orientation messages are regenerated instead. |
17
17
  | Recent conversation | Pi keeps its normal verbatim tail. |
18
18
  | Earlier compacted spans | Re-rendered chronologically, without repeated model summarization. |
19
19
  | Read/modified file lists | Cumulative operation lists with checkpoint-relative retained-evidence annotations. |
20
20
 
21
- Checkpoints label tool outcomes as `ok`, `error`, or `unknown` and remind the
22
- agent to recover missing evidence when needed. These labels describe tool
23
- results, not a guarantee that tests passed. Output removal is explained once in
24
- the checkpoint header rather than repeated beside every outcome. There is no
25
- required-document reread checklist: retained reads remain available as evidence.
26
-
27
- File-tool signatures keep complete identifying paths, made relative to the session
28
- working directory where possible. Shell commands abbreviate that directory to
29
- `.` at path boundaries, without changing raw arguments. This is display notation,
30
- not a replayable command. Read/modified file lists use the same relative paths.
31
- Write bodies become `content=<N chars>`; edit arrays become `edits=K` (individual
32
- `oldText`/`newText` arguments become character counts). Other argument previews,
33
- including bash commands, retain a 160-character JSON-encoded prefix with a single
34
- ellipsis when abbreviated. Multi-line command prefixes are not reduced to their
35
- first line. These changes affect only checkpoint signatures, never conversation
36
- prose, retained read outputs, or raw session evidence.
21
+ New tool lines use `[Tools]:` with compact display signatures:
22
+
23
+ ```text
24
+ read "src/example.ts":12-41
25
+ write "scratch.py" (2144 chars)
26
+ edit "src/example.ts" ×2
27
+ bash "uv run pytest -q 2>&1 | tail -25" → output: "3 failed, 16 passed in 0.21s"
28
+ ```
29
+
30
+ File paths remain complete and are relative to the session working directory where
31
+ possible. Read ranges record requested lines, not actual returned coverage or symbol
32
+ locations. Write bodies become sizes; edit arrays become counts (individual
33
+ `oldText`/`newText` fields become sizes). Bash omits its tool-level `timeout` argument
34
+ but retains other arguments such as `background`. Commands abbreviate the working
35
+ directory to `.` at path boundaries. New JSON-encoded previews keep the first 160
36
+ characters, followed by an ellipsis when truncated. Newlines remain escaped;
37
+ imports, redirections, and shell syntax are not rewritten. Other argument previews
38
+ remain bounded prefixes. These signatures are display notation, not replayable shell
39
+ commands. Calls normally remain separate across assistant messages. The size guard
40
+ may fold adjacent tool-only prefixes while preserving ordering and independently
41
+ removable calls. No command diffs or read folding are performed.
42
+
43
+ `[tool error]` means a safely matched result was flagged as an error; `[unknown]`
44
+ means no safely matched result/status. Plain successes have no status label; this
45
+ **does not establish exit 0 or passing tests**. Legacy `[ok]` means only that the
46
+ result was not flagged as an error. Selected bash observations appear after `→`:
47
+ reported nonzero shell status, `no output`, recognized test/build summary lines,
48
+ explicit HTTP status observations for leading curl/wget commands, or a short
49
+ error-text quote. Detectors are conservative lexical heuristics, not verdicts.
50
+ Test summaries are scanned only for recognized test/build invocations; error text
51
+ only for recognized execution commands, not leading file-read/search/git commands.
52
+ Unknown formats remain unlabelled. A status for a pipeline does not establish the
53
+ status of its individual commands. A bracketed git commit hash can also be retained.
54
+
55
+ Likely historical bash observations (network, terminal, scripts, timings) may retain
56
+ a complete text output of at most 100 characters, but not arbitrary output tails.
57
+ Media, structured-only results, and detected truncated output do not qualify as tiny
58
+ complete observations. Every quote is escaped and bounded. All observations are
59
+ historical, not proof of current state; assistant prose remains a record of claims,
60
+ not independent verification.
61
+
62
+ Only selected preparation messages supply output labels; raw history and the
63
+ retained tail do not supply missing outcomes. Stored canonical span lines remain
64
+ unchanged; their presentation in a later checkpoint may tighten under budget pressure.
65
+
66
+ When omitted observations, payloads, or provenance are needed, prefer
67
+ `context_lookup` with a specific historical question. Recovery results supply
68
+ ENTRY ids for targeted follow-up. For a specific missing passage at a known ENTRY
69
+ id, `context_show_entry` can read that entry directly; search or interpretation
70
+ remains a `context_lookup` task.
71
+ The list/grep tools remain fallbacks when lookup findings are incomplete. For
72
+ current state, inspect files. There is no required-document reread checklist.
37
73
 
38
74
  All newly compacted custom messages follow the same stub policy, regardless of
39
75
  extension, display setting, or content format. Long type names are abbreviated
40
76
  like tool-call arguments. This applies even with the cap disabled. Previously
41
- saved spans are not rewritten; older custom-message bodies may remain in them.
77
+ saved canonical spans are not rewritten; older custom-message bodies may remain in them.
42
78
 
43
79
  ### File-list evidence annotations
44
80
 
@@ -111,20 +147,50 @@ original branch, not from its summary prose.
111
147
 
112
148
  #### How cap trimming works
113
149
 
114
- **User messages are prioritized**—capping is not simply an oldest-first cutoff:
115
-
116
- 1. Remove non-user content, oldest first.
117
- 2. If still over budget, shorten long user messages to marked prefix stubs,
118
- oldest first.
119
- 3. As a last resort, remove the oldest remaining content, including user messages.
150
+ The pure renderer/size guard lives in `extensions/lib/checkpoint-cap.ts`, separately
151
+ from Pi hooks, cap-policy dialogs, and session access in `extensions/index.ts`.
152
+ It accepts canonical span data and a line budget and never mutates its inputs.
153
+ **Presentation reductions precede history omission.** Each rung walks oldest first
154
+ across all eligible spans, stopping as soon as the budget fits:
155
+
156
+ 1. Shorten bash previews from 160 to 120 encoded characters.
157
+ 2. If still over budget, shorten them to 80 characters.
158
+ 3. Fold repeated `[Tools]:` prefixes across adjacent tool-only messages in the
159
+ same span. Do not cross prose, custom messages, user messages, or span boundaries.
160
+ 4. Only then remove non-user content, oldest first. Structured tool batches remain
161
+ independently trimmable by call even after prefixes have been folded.
162
+ 5. Shorten long user messages to marked prefix stubs, oldest first.
163
+ 6. As a last resort, remove the oldest remaining content, including user messages.
164
+
165
+ File paths, read ranges, tool status, and output observations are not shortened by
166
+ presentation stages. User and assistant prose remains verbatim until the destructive
167
+ fallback. `tools-tightened="true"` identifies presentation changes without omitted
168
+ prose/calls; `trimmed="true"` and a recovery note identify actual omissions or user
169
+ text shortening. Both attributes can occur on one span. Empty spans are not marked
170
+ unless they became empty through omission.
171
+
172
+ New spans store versioned, bounded display records in `details.span.tools`, alongside
173
+ their normal uncapped `lines`. Records contain signature fragments, original encoded
174
+ command prefixes, and annotations—not unbounded commands, write/edit payloads, or
175
+ full tool outputs. Smaller previews are always derived from
176
+ the same canonical prefix, never from a previous 120/80-character rendering.
177
+ Version-2 records distinguish a truncated prefix from a complete short command.
178
+ Stored compaction entries are not edited: a later checkpoint re-renders its earlier
179
+ spans for the current budget. Increasing the budget or disabling the cap restores
180
+ normal previews; reload/resume/fork follow the active branch's records.
181
+
182
+ Only records that exactly reproduce the stored canonical tool line can be tightened.
183
+ Legacy text-only spans, unsupported versions, and malformed/mismatched records stay
184
+ opaque and use the conservative omission fallback. They are not regex-parsed or
185
+ reconstructed from current raw history, which might differ from the projected
186
+ content originally compacted. Inherited model-summary/opaque bases remain fixed.
120
187
 
121
188
  Retained startup reads count as fixed budget overhead and are never trimmed.
122
189
  Like an inherited base, they can exceed the budget by themselves; in that case
123
190
  the extension warns and preserves them. The conversation-line budget still has
124
- a 500-character minimum. Every span changed by the cap carries `trimmed="true"`
125
- and a recovery note, including partial line removal and shortened user messages.
126
- An originally empty span is not marked as trimmed. Originals remain recoverable
127
- from the session.
191
+ a 500-character minimum. Space for span annotations is reserved in the size guard.
192
+ Originals remain recoverable from the session; cap settings and warn/on/off dialog
193
+ behavior are unchanged.
128
194
 
129
195
 
130
196
  ### Session-backed lookup
@@ -199,14 +265,14 @@ files through filesystem tools. This restriction does not apply to user-requeste
199
265
  session audits, debugging, or cross-session analysis, which can use ordinary file
200
266
  tools. Lookup itself still cannot search other sessions or abandoned branches.
201
267
 
202
- The extension registers a subagent lookup and three direct-search fallback tools:
268
+ The extension registers a subagent lookup and three bounded direct-recovery tools:
203
269
 
204
270
  | Tool | Purpose |
205
271
  |---|---|
206
- | `context_lookup` | Recover specific historical details from the full raw session branch. Accepts only `question`. |
207
- | `context_list_entries` | Fallback: list entry ids, roles, timestamps, and previews. |
208
- | `context_grep` | Fallback: regex-search the raw branch with surrounding lines and entry attribution. |
209
- | `context_show_entry` | Fallback: retrieve an entry by id. |
272
+ | `context_lookup` | Recover outputs, findings, decisions, reasoning, and provenance hidden by compaction, including conflicts with new evidence. A subagent searches the raw branch and returns relevant findings. Accepts only `question`. |
273
+ | `context_list_entries` | Post-compaction fallback: list raw session ENTRY headers and previews. |
274
+ | `context_grep` | Post-compaction fallback: regex-search raw history, including thinking and tool outputs, with entry attribution. |
275
+ | `context_show_entry` | Recover a specific detail hidden by compaction at a known ENTRY id, or after lookup. Optional `includeRelated` recovers matched call/result entries only when that counterpart is needed. |
210
276
 
211
277
  For example, ask the agent to recover the build error observed before compaction.
212
278
  It can call `context_lookup` with:
@@ -217,6 +283,32 @@ It can call `context_lookup` with:
217
283
  }
218
284
  ```
219
285
 
286
+ ENTRY ids returned by recovery tools can narrow subsequent `context_lookup`
287
+ questions or identify a specific passage for `context_show_entry`. Prefer lookup
288
+ when search or interpretation is needed.
289
+ Lookup, listing, and grep use concise capability-oriented advertisements. The
290
+ `context_show_entry` advertisement retains small-first retrieval and continuation
291
+ only while the requested detail is missing, incomplete, or needs more context to
292
+ resolve ambiguity; stop once the question is answered. The skill retains bounded
293
+ recovery guidance, including that a partial search does not establish absence.
294
+ Advertisement changes do not change payload limits, defaults, or retrieval behavior,
295
+ and do not guarantee small total responses. No automatic decision sweep or new
296
+ re-orientation instruction is added.
297
+
298
+ Ordinary entry retrieval defaults to `includeRelated=false`. Related expansion
299
+ remains available to the subagent and direct entry tool; it is one-hop and
300
+ chronological: a result includes its originating assistant entry (including any
301
+ sibling calls), not sibling outputs; an assistant includes its matched results.
302
+ Relations come from raw call IDs and matching tool names, never transcript text.
303
+ Ambiguous duplicate IDs, orphan results, and mismatched tool names do not establish
304
+ relations. Sequential ID reuse is matched separately. Branch scoping and source
305
+ overrides apply equally to both modes.
306
+
307
+ Related expansions share the usual character/line guards. Keep `includeRelated`
308
+ unchanged when following an offset; changing it starts a different retrieval and
309
+ spends a substantive subagent search turn. An expansion of an unfinished call may
310
+ change if results arrive later; restart paging if its source changes.
311
+
220
312
  The subagent searches in its own context and returns findings with entry
221
313
  references. Its raw search results stay out of the main conversation. If findings
222
314
  are incomplete, the fallback tools run the same searches directly; their results
@@ -15,7 +15,7 @@
15
15
  * Valid continuation-only turns are exempt;
16
16
  * total search-phase calls capped at 3x this,
17
17
  * plus one final write-up on exhaustion
18
- * MECH_COMPACT_LOOKUP_MAX_CALLS consecutive lookup limit (default 1;
18
+ * MECH_COMPACT_LOOKUP_MAX_CALLS consecutive lookup limit (default 3;
19
19
  * 0 = unlimited). Non-recovery tool results,
20
20
  * bash executions, or user messages reset it.
21
21
  * Fallback tools neither count nor reset it.
@@ -33,6 +33,8 @@ import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-work
33
33
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
34
34
  import { buildSessionProjection, SessionManager } from "@earendil-works/pi-coding-agent";
35
35
  import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
36
+ import { capSpans, commandPreview, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
37
+ import type { SpanContent, ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
36
38
 
37
39
  // ============================================================================
38
40
  // Configuration
@@ -72,7 +74,7 @@ function percentFromEnv(name: string, fallback: number): number {
72
74
  function lookupMaxCallsFromEnv(): number {
73
75
  const raw = process.env.MECH_COMPACT_LOOKUP_MAX_CALLS?.trim();
74
76
  const n = raw && /^\d+$/.test(raw) ? Number(raw) : NaN;
75
- return Number.isSafeInteger(n) && n >= 0 ? n : 1;
77
+ return Number.isSafeInteger(n) && n >= 0 ? n : 3;
76
78
  }
77
79
 
78
80
  const cfg = {
@@ -82,7 +84,7 @@ const cfg = {
82
84
  lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 25),
83
85
  lookupMaxCalls: lookupMaxCallsFromEnv(),
84
86
  lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
85
- argSnippetChars: 160,
87
+ argSnippetChars: NORMAL_PREVIEW_CHARS,
86
88
  listMaxChars: 12_000,
87
89
  grepMaxChars: 12_000,
88
90
  showEntryMaxChars: 24_000,
@@ -294,6 +296,28 @@ interface TranscriptIndexSection {
294
296
  startLine: number;
295
297
  }
296
298
 
299
+ // Pair only selected messages, by call id AND tool name. Ambiguous concurrent
300
+ // ids stay unknown; sequential reuse is allowed after consuming a result.
301
+ function pairedToolResults(messages: AgentMessage[]): Map<object, Record<string, any>> {
302
+ const results = new Map<object, Record<string, any>>();
303
+ const pending = new Map<string, { block: object; name: string } | null>();
304
+ for (const message of messages) {
305
+ const m = message as unknown as Record<string, any>;
306
+ if (m.role === "assistant") {
307
+ for (const block of m.content ?? []) {
308
+ if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
309
+ pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
310
+ }
311
+ } else if (m.role === "toolResult") {
312
+ const call = pending.get(m.toolCallId);
313
+ if (!call || call.name !== m.toolName) continue;
314
+ results.set(call.block, m);
315
+ pending.delete(m.toolCallId);
316
+ }
317
+ }
318
+ return results;
319
+ }
320
+
297
321
  interface TranscriptIndexEntry {
298
322
  id: string;
299
323
  type: string;
@@ -303,6 +327,8 @@ interface TranscriptIndexEntry {
303
327
  /** 1-based line number of the last line of the block (inclusive) */
304
328
  endLine: number;
305
329
  sections?: TranscriptIndexSection[];
330
+ /** Raw, unambiguously matched call/result entries; never parsed from text. */
331
+ relatedIds?: string[];
306
332
  }
307
333
 
308
334
  function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index: TranscriptIndexEntry[] } {
@@ -414,6 +440,25 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
414
440
  if (b.sections && b.sections.length > 0) e.sections = b.sections.map((s) => ({ kind: s.kind, startLine: b.hrIdx + s.rel + 3 }));
415
441
  return e;
416
442
  });
443
+ const byMessage = new Map<object, string>();
444
+ const byCall = new Map<object, string>();
445
+ const messages: AgentMessage[] = [];
446
+ for (const entry of entries) {
447
+ if (entry.type !== "message") continue;
448
+ messages.push(entry.message);
449
+ byMessage.set(entry.message, entry.id);
450
+ if (entry.message.role === "assistant")
451
+ for (const block of entry.message.content ?? [])
452
+ if (block.type === "toolCall") byCall.set(block, entry.id);
453
+ }
454
+ const byId = new Map(index.map((entry) => [entry.id, entry]));
455
+ for (const [call, result] of pairedToolResults(messages)) {
456
+ const callId = byCall.get(call), resultId = byMessage.get(result);
457
+ if (!callId || !resultId) continue;
458
+ const callEntry = byId.get(callId)!, resultEntry = byId.get(resultId)!;
459
+ (callEntry.relatedIds ??= []).push(resultId);
460
+ resultEntry.relatedIds = [callId];
461
+ }
417
462
  return { lines, index };
418
463
  }
419
464
 
@@ -444,47 +489,128 @@ function argumentSnippet(value: unknown): string {
444
489
  return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
445
490
  }
446
491
 
447
- function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
492
+ function toolSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): ToolStub {
493
+ const a = args ?? {};
494
+ if (!["read", "write", "edit", "bash"].includes(name))
495
+ return { prefix: `${name}(${Object.entries(a).map(([k, v]) => `${k}=${argumentSnippet(v)}`).join(", ")})`, suffix: "" };
448
496
  const parts: string[] = [];
449
- for (const [k, v] of Object.entries(args ?? {})) {
450
- let s: string;
451
- if (["read", "write", "edit"].includes(name) && k === "path" && typeof v === "string")
452
- s = JSON.stringify(checkpointPath(v, cwd)); // Keep the whole identifying path.
497
+ let command: ToolStub["command"];
498
+ const fileTool = ["read", "write", "edit"].includes(name) && typeof a.path === "string";
499
+ let base = fileTool ? `${name} ${JSON.stringify(checkpointPath(a.path as string, cwd))}` : name;
500
+ const range = name === "read" && fileTool &&
501
+ (a.offset === undefined || (Number.isSafeInteger(a.offset) && (a.offset as number) > 0)) &&
502
+ (a.limit === undefined || (Number.isSafeInteger(a.limit) && (a.limit as number) > 0));
503
+ if (range && (a.offset !== undefined || a.limit !== undefined)) {
504
+ const start = (a.offset as number | undefined) ?? 1;
505
+ const end = a.limit === undefined ? "" : start + (a.limit as number) - 1;
506
+ base += `:${start}-${end}`; // Requested range, not a claim about returned lines.
507
+ }
508
+ for (const [k, v] of Object.entries(a)) {
509
+ if (fileTool && k === "path") continue;
510
+ if (range && (k === "offset" || k === "limit")) continue;
511
+ if (name === "bash" && k === "timeout") continue;
512
+ if (name === "bash" && k === "command" && typeof v === "string")
513
+ command = commandPreview(JSON.stringify(checkpointCommand(v, cwd)));
453
514
  else if (name === "write" && k === "content" && typeof v === "string")
454
- s = `<${v.length} chars>`;
515
+ parts.push(`(${v.length} chars)`);
455
516
  else if (name === "edit" && k === "edits" && Array.isArray(v))
456
- s = String(v.length);
517
+ parts.push(`×${v.length}`);
457
518
  else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
458
- s = `<${v.length} chars>`;
459
- else
460
- s = argumentSnippet(name === "bash" && k === "command" && typeof v === "string" ? checkpointCommand(v, cwd) : v);
461
- parts.push(`${k}=${s}`);
519
+ parts.push(`${k}=<${v.length} chars>`);
520
+ else parts.push(`${k}=${argumentSnippet(v)}`);
462
521
  }
463
- return `${name}(${parts.join(", ")})`;
522
+ return command ? { prefix: `${base} `, command, suffix: parts.length ? ` ${parts.join(" ")}` : "" }
523
+ : { prefix: [base, ...parts].join(" "), suffix: "" };
464
524
  }
465
525
 
466
- function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
467
- // Pair calls with later results in Pi's selected messages only. Never infer
468
- // outcomes from result text, assistant claims, or another branch/the kept tail.
469
- const outcomes = new Map<object, "ok" | "error">();
470
- const pending = new Map<string, { block: object; name: string } | null>();
471
- for (const msg of messages) {
472
- const m = msg as unknown as Record<string, any>;
473
- if (m.role === "assistant") {
474
- for (const block of m.content ?? []) {
475
- if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
476
- // Concurrent duplicate IDs cannot be attributed safely. Sequential
477
- // reuse is fine once the preceding call's result has been consumed.
478
- pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
479
- }
480
- } else if (m.role === "toolResult") {
481
- const call = pending.get(m.toolCallId);
482
- if (!call || call.name !== m.toolName) continue;
483
- if (typeof m.isError === "boolean") outcomes.set(call.block, m.isError ? "error" : "ok");
484
- pending.delete(m.toolCallId);
485
- }
526
+ function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
527
+ return renderToolStub(toolSignature(name, args, cwd));
528
+ }
529
+
530
+ // Conservative lexical categories for selected output observations. These do
531
+ // not parse shell syntax or establish whether a command succeeded.
532
+ function commandHints(command: string): { tests: boolean; network: boolean; historical: boolean } {
533
+ const core = command.replace(/^\s*cd\s+(?:"[^"\n]*"|'[^'\n]*'|[^\s;&|]+)\s*&&\s*/, "").trimStart();
534
+ const tests = /^(?:(?:uv run |(?:\S*\/)?python[\d.]* -m )?pytest\b|(?:\S*\/)?pytest\b|(?:npm|pnpm|yarn) (?:run )?(?:test|build)\b|node --test\b|(?:\.\/)?gradlew\b|cargo (?:test|build)\b|go (?:test|build)\b|dotnet (?:test|build)\b|mvn (?:test|verify|package)\b)/.test(core);
535
+ const network = /^(?:curl|wget)\b/.test(core);
536
+ const readOnly = /^(?:cat|sed|awk|rg|grep|head|tail|find|ls|man|git)\b/.test(core);
537
+ const historical = !readOnly && (network || /^(?:timeout\s+\S+\s+)?tmux\b/.test(core) ||
538
+ /^(?:\S*\/)?(?:python[\d.]*|node|ruby|perl)\b[^\n]*(?:\s-[ce]\b|\s-\s*<<)/.test(core) ||
539
+ /^(?:uv run )?(?:\S*\/)?(?:python[\d.]*|node)\b/.test(core) ||
540
+ /^(?:time|hyperfine)\b|\b(?:bench(?:mark)?|timeit)\b/.test(core));
541
+ return { tests, network, historical };
542
+ }
543
+
544
+ function observationQuote(text: string): string {
545
+ if (JSON.stringify(text).length <= cfg.argSnippetChars) return JSON.stringify(text);
546
+ // Unlike a generic argument prefix, keep output quotations closed and escaped
547
+ // even when the source contains control characters or ends at a surrogate.
548
+ let end = Math.min(text.length, cfg.argSnippetChars);
549
+ while (JSON.stringify(text.slice(0, end) + "…").length > cfg.argSnippetChars) end--;
550
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
551
+ return JSON.stringify(text.slice(0, end) + "…");
552
+ }
553
+
554
+ function bashOutputLabel(command: string, result: Record<string, any>): string {
555
+ const content = result.content;
556
+ // Do not treat an image, structured-only result, or truncation notice as a
557
+ // tiny complete text observation. Summaries below quote selected text only.
558
+ const textOnly = typeof content === "string" || (Array.isArray(content) && content.length > 0 && content.every((b) => b?.type === "text" && typeof b.text === "string"));
559
+ if (!textOnly) return "";
560
+ const raw = textOf(content).text;
561
+ const structuredExit = result.structuredContent?.exit_code;
562
+ const hasStructuredExit = Number.isSafeInteger(structuredExit);
563
+ const suffix = /(?:^|\n)Command exited with code (-?\d+)\s*$/.exec(raw);
564
+ // Successful reads can print a fixture containing the wrapper's exact text.
565
+ // Prefer explicit metadata; trust a legacy nonzero footer only on tool error.
566
+ const exit = suffix && (hasStructuredExit ? Number(suffix[1]) === structuredExit : result.isError === true) ? suffix : undefined;
567
+ const bodyText = exit ? raw.slice(0, exit.index) : raw;
568
+ const body = bodyText.trim();
569
+ const partial = result.details?.truncation?.truncated === true || /\[(?:Output truncated|Showing last |Showing lines )/i.test(body);
570
+ const labels: string[] = [];
571
+ const reportedExit = hasStructuredExit ? structuredExit : exit ? Number(exit[1]) : undefined;
572
+ const exitCode = Number.isSafeInteger(reportedExit) ? reportedExit : undefined;
573
+ if (exitCode !== undefined && exitCode !== 0) labels.push(`exit ${exitCode}`); // Reported shell status, NOT pipeline/test status.
574
+ if (!partial && (bodyText === "" || body === "(no output)")) return [...labels, "no output"].join("; ");
575
+ const hints = commandHints(command);
576
+ const lines = body.replace(/\x1b\[[0-9;]*m/g, "").split("\n");
577
+ let observed: string[] = [];
578
+ if (hints.tests) {
579
+ observed = lines.filter((line) =>
580
+ /^=+ .*\b\d+ (?:passed|failed|errors?|skipped|xfailed)\b.*=+$/.test(line.trim()) ||
581
+ /^(?:\d+ (?:passed|failed|errors?|skipped|xfailed|deselected|warnings?)(?:, )?)+ in [\d.]+s$/.test(line.trim()) ||
582
+ /^(?:ℹ|#) (?:pass|fail) \d+$/.test(line.trim()) ||
583
+ /^BUILD (?:SUCCESSFUL|FAILED)\b/.test(line.trim()) ||
584
+ /^(?:PASS|FAIL): \d+\/\d+$/.test(line.trim())).slice(-3);
585
+ }
586
+ if (hints.network) {
587
+ const codes = [...body.matchAll(/(?:^|\n)(?:HTTP\/[\d.]+\s+([1-5]\d\d)\b|http(?:_code)?[=: ]\s*([1-5]\d\d)\b)/gi)].map((m) => m[1] ?? m[2]);
588
+ if (codes.length) labels.push(`output: http ${codes.slice(0, 4).join(",")}${codes.length > 4 ? ",…" : ""}`);
486
589
  }
590
+ // Only recognized execution commands get error-text scanning. In particular,
591
+ // never extract test/error labels from file reads, searches, or git views.
592
+ if (!observed.length && (hints.tests || hints.historical)) {
593
+ const errors = lines.filter((line) => line.trim()).slice(-6).filter((line) =>
594
+ /^(?:\s*\w*(?:Error|Exception):|Traceback \(most recent call last\):|error(?:\[\w+\])?:|fatal:)|command not found/.test(line));
595
+ observed = errors.slice(-1);
596
+ }
597
+ if (observed.length) labels.push(`output: ${observed.map((line) => observationQuote(line.trim())).join(" / ")}`);
598
+ else if (!labels.some((label) => label.startsWith("output:")) && hints.historical && !partial &&
599
+ bodyText.length <= 100 && JSON.stringify(bodyText).length <= cfg.argSnippetChars)
600
+ labels.push(`output: ${JSON.stringify(bodyText)}`);
601
+ // A commit hash is useful provenance, but only extract the git-generated
602
+ // bracketed form, not arbitrary lines that merely start with hex digits.
603
+ if (/^(?:git\b|.*&&\s*git\b)/.test(command) && /\bgit commit\b/.test(command)) {
604
+ const hash = /^\[[^\]\n]+ ([0-9a-f]{7,40})\]/m.exec(body)?.[1];
605
+ if (hash) labels.push(`commit ${hash}`);
606
+ }
607
+ return labels.join("; ");
608
+ }
609
+
610
+ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
611
+ const results = pairedToolResults(messages);
487
612
  const lines: string[] = [];
613
+ const tools: ToolLines = { version: 2, lines: [] };
488
614
  for (const msg of messages) {
489
615
  const m = msg as unknown as Record<string, any>;
490
616
  switch (msg.role) {
@@ -495,15 +621,26 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
495
621
  }
496
622
  case "assistant": {
497
623
  let prose = "";
498
- const calls: string[] = [];
624
+ const calls: ToolStub[] = [];
499
625
  for (const block of m.content ?? []) {
500
626
  if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
501
- else if (block.type === "toolCall")
502
- calls.push(`${toolCallSignature(String(block.name), block.arguments, cwd)} [${outcomes.get(block) ?? "unknown"}]`);
627
+ else if (block.type === "toolCall") {
628
+ const name = String(block.name), args = block.arguments ?? {};
629
+ const result = results.get(block);
630
+ const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
631
+ const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
632
+ const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
633
+ const stub = toolSignature(name, args, cwd);
634
+ stub.suffix += status + (label ? ` → ${label}` : "");
635
+ calls.push(stub);
636
+ }
503
637
  // thinking blocks: removed by design (kept in the session)
504
638
  }
505
639
  if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
506
- if (calls.length > 0) lines.push(`[Assistant tool calls]: ${calls.join("; ")}`);
640
+ if (calls.length > 0) {
641
+ tools.lines.push({ index: lines.length, calls, mergeable: !prose.trim() });
642
+ lines.push(renderToolLine(calls));
643
+ }
507
644
  break;
508
645
  }
509
646
  case "toolResult":
@@ -526,7 +663,7 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
526
663
  break;
527
664
  }
528
665
  }
529
- return lines;
666
+ return { lines, ...(tools.lines.length ? { tools } : {}) };
530
667
  }
531
668
 
532
669
  // Startup reference retention is a lexical heuristic, not an interpretation of
@@ -640,7 +777,7 @@ function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstK
640
777
  const retained = state.reads.filter((r) => !tail.has(r.entryId));
641
778
  if (retained.length === 0) return "";
642
779
  return ["### Retained startup reads",
643
- "Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool-call status labels refer to the conversation spans, where outputs are removed, not these retained copies.",
780
+ "Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool-call status labels refer to the conversation spans, not these retained copies.",
644
781
  ...retained.map((r) => `<retained-read entry=${JSON.stringify(r.entryId)} path=${JSON.stringify(r.path)} offset=${r.offset ?? 1}${r.limit === undefined ? "" : ` limit=${r.limit}`}>
645
782
  ${r.text.join("\n")}
646
783
  </retained-read>`),
@@ -770,15 +907,17 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
770
907
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
771
908
  * (the base is opaque; the session holds the raw history).
772
909
  */
910
+ type StoredSpan = SpanContent & { at: string; reason: string; from?: string; to?: string };
911
+
773
912
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
774
913
  base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
775
- spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[];
914
+ spans: StoredSpan[];
776
915
  } {
777
916
  const spanDetails = (e: SessionEntry) => {
778
917
  if (e.type !== "compaction") return undefined;
779
918
  const d = (e as { details?: Record<string, any> }).details;
780
919
  if (!d || d.kind !== MECH_KIND || !Array.isArray(d.span?.lines)) return undefined;
781
- return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[] };
920
+ return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[]; tools?: ToolLines };
782
921
  };
783
922
  let baseIdx = -1;
784
923
  for (let i = branchEntries.length - 1; i >= 0; i--) {
@@ -798,7 +937,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
798
937
  summary: (baseEntry as { summary?: string }).summary ?? "",
799
938
  }
800
939
  : null;
801
- const spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[] = [];
940
+ const spans: StoredSpan[] = [];
802
941
  for (let i = Math.max(baseIdx + 1, 0); i < branchEntries.length; i++) {
803
942
  const sd = spanDetails(branchEntries[i]);
804
943
  if (sd)
@@ -810,50 +949,13 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
810
949
  from: typeof sd.from === "string" && sd.from !== "" ? sd.from : undefined,
811
950
  to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
812
951
  lines: sd.lines,
952
+ tools: sd.tools,
813
953
  });
814
954
  }
815
955
  return { base, spans };
816
956
  }
817
957
 
818
- /**
819
- * Size guard across ordered spans (oldest first): if the total line budget is
820
- * exceeded, (1) drop the oldest non-user lines, (2) stub each oversized user
821
- * line at most once in a single forward pass (never re-stub → no loops),
822
- * (3) drop the oldest remaining lines until under budget. Everything dropped
823
- * remains in the session.
824
- */
825
- function capSpans(spans: string[][], budget: number): string[][] {
826
- const items: { span: number; line: string }[] = spans.flatMap((lines, span) => lines.map((line) => ({ span, line })));
827
- let size = items.reduce((a, it) => a + it.line.length + 1, 0);
828
- const over = () => size > budget;
829
- const remove = (i: number) => {
830
- size -= items[i].line.length + 1;
831
- items.splice(i, 1);
832
- };
833
-
834
- // 1) drop oldest non-user lines (flat order = span order = oldest first;
835
- // terminates: each pass removes a line or advances i)
836
- for (let i = 0; i < items.length && over(); ) {
837
- if (items[i].line.startsWith("[User]:")) i++;
838
- else remove(i);
839
- }
840
- // 2) stub user lines, oldest first, each at most once (terminates: single forward pass)
841
- for (let i = 0; i < items.length && over(); i++) {
842
- const line = items[i].line;
843
- if (!line.startsWith("[User]:") || line.length <= 120) continue;
844
- const stub = `${line.slice(0, 120)}…[truncated +${line.length - 120} chars — use context_lookup]`;
845
- if (stub.length >= line.length) continue; // stubbing would not shrink it; step 3 drops it
846
- size += stub.length - line.length;
847
- items[i] = { ...items[i], line: stub };
848
- }
849
- // 3) drop oldest remaining lines until under budget (terminates: removes one per iteration)
850
- while (over() && items.length > 0) remove(0);
851
-
852
- return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
853
- }
854
-
855
958
  const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
856
- const RECOVERY_TRIGGERS = "Ask `context_lookup` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence.";
857
959
  const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
858
960
  const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
859
961
  const RECOVERY_FILESYSTEM_RULE = "For recovery of details hidden by compaction, do not read or grep raw session JSONL files through filesystem tools; use the recovery tools instead.";
@@ -867,7 +969,7 @@ const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier
867
969
 
868
970
  const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Prefer \`context_lookup\` with a specific historical question: a subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SCOPE_RULE} If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`; follow their pagination instructions for more detail. ${RECOVERY_FILESYSTEM_RULE}`;
869
971
 
870
- const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; use `context_lookup` when you need that historical evidence or its provenance, and inspect the source when you need current state.";
972
+ const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs and file lists omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Use `context_lookup` for omitted observations or provenance; inspect sources for current state.";
871
973
 
872
974
  const REORIENT_MESSAGE = "transparent-compact:reorient";
873
975
  const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead. If lookup findings are incomplete, use \`context_list_entries\`, \`context_grep\`, or \`context_show_entry\`, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE} Keep these evidence/recovery rules in force as work continues.`;
@@ -921,6 +1023,7 @@ async function buildMechanicalSummary(opts: {
921
1023
  branchEntries: SessionEntry[];
922
1024
  now: string;
923
1025
  spanLines: string[]; // this compaction's own span, un-capped
1026
+ spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
924
1027
  spanFrom?: string; // ISO timestamp of the first summarised message
925
1028
  spanTo?: string; // ISO timestamp of the last summarised message
926
1029
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
@@ -932,7 +1035,8 @@ async function buildMechanicalSummary(opts: {
932
1035
  chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
933
1036
  }): Promise<string | undefined> {
934
1037
  const { base, spans } = collectBaseAndSpans(opts.branchEntries);
935
- const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo, lines: opts.spanLines }];
1038
+ const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1039
+ lines: opts.spanLines, tools: opts.spanTools }];
936
1040
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
937
1041
 
938
1042
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -943,7 +1047,7 @@ async function buildMechanicalSummary(opts: {
943
1047
  let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
944
1048
  if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
945
1049
  overhead += allSpans.reduce(
946
- (a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
1050
+ (a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + TIGHTENED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
947
1051
  0,
948
1052
  );
949
1053
  // Closing line: where the verbatim (uncompacted) tail begins. Spans end at
@@ -964,16 +1068,17 @@ async function buildMechanicalSummary(opts: {
964
1068
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
965
1069
  if (maxChars !== undefined && retainedReads.length > maxChars)
966
1070
  opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
967
- const capped = maxChars === undefined ? lines : capSpans(lines, Math.max(500, maxChars - overhead));
1071
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
968
1072
 
969
1073
  const blocks: string[] = [];
970
1074
  if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
971
- capped.forEach((lines, i) => {
1075
+ capped.lines.forEach((lines, i) => {
972
1076
  const s = allSpans[i];
973
- const trimmed = lines.length !== s.lines.length || lines.some((line, j) => line !== s.lines[j]);
1077
+ const trimmed = capped.trimmed[i];
974
1078
  const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
1079
+ const attributes = (capped.tightened[i] ? TIGHTENED_ATTR : "") + (trimmed ? SPAN_TRIMMED_ATTR : "");
975
1080
  blocks.push([
976
- trimmed ? `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>` : open,
1081
+ attributes ? `${open.slice(0, -1)}${attributes}>` : open,
977
1082
  ...(trimmed ? [SPAN_TRIMMED_NOTE] : []),
978
1083
  ...lines,
979
1084
  SPAN_CLOSE,
@@ -989,9 +1094,10 @@ async function buildMechanicalSummary(opts: {
989
1094
  opts.notify(MIXED_CONTEXT_WARNING);
990
1095
  }
991
1096
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
992
- parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming; tool calls are kept as one-line signatures. Paths under the session working directory are shown relative to it (as `.` in shell commands). Write contents and edit payloads are replaced by sizes/counts; other argument snippets keep up to 160 characters followed by an ellipsis when abbreviated. Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
993
- parts.push("- Tool status: ok = result not flagged as an error; error = result flagged as an error; unknown = no safely matched result/status. Output content is removed in all cases. ok does not prove a command or tests passed. Calls without a status in older spans have unknown outcomes.");
994
- parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Previously saved spans are unchanged.");
1097
+ parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming. Retained prose is a record of what was said, not verification of its claims. Tool signatures are display notation, not replayable shell commands: paths under the working directory become relative (`.` in commands); read ranges are requested lines; write/edit payloads become sizes/counts. New bash previews keep the first 160 encoded characters, followed by … when truncated, with escaped newlines. Thinking and most output are removed; selected output observations remain after →.");
1098
+ parts.push("- [tool error] means the result was flagged as an error; [unknown] means no safely matched result/status. Unlabelled does NOT establish exit 0 or passing tests. → exit N is a reported shell status; output: quotes/extracts selected output, not an inferred verdict. Everything shown is historical. Legacy [ok] only means not flagged as a tool error; legacy calls without status are unknown.");
1099
+ parts.push("- Under size pressure, `tools-tightened` marks 120/80-character previews or grouped tool-only lines. Conversation prose and tool calls are retained unless `trimmed` is also marked. Tightening stops as soon as the budget fits; outcome observations and identifying file paths are not shortened by these stages.");
1100
+ parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Stored canonical spans are unchanged; their presentation may tighten under the cap.");
995
1101
  parts.push(
996
1102
  "- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that. The retained verbatim conversation begins after the explicit boundary marker at the end of this checkpoint.",
997
1103
  );
@@ -1189,16 +1295,22 @@ function grepTranscript(transcripts: Transcript[], opts: GrepOptions, onContinua
1189
1295
  return out.join("\n\n") + notice;
1190
1296
  }
1191
1297
 
1192
- function showEntry(transcripts: Transcript[], opts: { id: string; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1298
+ function showEntry(transcripts: Transcript[], opts: { id: string; includeRelated?: boolean; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1193
1299
  const targets = opts.file ? transcripts.filter((d) => d.name === opts.file) : transcripts;
1194
1300
  const out: string[] = [];
1195
1301
  const headers: string[] = [];
1196
1302
  for (const d of targets) {
1197
1303
  const e = d.index.find((x) => x.id === opts.id);
1198
1304
  if (!e) continue;
1199
- const block = d.lines.slice(e.startLine - 2, e.endLine); // includes the rule before the header
1200
- out.push(`### ${d.name}\n${block.join("\n")}`);
1201
- headers.push(`${d.name}: ${d.lines[e.startLine - 1]}`);
1305
+ const ids = new Set([e.id, ...(opts.includeRelated === true ? e.relatedIds ?? [] : [])]);
1306
+ // Chronological, one-hop expansion: a result includes its originating
1307
+ // assistant, not all sibling outputs. An assistant includes its results.
1308
+ for (const entry of d.index) {
1309
+ if (!ids.has(entry.id)) continue;
1310
+ const block = d.lines.slice(entry.startLine - 2, entry.endLine);
1311
+ out.push(`### ${d.name}\n${block.join("\n")}`);
1312
+ headers.push(`${d.name}: ${d.lines[entry.startLine - 1]}`);
1313
+ }
1202
1314
  }
1203
1315
  return out.length ? pageText(out.join("\n\n"), {
1204
1316
  offset: opts.offset, maxChars: cfg.showEntryMaxChars,
@@ -1222,7 +1334,8 @@ const GREP_FIELDS = {
1222
1334
  throughEntry: THROUGH_ENTRY_FIELD,
1223
1335
  };
1224
1336
  const SHOW_FIELDS = {
1225
- id: Type.String({ description: "Entry id" }),
1337
+ id: Type.String({ description: "ENTRY id" }),
1338
+ includeRelated: Type.Optional(Type.Boolean({ description: "Include unambiguously matched tool call/result entries (default false). Keep unchanged when paging." })),
1226
1339
  maxLines: Type.Optional(Type.Integer({ minimum: 1, description: "Max lines per page (default 400); character limit also applies" })),
1227
1340
  offset: OFFSET_FIELD,
1228
1341
  };
@@ -1248,7 +1361,7 @@ const LOOKUP_SYSTEM_PROMPT = `You are a context-lookup subagent for a coding age
1248
1361
  You have three tools:
1249
1362
  - list_entries: paginated overview of entries (id, role, timestamp, preview)
1250
1363
  - grep: paginated transcript search; matches come with surrounding lines and authoritative ENTRY attribution
1251
- - show_entry: retrieve an entry by id in bounded pages
1364
+ - show_entry: retrieve an entry by id in bounded pages; includeRelated=true also shows its matched tool call/result
1252
1365
 
1253
1366
  Search tools bound each response, not the underlying history. A partial page is not the entire evidence, but you do NOT need to exhaust every page. Follow continuation parameters only when omitted content is needed to answer the question, keeping all other search/context parameters unchanged. Narrow an overly broad search rather than paging through irrelevant matches. Stop paging once you have sufficient relevant evidence.
1254
1367
 
@@ -1289,6 +1402,7 @@ function lookupPageKey(name: string, args: Record<string, any>): string | undefi
1289
1402
  break;
1290
1403
  case "show_entry":
1291
1404
  fields = [typeof args.id === "string" ? args.id : undefined, string("file"),
1405
+ typeof (args.includeRelated ?? false) === "boolean" ? (args.includeRelated ?? false) : undefined,
1292
1406
  number("maxLines", 400, 1), number("offset", 0)];
1293
1407
  break;
1294
1408
  default:
@@ -1319,7 +1433,7 @@ async function runLookupSubagent(opts: {
1319
1433
  },
1320
1434
  {
1321
1435
  name: "show_entry",
1322
- description: "Retrieve an indexed entry by ENTRY id in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset only if omitted content is needed; a page may not contain the entire entry.",
1436
+ description: "Retrieve an indexed entry by ENTRY id, optionally with matched tool call/result entries (includeRelated=true), in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset only if omitted content is needed; keep includeRelated unchanged when paging.",
1323
1437
  parameters: Type.Object({ ...SHOW_FIELDS, file: FILE_FIELD }),
1324
1438
  },
1325
1439
  ];
@@ -1524,7 +1638,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1524
1638
  pi.registerTool({
1525
1639
  name: "context_grep",
1526
1640
  label: "Context: grep",
1527
- description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and authoritative entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1641
+ description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1528
1642
  promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
1529
1643
  parameters: Type.Object(GREP_FIELDS),
1530
1644
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
@@ -1534,8 +1648,8 @@ function registerDirectTools(pi: ExtensionAPI): void {
1534
1648
  pi.registerTool({
1535
1649
  name: "context_show_entry",
1536
1650
  label: "Context: show entry",
1537
- description: pre + "Retrieve an indexed session entry by ENTRY id (from context_list_entries or context_grep) in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset for the rest; a page may not contain the entire entry.",
1538
- promptSnippet: "Fallback: retrieve this conversation's entries for post-compaction recovery",
1651
+ description: "Read a known raw session entry to recover a specific detail hidden by compaction. Use an ENTRY id returned by context_lookup, context_grep, or context_list_entries. Prefer context_lookup when search or interpretation is needed; same scope as context_lookup. Start with a small maxLines. Optional includeRelated=true includes matched tool call/result entries; use it only if the counterpart is needed. Returns up to 24000 payload characters and maxLines lines per page, plus attribution/cursor notes; a page may not contain the entire entry. Continue with the reported offset only if the requested detail is missing, incomplete, or needs more context to resolve ambiguity, keeping includeRelated unchanged. Stop once the question is answered; do not expand surrounding history by default.",
1652
+ promptSnippet: "Recover a specific detail hidden by compaction at a known ENTRY id in this conversation.",
1539
1653
  parameters: Type.Object(SHOW_FIELDS),
1540
1654
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1541
1655
  return run(ctx, (t) => showEntry(t, params));
@@ -1707,7 +1821,8 @@ export default function (pi: ExtensionAPI) {
1707
1821
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1708
1822
  const spanFrom = toIso(msgTs(allMessages[0]));
1709
1823
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1710
- const spanLines = summarizeMessages(allMessages, ctx.cwd);
1824
+ const span = summarizeMessages(allMessages, ctx.cwd);
1825
+ const spanLines = span.lines;
1711
1826
 
1712
1827
  // 3) Freeze startup references after the second user prompt, then carry
1713
1828
  // their original outputs forward outside the trimmable conversation spans.
@@ -1718,6 +1833,7 @@ export default function (pi: ExtensionAPI) {
1718
1833
  branchEntries,
1719
1834
  now: nowIso,
1720
1835
  spanLines,
1836
+ spanTools: span.tools,
1721
1837
  spanFrom,
1722
1838
  spanTo,
1723
1839
  firstKeptEntryId: preparation.firstKeptEntryId,
@@ -1747,7 +1863,8 @@ export default function (pi: ExtensionAPI) {
1747
1863
  startupReads: retained,
1748
1864
  // Only this compaction's own span (un-capped lines). Earlier spans
1749
1865
  // are re-rendered from the earlier entries' details — no nesting.
1750
- span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
1866
+ span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
1867
+ lines: spanLines, ...(span.tools ? { tools: span.tools } : {}) },
1751
1868
  },
1752
1869
  },
1753
1870
  };
@@ -1766,7 +1883,7 @@ export default function (pi: ExtensionAPI) {
1766
1883
  label: "Context lookup",
1767
1884
  executionMode: "sequential",
1768
1885
  description:
1769
- `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. ${RECOVERY_TRIGGERS} A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} If findings are incomplete, use context_list_entries, context_grep, or context_show_entry, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE}`,
1886
+ `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. Ask \`context_lookup\` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence. A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} If findings are incomplete, use context_list_entries, context_grep, or context_show_entry, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE}`,
1770
1887
  promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
1771
1888
  parameters: Type.Object({
1772
1889
  question: Type.String({ description: "A specific question about earlier in this conversation: an output, source of a finding, reason for a decision, or evidence behind notes that conflict with new observations." }),
@@ -0,0 +1,178 @@
1
+ /** Pure checkpoint presentation and progressive size guard. No Pi, filesystem,
2
+ * model calls, or session mutation. Canonical span lines/records are never edited.
3
+ */
4
+ export const TOOL_PREFIX = "[Tools]: ";
5
+ export const NORMAL_PREVIEW_CHARS = 160;
6
+ export const TIGHTENED_ATTR = ' tools-tightened="true"';
7
+
8
+ // Encoded display fragments, NOT full commands or executable arguments.
9
+ // Retain the original prefix for every smaller head-only preview.
10
+ export interface CommandPreview { head: string; truncated?: boolean }
11
+ export interface ToolStub {
12
+ prefix: string;
13
+ command?: CommandPreview;
14
+ suffix: string;
15
+ }
16
+ export interface ToolLine {
17
+ index: number;
18
+ calls: ToolStub[];
19
+ /** Both adjacent messages must be tool-only before prefixes may be folded. */
20
+ mergeable: boolean;
21
+ }
22
+ export interface ToolLines { version: 2; lines: ToolLine[] }
23
+ export interface SpanContent { lines: string[]; tools?: ToolLines }
24
+ export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[] }
25
+
26
+ function headPrefix(text: string, max: number): string {
27
+ let end = Math.min(text.length, max);
28
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
29
+ return text.slice(0, end);
30
+ }
31
+ export function commandPreview(encoded: string): CommandPreview {
32
+ return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
33
+ : { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
34
+ }
35
+ export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
36
+ return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
37
+ }
38
+ export function renderToolStub(stub: ToolStub, max = NORMAL_PREVIEW_CHARS): string {
39
+ return stub.prefix + (stub.command ? renderCommand(stub.command, max) : "") + stub.suffix;
40
+ }
41
+ export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS): string {
42
+ return TOOL_PREFIX + calls.map((call) => renderToolStub(call, max)).join("; ");
43
+ }
44
+
45
+ // Stored records are optional/versioned. Require exact canonical round-tripping
46
+ // before using one; missing or invalid records leave text opaque.
47
+ function toolRecords(span: SpanContent): Map<number, ToolLine> {
48
+ const records = new Map<number, ToolLine>();
49
+ try {
50
+ const tools = span.tools;
51
+ if (!tools || tools.version !== 2 || !Array.isArray(tools.lines)) return records;
52
+ const seen = new Set<number>();
53
+ for (const record of tools.lines) {
54
+ if (!record || !Number.isSafeInteger(record.index) || record.index < 0 || record.index >= span.lines.length) continue;
55
+ if (seen.has(record.index)) { records.delete(record.index); continue; }
56
+ seen.add(record.index);
57
+ if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length) continue;
58
+ const valid = record.calls.every((call) => {
59
+ if (!call || typeof call.prefix !== "string" || typeof call.suffix !== "string") return false;
60
+ const p = call.command;
61
+ if (p === undefined) return true;
62
+ if (!p || typeof p.head !== "string") return false;
63
+ return p.head.length <= NORMAL_PREVIEW_CHARS &&
64
+ (p.truncated === undefined || typeof p.truncated === "boolean") &&
65
+ (p.truncated !== true || p.head.length >= NORMAL_PREVIEW_CHARS - 1);
66
+ });
67
+ if (valid && renderToolLine(record.calls) === span.lines[record.index]) records.set(record.index, record);
68
+ }
69
+ } catch { return new Map(); }
70
+ return records;
71
+ }
72
+
73
+ interface Row {
74
+ index: number;
75
+ text: string;
76
+ calls?: ToolStub[];
77
+ mergeable: boolean;
78
+ preview: number;
79
+ foldPrefix: boolean;
80
+ tightened: boolean;
81
+ }
82
+
83
+ /** Stop as soon as the budget fits: 120-char previews, then 80, adjacent
84
+ * tool-only prefixes, and finally the historical destructive cap.
85
+ * Every rung walks oldest first, across all spans (not just the new one).
86
+ */
87
+ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
88
+ const tightened = spans.map(() => false), trimmed = spans.map(() => false);
89
+ let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0);
90
+ if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed };
91
+ const states = spans.map((span) => {
92
+ const records = toolRecords(span);
93
+ return span.lines.map((text, index): Row => {
94
+ const record = records.get(index);
95
+ return { index, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
96
+ preview: NORMAL_PREVIEW_CHARS, foldPrefix: false, tightened: false };
97
+ });
98
+ });
99
+ const joined = (rows: Row[], i: number) => i > 0 && rows[i].foldPrefix && rows[i].calls && rows[i - 1].calls &&
100
+ rows[i].mergeable && rows[i - 1].mergeable && rows[i].index === rows[i - 1].index + 1;
101
+ const measure = () => states.reduce((n, rows) => n + rows.reduce((s, row, i) =>
102
+ s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0);
103
+ const finish = (): CappedSpans => ({
104
+ lines: states.map((rows, span) => {
105
+ const lines: string[] = [];
106
+ for (let i = 0; i < rows.length; i++) {
107
+ const row = rows[i];
108
+ if (joined(rows, i)) lines[lines.length - 1] += `; ${row.text.slice(TOOL_PREFIX.length)}`;
109
+ else lines.push(row.text);
110
+ if (row.tightened || joined(rows, i)) tightened[span] = true;
111
+ }
112
+ return lines;
113
+ }), tightened, trimmed,
114
+ });
115
+ const render = (row: Row) => renderToolLine(row.calls!, row.preview);
116
+ const update = (row: Row) => {
117
+ const text = render(row);
118
+ if (text.length < row.text.length) {
119
+ size += text.length - row.text.length;
120
+ row.text = text;
121
+ row.tightened = true;
122
+ }
123
+ };
124
+ for (const max of [120, 80]) {
125
+ for (const rows of states) for (const row of rows) {
126
+ if (!row.calls?.some((call) => call.command)) continue;
127
+ row.preview = max;
128
+ update(row);
129
+ if (size <= budget) return finish();
130
+ }
131
+ }
132
+ for (const rows of states) for (let i = 1; i < rows.length; i++) {
133
+ const row = rows[i];
134
+ row.foldPrefix = true;
135
+ if (joined(rows, i)) size -= TOOL_PREFIX.length - 1;
136
+ if (size <= budget) return finish();
137
+ }
138
+
139
+ // No presentation-only rung fits. Keep calls independently removable even
140
+ // when their prefixes are folded; never cap a giant concatenated tool line.
141
+ for (let span = 0; span < states.length && size > budget; span++) {
142
+ const rows = states[span];
143
+ for (let i = 0; i < rows.length && size > budget;) {
144
+ const row = rows[i];
145
+ if (row.text.startsWith("[User]:")) { i++; continue; }
146
+ if (row.calls && row.calls.length > 1) {
147
+ row.calls.shift();
148
+ row.text = render(row);
149
+ } else rows.splice(i, 1);
150
+ trimmed[span] = true;
151
+ size = measure();
152
+ }
153
+ }
154
+ // Stub each oversized user line once. Canonical lines remain untouched, so
155
+ // later checkpoints never shorten an already shortened presentation again.
156
+ for (let span = 0; span < states.length && size > budget; span++) {
157
+ for (const row of states[span]) {
158
+ if (size <= budget) break;
159
+ const line = row.text;
160
+ if (!line.startsWith("[User]:") || line.length <= 120) continue;
161
+ let end = 120;
162
+ if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
163
+ const stub = `${line.slice(0, end)}…[truncated +${line.length - end} chars — use context_lookup]`;
164
+ if (stub.length >= line.length) continue;
165
+ row.text = stub;
166
+ trimmed[span] = true;
167
+ size = measure();
168
+ }
169
+ }
170
+ for (let span = 0; span < states.length && size > budget; span++) {
171
+ while (states[span].length && size > budget) {
172
+ states[span].shift();
173
+ trimmed[span] = true;
174
+ size = measure();
175
+ }
176
+ }
177
+ return finish();
178
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.8.9",
3
+ "version": "0.9.3",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -12,6 +12,11 @@ history, including recorded tool outputs and your reasoning, is preserved in the
12
12
  session and can be retrieved. Retained startup reads and the uncompacted tail
13
13
  remain available as evidence; recover only hidden information needed for the task.
14
14
 
15
+ Under size pressure, `tools-tightened` on its own marks reduced tool previews
16
+ or grouped tool-only lines, without omitted conversation prose or calls. If
17
+ `trimmed` is also present, content was omitted or user text was shortened. Neither means that the original evidence
18
+ was never recorded; recover task-relevant missing detail through the tools below.
19
+
15
20
  Use the recovery tools for history established by this conversation or its checkpoint,
16
21
  not project discovery, requirements never supplied, other sessions, or abandoned branches.
17
22
  For unfamiliar project details or missing requirements, inspect project files or
@@ -25,7 +30,7 @@ This skill pairs with the `@foliox/transparent-compact-pi` extension, which prov
25
30
 
26
31
  - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Selected startup read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders and a recap follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
27
32
  - **`context_lookup`** — the preferred first step for this recovery workflow: a subagent searches the full raw session branch in its **own** context and returns relevant findings. At lookup time, the extension mechanically renders the branch into entry-anchored text with an authoritative entry/section index, in memory.
28
- - **Bounded fallback tools** — if those findings are incomplete, use `context_list_entries`, `context_grep`, and `context_show_entry` for direct evidence recovery. Their results enter this conversation. For recovery of details hidden by compaction, these are the permitted fallback, not filesystem access to session files.
33
+ - **Bounded direct tools** — use `context_show_entry` for a specific detail hidden by compaction at a known ENTRY id returned by a recovery tool. If lookup findings are incomplete, use `context_list_entries` to locate an entry, `context_grep` to find a narrow passage, or `context_show_entry` to inspect a known entry. Their raw results enter this conversation; retrieve only what the question needs. For recovery of details hidden by compaction, these are the permitted direct tools, not filesystem access to session files.
29
34
 
30
35
  Pi normally saves sessions under `~/.pi/agent/sessions/`; custom session locations also work. In-memory sessions retain history only while the process lives and cannot be resumed after exit.
31
36
 
@@ -37,6 +42,10 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
37
42
  - You are unsure where an earlier finding came from, what a command actually printed, or why you reached a conclusion.
38
43
  - Earlier notes conflict with new evidence and you need to check the historical evidence behind them.
39
44
 
45
+ Tool stubs and file lists do not preserve the full supporting material. Most output
46
+ and detailed payloads are omitted. Inline observations are historical, not verification
47
+ of unshown details or current state. Unlabelled calls do not establish exit 0 or passing tests.
48
+
40
49
  Ask `context_lookup` a **specific historical question** to recover hidden supporting
41
50
  evidence. This can avoid repeating slow or unreliable research. For example:
42
51
  "Where did our earlier Holi 2026 date come from: a
@@ -55,6 +64,13 @@ published source or our own computation? Include the observed output and ENTRY i
55
64
  context_lookup({ question: "What exact error did the earlier test run return for the N=7 case? Include the ENTRY id and observed tool output." })
56
65
  ```
57
66
 
67
+ You may include an ENTRY id from an earlier recovery result in the question to
68
+ narrow the search. If you already know the ENTRY id and only need a specific
69
+ passage, `context_show_entry` can read that entry directly. Prefer
70
+ `context_lookup` when search or interpretation is needed. For post-compaction
71
+ recovery, continue paging only if the requested detail is missing, incomplete, or
72
+ needs more context to resolve ambiguity; stop once the question is answered.
73
+
58
74
  For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically. It does **not** search abandoned branches or unrelated sessions. If the detail is absent, report that limitation instead of claiming it was recovered or widening this recovery search through filesystem tools.
59
75
 
60
76
  A study harness may configure `MECH_COMPACT_LOOKUP_SESSION_FILE` to make the extension search a full session rather than a pruned fork. This is extension configuration, not a tool argument or a file the main agent should read. Do not discover or change the override to broaden a lookup.
@@ -69,10 +85,12 @@ the same recovery episode. Narration and thinking do not reset it either. Only
69
85
  a tool result outside the four recovery tools, a user message, or a bash
70
86
  execution resets the limit.
71
87
 
72
- Search responses are pages, not necessarily complete evidence. Follow pages
73
- only when omitted content is needed; do not exhaust every match or entry merely
74
- because a continuation is available. Keep other parameters unchanged and use
75
- all continuation parameters printed at the end of a limited page:
88
+ Search responses are pages, not necessarily complete evidence. Continue only
89
+ when the needed detail is missing, incomplete, or needs more context to resolve
90
+ ambiguity; do not exhaust every match or entry merely because a continuation is
91
+ available. A partial search does not establish that something never happened.
92
+ Keep other parameters unchanged and use all continuation parameters printed at
93
+ the end of a limited page:
76
94
 
77
95
  - Listings and entry retrieval: `offset` counts characters (UTF-16 code units)
78
96
  in the rendered listing or entry, starting at 0.
@@ -80,6 +98,10 @@ all continuation parameters printed at the end of a limited page:
80
98
  the context of an oversized match. Grep reports how many matches remain.
81
99
  - `maxLines` and `maxMatches` limit a page, not the backing history. Increasing
82
100
  them does not remove the character guard. Use the reported cursor instead.
101
+ - `context_show_entry` defaults to a single entry. `includeRelated=true` adds
102
+ unambiguously matched tool call/result entries in chronological order. Keep
103
+ this flag unchanged when paging. A result expands to its originating assistant,
104
+ not sibling outputs; an assistant expands to its matched results.
83
105
 
84
106
  Listing/grep cursors also report `throughEntry`: retain this original last-entry
85
107
  id on subsequent pages, so newly appended calls/results cannot keep expanding