@foliox/transparent-compact-pi 0.8.5 → 0.8.7

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
@@ -2,16 +2,58 @@
2
2
 
3
3
  ## Unreleased — initial release preparation
4
4
 
5
+ - Advertise recovery positively as retrieving history hidden by compaction, with
6
+ explicit provenance and contradiction triggers in the lookup description, skill,
7
+ and post-compaction reminders. Distinguish historical observations from current
8
+ source contents; allow cheap rereads/recomputations and avoid blanket fact
9
+ re-verification. Re-orientation leads with ordinary input restoration and makes
10
+ lookup conditional on a hidden historical need, rather than reusing the tool
11
+ advertisement. Shorten fallback descriptions by referring to lookup's scope
12
+ rather than repeating it. Keep recovery scope, fallback, and filesystem boundaries.
13
+
14
+ - Make compaction tool signatures leaner: short outcome labels, relative project
15
+ paths, write sizes and edit counts instead of payload previews, and a single
16
+ ellipsis for abbreviated arguments. Keep bash previews at 160 characters and
17
+ preserve complete file-tool paths. Bound user bash-execution stubs too. Raw
18
+ history, retained outputs, and user/assistant prose are unchanged.
19
+ - Mark all size-trimmed spans, including partial removals and shortened user
20
+ messages; no longer label originally empty spans as trimmed.
21
+
22
+ - Scope recovery guidance to specific earlier details hidden by compaction in the
23
+ current conversation, not startup, project discovery, or missing requirements.
24
+ Filesystem restrictions apply only to that recovery workflow, not user-requested
25
+ session audits, debugging, or cross-session analysis. Remove the misleading
26
+ pre-task skill trigger and align lookup, fallback, and checkpoint descriptions.
27
+ - Remove obsolete recovery-interface guidance and legacy metadata rendering.
28
+ Agent-facing instructions describe only the current session-backed tools;
29
+ independent exports are documented through Pi's `/export`.
30
+
31
+ - Rename the extension entry point to `extensions/index.ts` so Pi's compact
32
+ extension list shows the npm package name without a `:transparent-compact.ts` suffix.
33
+
5
34
  - Deterministic checkpoints retain user messages and assistant prose, subject to
6
35
  a size guard; thinking, full tool outputs, and arguments remain in Pi's session.
36
+ - Startup text reads whose names appear in AGENTS/CLAUDE instructions are retained
37
+ verbatim, including pagination chunks. Selection scans the first user-prompt
38
+ interval without model calls, agent action or filesystem reads, then freezes
39
+ after the second prompt. Later compactions carry the outputs forward separately
40
+ from conversation spans, without duplicating reads still in the recent tail.
41
+ Retained reads count as fixed cap overhead but are never silently trimmed.
42
+ - Remove the required-document and edit-target reread checklist. Recovery guidance
43
+ now asks only for missing task-relevant evidence; retained reads remain usable.
44
+ - Newly compacted custom messages become bounded type stubs marked `content
45
+ removed`, regardless of their source extension. Bodies remain recoverable from
46
+ raw session history; previously saved spans are not rewritten. Managed
47
+ re-orientation messages continue to be regenerated instead.
7
48
  - Tool signatures record per-call `ok`, `error`, or `unknown` outcomes from
8
- matched tool-result metadata, always marking output as removed. Missing or
49
+ matched tool-result metadata; the header explains that outputs are removed. Missing or
9
50
  ambiguous outcomes are never inferred, including unlabelled older spans.
10
- - Read-file entries explicitly mark content as removed; a closing evidence rule
11
- requires lookup or re-reading before relying on removed outputs or document rules.
51
+ - Read-file entries distinguish retained startup reads from removed content; a closing
52
+ evidence rule directs historical evidence/provenance questions to lookup and
53
+ current-state questions to the source.
12
54
  - The instruction envelope now has recovery explanations before all compacted
13
- spans, one evidence-boundary warning after them, and a mandatory numbered
14
- re-orientation checklist plus brief recovery recap after the retained tail.
55
+ spans, one evidence-boundary warning after them, and numbered
56
+ recovery reminders plus brief recovery recap after the retained tail.
15
57
  The checklist is persisted and remains active after the first response. Later
16
58
  compactions regenerate the envelope: old generated checklists are neither
17
59
  summarized into spans nor replayed from the retained tail. Raw originals remain
@@ -29,7 +71,8 @@
29
71
  after applying a summary cannot restore earlier model-summarized context to verbatim.
30
72
  - Session-backed `context_lookup` searches the full raw active branch across all
31
73
  compactions, using an in-memory transcript with authoritative entry attribution.
32
- - No local transcript dump, temporary file, ownership matching, or pruning.
74
+ - Transcript rendering uses retained session history in memory, without additional
75
+ files, ownership matching, or pruning.
33
76
  - Optional `MECH_COMPACT_LOOKUP_SESSION_FILE` supports full-session recovery from
34
77
  pruned harness forks, with explicit failures for invalid overrides.
35
78
  - Subagent lookup provides list, grep, and entry-retrieval tools; exhausted lookups
@@ -83,8 +126,7 @@
83
126
  Non-interactive mode warns and caps; cancellation never falls through to summary.
84
127
  For unattended interactive sessions, use `/cap-compaction on` to avoid waiting
85
128
  for trim dialogs. The `warn` default and conversion factor are unchanged.
86
- - Removed `/dump-context`, `dump_context`, and the `dumpDir` lookup argument;
87
- old dump-directory and git-ignore warning settings are unused.
129
+ - Removed obsolete file-backed recovery interfaces and their configuration.
88
130
  - Bundled `context-retrieval` skill describes session-backed evidence recovery,
89
131
  branch scope, historical provenance, and re-verification after compaction.
90
132
  - Deterministic tests cover session recovery, overrides, attribution, size guards,
@@ -95,6 +137,6 @@
95
137
  cursor-error recovery, truncation boundaries, provider caching options, and
96
138
  real Pi agent-turn persistence ordering with a stubbed model (no live inference).
97
139
  - Preliminary synthetic pilot figures are preserved as historical results from
98
- the dump-based implementation, not measurements of the current implementation.
140
+ the earlier file-backed implementation, not measurements of the current implementation.
99
141
 
100
142
  No version has been published from this staging directory. Full evaluation is pending.
package/README.md CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  Deterministic context compaction for [Pi](https://pi.dev/), with session-backed
4
4
  recovery. By default, replaces Pi's model-generated compaction summary with a verbatim
5
- compaction, with a checkpoint built mechanically from conversation text. Thinking and tool outputs are removed
6
- from the active model context, while user inputs, assistant text, and tool call stubs are retained verbatim.
5
+ compaction, with a checkpoint built mechanically from conversation text. Thinking and most tool outputs are removed
6
+ from the active model context, while user inputs, assistant text and selected startup reads are retained verbatim.
7
+ Tool calls and custom messages are reduced to short stubs; custom-message bodies remain recoverable from the session.
7
8
  Verbatim compaction itself makes no model call. When a missing detail is needed, `context_lookup` runs a subagent over the session's
8
9
  full raw branch and returns only relevant findings.
9
10
  The goal is to let the agent withstand many (but finite) rounds of compaction without the copy-of-a-copy degradation of model-summary compaction, which is exacerbated in sub-frontier models.
@@ -44,6 +45,9 @@ or from a downloaded or cloned checkout:
44
45
  pi install /absolute/path/to/transparent-compact
45
46
  ```
46
47
 
48
+ The extension entry point is `extensions/index.ts`, so Pi's compact extension list
49
+ shows `@foliox/transparent-compact-pi` without a filename suffix for npm installs.
50
+
47
51
  ## Usage
48
52
 
49
53
  Pi's compaction uses transparent-compact by default once the extension is loaded.
@@ -54,13 +58,35 @@ To compact manually:
54
58
  ```
55
59
 
56
60
  The checkpoint begins with an explanation and full recovery instructions, and
57
- ends with an evidence-boundary warning. A mandatory re-orientation checklist and
61
+ ends with an evidence-boundary warning. Task-relevant recovery reminders and a
58
62
  brief recovery recap follow **the retained recent history and any pending new
59
63
  user input**. They are saved in the session and remain available on later turns.
60
64
  After another compaction, only the current checklist is presented: older generated
61
65
  checklists are excluded from compacted spans and the retained tail. This is
62
66
  instruction delivery, not a guarantee of model compliance.
63
67
 
68
+ Compaction hides earlier details from the model's view; recorded history remains
69
+ retrievable. Recovery guidance explicitly names uncertain provenance (where a
70
+ finding came from or why a conclusion was reached) and contradictions between
71
+ earlier notes and new evidence. Prefer lookup for historical observations or to
72
+ avoid repeating costly research; inspect project files for current contents.
73
+ Cheap local rereads and recomputations remain reasonable.
74
+
75
+ ### Automatic startup-read retention
76
+
77
+ Successful text reads between the first and second user prompts are retained when
78
+ their paths or filenames appear in AGENTS.md / CLAUDE.md instructions. Selection
79
+ is purely mechanical: no model call, agent tagging, or extra filesystem reads.
80
+ Original output chunks, including paginated reads, survive in a separate checkpoint
81
+ section and carry forward across later compactions. Copies still in the recent
82
+ tail are not duplicated. If compaction happens before the second prompt, collection
83
+ continues until that prompt arrives.
84
+
85
+ This is a literal filename-matching heuristic, not an interpretation of required
86
+ reading. It does not capture every possible reference or fill in incomplete reads.
87
+ The agent is no longer given a required-document reread checklist; recovery is for
88
+ missing task-relevant evidence. See [selection details](docs/DESIGN.md#retained-startup-reads).
89
+
64
90
  ### Select the compaction method
65
91
 
66
92
  ```text
@@ -85,7 +111,7 @@ See [how cap trimming works](docs/DESIGN.md#how-cap-trimming-works) for the remo
85
111
  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.
86
112
  If you find that in normal usage you frequently work over the compaction cap, other compaction tools are likely to be more suitable.
87
113
 
88
- The default is **`warn 25%`**: a conversation-section budget estimated at 25% of
114
+ The default is **`warn 25%`**: a conversation-and-retained-reads budget estimated at 25% of
89
115
  the current model's context window, using **4 characters per token**, not an
90
116
  exact tokenizer. When content would actually be trimmed, choose **Apply trimming**,
91
117
  **Disable cap for this session**, **Change budget**, or **Cancel compaction**. Disabling persists as `off`, rather than
@@ -112,8 +138,10 @@ Tokens are estimated with `ceil(chars / 4)`, not an exact tokenizer. For a
112
138
  characters.
113
139
 
114
140
  The budget is a size guard, not a guarantee that the whole model context fits.
115
- Instructions and file lists remain outside it. Disabling the cap
116
- still removes thinking and tool outputs and abbreviates tool-call signatures.
141
+ Instructions and file lists remain outside it. Retained startup reads count as
142
+ fixed overhead but are never trimmed; if they alone exceed the budget, the
143
+ extension warns and keeps them. Disabling the cap still removes thinking and
144
+ unselected tool outputs and abbreviates tool-call signatures.
117
145
  It may leave too much context for the model, particularly during overflow recovery.
118
146
 
119
147
  With no interactive UI, `warn` emits a warning and applies the cap. TUI and
@@ -131,7 +159,7 @@ starting Pi:
131
159
 
132
160
  | Variable | Default | Meaning |
133
161
  |---|---|---|
134
- | `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset (uses percentage budget) | Initial conversation-section character budget override; takes precedence over the percentage setting. |
162
+ | `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset (uses percentage budget) | Initial conversation-and-retained-reads character budget override; takes precedence over the percentage setting. |
135
163
  | `MECH_COMPACT_MAX_SUMMARY_PERCENT` | `25` | Initial percentage of the model's context window, using estimated tokens. Accepts numbers greater than 0 and at most 100, including decimals; invalid values fall back to 25. |
136
164
  | `MECH_COMPACT_LOOKUP_MODEL` | Session model | Optional `provider/modelId` for lookups; must support tool calls and be available in Pi. An unresolved model falls back to the session model. |
137
165
  | `MECH_COMPACT_LOOKUP_TURNS` | `10` | Maximum substantive search turns. Valid continuation-only turns are exempt; total search-phase model calls are capped at 3× this budget (30 by default), plus one tool-free write-up on exhaustion. |
@@ -166,8 +194,8 @@ migration. The override is extension configuration, not a tool argument or a
166
194
  filesystem search route for the main agent.
167
195
 
168
196
  The character budget is not a token limit or a hard cap on the whole checkpoint.
169
- Instructions and file lists sit outside the conversation section; an inherited
170
- base is uncapped and the line budget has a 500-character minimum. Tune it
197
+ Instructions and file lists sit outside the budget; an inherited base and retained
198
+ startup reads are uncapped, and the line budget has a 500-character minimum. Tune it
171
199
  alongside the model's context window and Pi's `compaction.keepRecentTokens`.
172
200
 
173
201
  ### Local inference engines
package/docs/DESIGN.md CHANGED
@@ -12,14 +12,66 @@ 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; retained in the raw session. |
15
+ | Tool outputs | Removed from the checkpoint except selected startup reads; all remain in the raw session. |
16
+ | Custom messages | Short type stubs marked `content removed`; bodies remain in the raw session. Managed re-orientation messages are regenerated instead. |
16
17
  | Recent conversation | Pi keeps its normal verbatim tail. |
17
18
  | Earlier compacted spans | Re-rendered chronologically, without repeated model summarization. |
18
- | Read/modified file lists | Carried forward, with file contents marked as removed. |
19
+ | Read/modified file lists | Carried forward, distinguishing retained startup reads from removed content. |
19
20
 
20
21
  Checkpoints label tool outcomes as `ok`, `error`, or `unknown` and remind the
21
- agent to recover missing evidence and re-read required documents before relying
22
- on them. These labels describe tool results, not a guarantee that tests passed.
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.
37
+
38
+ All newly compacted custom messages follow the same stub policy, regardless of
39
+ extension, display setting, or content format. Long type names are abbreviated
40
+ 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.
42
+
43
+ ### Retained startup reads
44
+
45
+ On the first verbatim compaction, the extension scans successful text-only `read`
46
+ call/result pairs between the first and second user messages on the active branch.
47
+ It retains outputs whose file paths or bare names occur literally in AGENTS/CLAUDE
48
+ context files supplied by Pi, or in AGENTS/CLAUDE files read during that interval.
49
+ `AGENTS.override.md` is recognized too. Named project-instruction blocks in the
50
+ rendered system prompt provide a fallback when structured context files are not
51
+ available. No files are opened and no model or agent action is involved.
52
+
53
+ Matching accepts absolute paths, paths relative to the working directory or
54
+ instruction file, and standalone basenames. It rejects substrings of other paths
55
+ or filenames. A bare basename can select multiple same-named files. This is a
56
+ lexical heuristic, not a required-reading parser: optional links can qualify;
57
+ indirect references, shell reads, nested tool calls and reads after the second
58
+ user message do not. Custom messages do not close the startup interval.
59
+
60
+ All selected output chunks are preserved verbatim, with entry IDs, paths, offsets
61
+ and limits. Pagination/truncation notices are retained too; retention never
62
+ invents missing pages or claims a partial read is a complete document. Failed,
63
+ ambiguous and non-text results are excluded. Selection respects explicit context
64
+ omissions/replacements. It does not check on-disk freshness.
65
+
66
+ The selection is stored in compaction details, separately from conversation spans.
67
+ Subsequent verbatim compactions carry it forward unchanged, without re-compacting
68
+ checkpoint text. If the second user message has not arrived yet, selection remains
69
+ open: later compactions scan the startup interval again and add newly qualifying
70
+ reads until it closes. Reads still in the uncompacted tail are not duplicated in
71
+ the checkpoint; they move into its retained-read section when the cut passes them.
72
+ Reload, resume and branch navigation follow the stored state on the active branch.
73
+ An older checkpoint without retention metadata initializes selection from the
74
+ original branch, not from its summary prose.
23
75
 
24
76
  #### How cap trimming works
25
77
 
@@ -30,8 +82,13 @@ on them. These labels describe tool results, not a guarantee that tests passed.
30
82
  oldest first.
31
83
  3. As a last resort, remove the oldest remaining content, including user messages.
32
84
 
33
- Trimming stops once the budget is satisfied. Originals remain recoverable from
34
- the session.
85
+ Retained startup reads count as fixed budget overhead and are never trimmed.
86
+ Like an inherited base, they can exceed the budget by themselves; in that case
87
+ the extension warns and preserves them. The conversation-line budget still has
88
+ a 500-character minimum. Every span changed by the cap carries `trimmed="true"`
89
+ and a recovery note, including partial line removal and shortened user messages.
90
+ An originally empty span is not marked as trimmed. Originals remain recoverable
91
+ from the session.
35
92
 
36
93
 
37
94
  ### Session-backed lookup
@@ -72,6 +129,33 @@ by provider.
72
129
 
73
130
  ### Recover historical details
74
131
 
132
+ Compaction hides earlier details from the model's current view; the recorded history,
133
+ including tool outputs and reasoning, remains in the session. Recovery can retrieve
134
+ specific outputs, trace where an earlier finding came from or why a conclusion was
135
+ reached, and check historical evidence when earlier notes conflict with new evidence.
136
+ These triggers are advertised in the tool description and conditionally explained
137
+ in post-compaction reminders, not just in the skill body. Reminders lead with
138
+ restoring task-relevant inputs, current-file reads, and cheap recomputation;
139
+ compaction alone is not a lookup trigger. Advertising and re-orientation use
140
+ separate wording. The skill description also names provenance and contradictions.
141
+ This is guidance, not a guarantee of model compliance.
142
+
143
+ Re-read project files for their current contents. Prefer lookup for what was
144
+ observed earlier or to avoid repeating slow external research or expensive
145
+ computations; cheap local rereads (including downloaded sources) and recomputations
146
+ remain reasonable. Current external facts may require fresh research. Retrieval
147
+ establishes what was recorded, not whether an earlier conclusion was correct.
148
+
149
+ Use recovery for history established by this conversation or its checkpoint, not
150
+ project discovery, requirements never supplied, other sessions, or abandoned branches.
151
+ For unfamiliar project details or missing requirements, inspect project files or
152
+ ask the user instead.
153
+
154
+ For this recovery workflow, use the recovery tools rather than reading raw session
155
+ files through filesystem tools. This restriction does not apply to user-requested
156
+ session audits, debugging, or cross-session analysis, which can use ordinary file
157
+ tools. Lookup itself still cannot search other sessions or abandoned branches.
158
+
75
159
  The extension registers a subagent lookup and three direct-search fallback tools:
76
160
 
77
161
  | Tool | Purpose |
@@ -111,23 +195,24 @@ instructions that must be prominent at the actual point of resumption:
111
195
 
112
196
  ```text
113
197
  Checkpoint introduction: what was removed + full recovery instructions
114
- All compacted spans (oldest first), then read/modified file lists
198
+ All compacted spans (oldest first), then retained startup reads and file lists
115
199
  One evidence-boundary warning + start-of-verbatim-tail marker
116
200
  Retained verbatim tail
117
201
  Any pending new user input
118
- Mandatory re-orientation checklist + brief recovery recap
202
+ Task-relevant recovery reminders + brief recovery recap
119
203
  ```
120
204
 
121
- The numbered checklist requires identifying documents mandated by system,
122
- developer and applicable project instructions, then re-reading each in its
123
- entirety before task planning or changes. For this step, a document is required
124
- reading if and only if those instructions explicitly instruct the agent to read
125
- it; merely mentioning or linking a document does not qualify. Grep matches, selected sections,
126
- summaries and reading only edit targets explicitly do not satisfy this step;
127
- truncated reads must continue to the end, and unavailable documents must be
128
- reported rather than silently skipped. It also requires restoring missing inputs
129
- rather than repeating completed writes, inspecting Git state, re-reading files
130
- before editing and verifying evidence before relying on it. It is a saved
205
+ The recovery reminders identify retained startup reads and the uncompacted tail
206
+ as available evidence. They ask for recovery only when task-relevant inputs are
207
+ missing, not for rediscovery of reading requirements or blanket document rereads.
208
+ They also distinguish restoring inputs from repeating completed writes, call for
209
+ inspecting Git state, and ask the agent to resolve task-relevant uncertainty or
210
+ contradictions using supporting output or current-state verification before treating
211
+ a claim as established. Retained prose can guide continuation without re-verifying
212
+ every fact; unresolved claims should be labelled unverified, and retrieved reasoning
213
+ remains a historical hypothesis. Historical outputs do not establish current file
214
+ or build/test state.
215
+ There is no blanket edit-target reread. It is a saved
131
216
  custom message tagged with the current compaction entry ID, not a temporary nudge:
132
217
  subsequent responses and user turns retain it in history before the work that
133
218
  followed it. `before_agent_start` adds it on normal starts/resume when missing;
@@ -145,8 +230,9 @@ Subsequent verbatim compactions skip these managed messages when building spans,
145
230
  then regenerate one envelope around the entire accumulated compacted context.
146
231
  Old generated checklists therefore do not accumulate inside spans or the active
147
232
  tail. Their original entries remain in raw session history for recovery/audit.
148
- Ordinary user, assistant and custom prose is never stripped by matching instruction
149
- text. Opaque inherited model summaries/legacy checkpoints are likewise not rewritten
233
+ User and assistant prose is never stripped by matching instruction text. Other
234
+ custom messages become type stubs regardless of whether their content resembles
235
+ instructions. Opaque inherited model summaries/legacy checkpoints are likewise not rewritten
150
236
  to remove text that looks like an old instruction envelope.
151
237
 
152
238
  Offline tests inspect actual SDK requests with roughly 20k-token tails, multiple
@@ -1,15 +1,12 @@
1
1
  /**
2
2
  * transparent-compact — transparent compaction with session-backed recovery.
3
3
  *
4
- * Builds a deterministic checkpoint without writing local transcript dumps. context_lookup renders the current raw
4
+ * Builds a deterministic checkpoint from retained session history. context_lookup renders the current raw
5
5
  * session branch in memory at call time, including earlier compactions,
6
6
  * thinking, full tool outputs, and tool-call arguments. Pi normally persists
7
7
  * this history under ~/.pi/agent/sessions/; custom session locations and
8
8
  * ephemeral sessions work too. Only the active branch is searched.
9
9
  *
10
- * Does not register dump_context or /dump-context, and does not read, write,
11
- * or prune old dumps.
12
- *
13
10
  * Optional env settings:
14
11
  * MECH_COMPACT_MAX_SUMMARY_CHARS initial character budget override (takes precedence over percent)
15
12
  * MECH_COMPACT_MAX_SUMMARY_PERCENT initial percentage of model context (default 25; >0, <=100)
@@ -162,7 +159,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
162
159
  // Exactly the existing cap's test, including its minimum 500-char line budget.
163
160
  const needsTrim = size.lineChars > Math.max(500, limit - size.overhead);
164
161
  if (state.mode !== "warn" || !needsTrim) return limit;
165
- const warning = `Verbatim compaction would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation-section chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
162
+ const warning = `Verbatim compaction would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
166
163
  if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
167
164
  ctx.ui.notify(`${warning} Applying the cap because no interactive UI is available.`, "warning");
168
165
  return limit;
@@ -357,9 +354,8 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
357
354
  break;
358
355
  }
359
356
  case "compaction": {
360
- const e = entry as SessionEntry & { tokensBefore?: number; firstKeptEntryId?: string; summary?: string; details?: { dumpDir?: string } };
357
+ const e = entry as SessionEntry & { tokensBefore?: number; firstKeptEntryId?: string; summary?: string };
361
358
  lines.push(`ENTRY ${entry.id} compaction ${t} tokensBefore=${e.tokensBefore ?? "?"} firstKeptEntryId=${e.firstKeptEntryId ?? "?"}`);
362
- if (e.details?.dumpDir) lines.push(` previous dump: ${e.details.dumpDir}`);
363
359
  lines.push("[summary]");
364
360
  lines.push(...String(e.summary ?? "").split("\n"));
365
361
  break;
@@ -423,22 +419,49 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
423
419
  // Mechanical summary (what replaces the model summary in the session)
424
420
  // ============================================================================
425
421
 
426
- function toolCallSignature(name: string, args: Record<string, unknown> | undefined): string {
422
+ // Display-only shortening: never change raw arguments or resolve symlinks.
423
+ function checkpointPath(value: string, cwd: string): string {
424
+ const prefix = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
425
+ if (value === cwd) return ".";
426
+ return value.startsWith(prefix) ? value.slice(prefix.length) : value;
427
+ }
428
+
429
+ function checkpointCommand(command: string, cwd: string): string {
430
+ const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
431
+ // Match complete path prefixes, not sibling directories or URL fragments.
432
+ return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, "g"), "$1.");
433
+ }
434
+
435
+ function argumentSnippet(value: unknown): string {
436
+ let s: string;
437
+ try {
438
+ s = JSON.stringify(value) ?? String(value);
439
+ } catch {
440
+ s = String(value);
441
+ }
442
+ return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
443
+ }
444
+
445
+ function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
427
446
  const parts: string[] = [];
428
447
  for (const [k, v] of Object.entries(args ?? {})) {
429
448
  let s: string;
430
- try {
431
- s = JSON.stringify(v) ?? String(v);
432
- } catch {
433
- s = String(v);
434
- }
435
- if (s.length > cfg.argSnippetChars) s = `${s.slice(0, cfg.argSnippetChars)}…[+${s.length - cfg.argSnippetChars} chars]`;
449
+ if (["read", "write", "edit"].includes(name) && k === "path" && typeof v === "string")
450
+ s = JSON.stringify(checkpointPath(v, cwd)); // Keep the whole identifying path.
451
+ else if (name === "write" && k === "content" && typeof v === "string")
452
+ s = `<${v.length} chars>`;
453
+ else if (name === "edit" && k === "edits" && Array.isArray(v))
454
+ s = String(v.length);
455
+ else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
456
+ s = `<${v.length} chars>`;
457
+ else
458
+ s = argumentSnippet(name === "bash" && k === "command" && typeof v === "string" ? checkpointCommand(v, cwd) : v);
436
459
  parts.push(`${k}=${s}`);
437
460
  }
438
461
  return `${name}(${parts.join(", ")})`;
439
462
  }
440
463
 
441
- function summarizeMessages(messages: AgentMessage[]): string[] {
464
+ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
442
465
  // Pair calls with later results in Pi's selected messages only. Never infer
443
466
  // outcomes from result text, assistant claims, or another branch/the kept tail.
444
467
  const outcomes = new Map<object, "ok" | "error">();
@@ -474,7 +497,7 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
474
497
  for (const block of m.content ?? []) {
475
498
  if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
476
499
  else if (block.type === "toolCall")
477
- calls.push(`${toolCallSignature(String(block.name), block.arguments)} [${outcomes.get(block) ?? "unknown"}; output removed]`);
500
+ calls.push(`${toolCallSignature(String(block.name), block.arguments, cwd)} [${outcomes.get(block) ?? "unknown"}]`);
478
501
  // thinking blocks: removed by design (kept in the session)
479
502
  }
480
503
  if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
@@ -485,12 +508,13 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
485
508
  // removed by design (kept in the session)
486
509
  break;
487
510
  case "bashExecution":
488
- lines.push(`[BashExecution]: $ ${String(m.command ?? "")} (output removed — use context_lookup)`);
511
+ lines.push(`[BashExecution]: ${toolCallSignature("bash", { command: String(m.command ?? "") }, cwd)} [output removed]`);
489
512
  break;
490
513
  case "custom":
491
514
  // Our instruction envelope is regenerated, not conversation prose.
492
515
  // Keep originals in raw history, but never carry old checklists into spans.
493
- if (m.customType !== REORIENT_MESSAGE) lines.push(`[Custom]: ${textOf(m.content).text}`);
516
+ if (m.customType !== REORIENT_MESSAGE)
517
+ lines.push(`[Custom message]: ${toolCallSignature("custom", { type: m.customType }, cwd)} [content removed — use context_lookup]`);
494
518
  break;
495
519
  case "branchSummary":
496
520
  case "compactionSummary":
@@ -503,6 +527,124 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
503
527
  return lines;
504
528
  }
505
529
 
530
+ // Startup reference retention is a lexical heuristic, not an interpretation of
531
+ // required-reading prose. Snapshot actual text read results; never open files.
532
+ interface StartupRead {
533
+ entryId: string;
534
+ path: string;
535
+ offset?: number;
536
+ limit?: number;
537
+ text: string[];
538
+ }
539
+ interface StartupReads {
540
+ version: 1;
541
+ closed: boolean;
542
+ reads: StartupRead[];
543
+ }
544
+
545
+ function isInstructionFile(file: string): boolean {
546
+ return /^(AGENTS(?:\.override)?|CLAUDE)\.md$/i.test(path.basename(file));
547
+ }
548
+
549
+ function mentionsPath(content: string, name: string): boolean {
550
+ if (!name) return false;
551
+ // A bare name can match, but not as a substring of another path or filename.
552
+ // Permit sentence-final punctuation, Markdown delimiters and link anchors.
553
+ const word = /[\p{L}\p{N}_./\\-]/u;
554
+ for (let at = content.indexOf(name); at >= 0; at = content.indexOf(name, at + 1)) {
555
+ const end = at + name.length;
556
+ const before = content[at - 1];
557
+ const after = content[end];
558
+ if ((!before || !word.test(before)) &&
559
+ (!after || !word.test(after) || (after === "." && (!content[end + 1] || /\s/.test(content[end + 1]))))) return true;
560
+ }
561
+ return false;
562
+ }
563
+
564
+ function startupReads(entries: SessionEntry[], ctx: ExtensionContext): StartupReads {
565
+ const latest = entries.findLast((e) => e.type === "compaction");
566
+ const previous = latest?.type === "compaction" &&
567
+ (latest.details as { kind?: string })?.kind === MECH_KIND
568
+ ? (latest.details as { startupReads?: StartupReads }).startupReads : undefined;
569
+ // Once the second user prompt has arrived, the selection and output bytes are
570
+ // frozen. Repeated compaction does not parse or compact an earlier checkpoint.
571
+ if (previous?.version === 1 && previous.closed) return previous;
572
+
573
+ const prompts = entries.filter((e) => e.type === "message" && e.message.role === "user");
574
+ const first = prompts[0] ? entries.indexOf(prompts[0]) : -1;
575
+ const second = prompts[1] ? entries.indexOf(prompts[1]) : entries.length;
576
+ const state: StartupReads = { version: 1, closed: prompts.length >= 2, reads: previous?.reads.slice() ?? [] };
577
+ if (first < 0) return state;
578
+
579
+ const sources = (ctx.getSystemPromptOptions?.().contextFiles ?? [])
580
+ .filter((f) => isInstructionFile(f.path)).map((f) => ({ path: f.path, content: f.content }));
581
+ // Older/custom contexts may expose only the rendered prompt. Restrict fallback
582
+ // extraction to named project-instruction blocks, never arbitrary prompt prose.
583
+ if (sources.length === 0) {
584
+ for (const match of (ctx.getSystemPrompt?.() ?? "").matchAll(/<project_instructions path="([^"]+)">\n?([\s\S]*?)<\/project_instructions>/g)) {
585
+ if (isInstructionFile(match[1])) sources.push({ path: match[1], content: match[2] });
586
+ }
587
+ }
588
+
589
+ // Respect explicit context omissions/replacements when selecting original
590
+ // reads. Raw session text remains recoverable, but is not silently resurrected.
591
+ const edits = new Map(entries.filter((e) => e.type === "context_edit").map((e) => [e.targetId, e.replacement]));
592
+ const pending = new Map<string, { name: string; args: Record<string, any> } | null>();
593
+ const reads: StartupRead[] = [];
594
+ for (const entry of entries.slice(first + 1, second)) {
595
+ if (entry.type !== "message" || edits.get(entry.id) === null) continue;
596
+ const msg = entry.message;
597
+ const content = edits.get(entry.id)?.content ?? (msg as { content?: unknown }).content;
598
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
599
+ if (!Array.isArray(blocks)) continue;
600
+ if (msg.role === "assistant") {
601
+ for (const b of blocks) {
602
+ if (b.type !== "toolCall" || typeof b.id !== "string") continue;
603
+ pending.set(b.id, pending.has(b.id) ? null : { name: b.name, args: b.arguments ?? {} });
604
+ }
605
+ } else if (msg.role === "toolResult") {
606
+ const call = pending.get(msg.toolCallId);
607
+ if (!call || call.name !== msg.toolName) continue;
608
+ pending.delete(msg.toolCallId);
609
+ if (call.name !== "read" || msg.isError !== false || typeof call.args.path !== "string" ||
610
+ blocks.length === 0 || blocks.some((b) => b.type !== "text" || typeof b.text !== "string")) continue;
611
+ const read: StartupRead = { entryId: entry.id, path: call.args.path,
612
+ ...(typeof call.args.offset === "number" ? { offset: call.args.offset } : {}),
613
+ ...(typeof call.args.limit === "number" ? { limit: call.args.limit } : {}),
614
+ text: blocks.map((b) => b.text) };
615
+ reads.push(read);
616
+ // Also recognize instruction files explicitly read during startup, e.g.
617
+ // nested AGENTS.md files not automatically loaded into the system prompt.
618
+ if (isInstructionFile(read.path)) sources.push({ path: read.path, content: read.text.join("\n") });
619
+ }
620
+ }
621
+ const known = new Set(state.reads.map((r) => r.entryId));
622
+ for (const read of reads) {
623
+ const absolute = path.resolve(ctx.cwd, read.path);
624
+ const names = [read.path, absolute, path.relative(ctx.cwd, absolute), path.basename(absolute)];
625
+ if (!known.has(read.entryId) && sources.some((source) =>
626
+ [...names, path.relative(path.dirname(path.resolve(ctx.cwd, source.path)), absolute)]
627
+ .some((name) => mentionsPath(source.content, name)))) {
628
+ state.reads.push(read);
629
+ known.add(read.entryId);
630
+ }
631
+ }
632
+ return state;
633
+ }
634
+
635
+ function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstKeptEntryId?: string): string {
636
+ const cut = entries.findIndex((e) => e.id === firstKeptEntryId);
637
+ const tail = new Set(cut < 0 ? [] : entries.slice(cut).map((e) => e.id));
638
+ const retained = state.reads.filter((r) => !tail.has(r.entryId));
639
+ if (retained.length === 0) return "";
640
+ return ["### Retained startup reads",
641
+ "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.",
642
+ ...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}`}>
643
+ ${r.text.join("\n")}
644
+ </retained-read>`),
645
+ ].join("\n\n");
646
+ }
647
+
506
648
  const SECTION_HEADER = "### Compacted conversation (oldest first)";
507
649
  const SPAN_CLOSE = "</compacted-span>";
508
650
  const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
@@ -606,21 +748,25 @@ function capSpans(spans: string[][], budget: number): string[][] {
606
748
  return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
607
749
  }
608
750
 
609
- const REORIENT_BLOCK = `**Post-compaction re-orientation — REQUIRED BEFORE CONTINUING.** Compaction may have removed information needed to follow the project instructions. Before planning or performing the next task, you MUST complete this checklist:
610
- 1. **Re-read every required document IN ITS ENTIRETY.** For this step, a document is required reading **if and only if** your applicable system prompt, developer instructions, or project instructions (including AGENTS.md / CLAUDE.md) explicitly instruct you to read it. Merely mentioning or linking a document does not qualify. Identify all such documents and re-read each from beginning to end, even if you read them before compaction. Grep matches, selected sections, summaries, and reading only files you intend to edit do NOT satisfy this requirement. If output is truncated, continue reading until you reach the end. Complete these reads before planning or changing anything; intending or promising to read does not count. If a required document is unavailable, report the blocker rather than silently skipping it.
611
- 2. Re-acquire any other information needed for the current task that is no longer in context. This means restoring inputs, not repeating completed work: do not redo writes, edits, or other state-changing actions merely because their results were dropped. If needed, recover those results with \`context_lookup\`, or verify current state.
612
- 3. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
613
- 4. Re-read any file you are about to modify — do not trust content you only remember from before the compaction.
614
- 5. **Treat other pre-compaction knowledge as unverified too.** Thinking and tool outputs were removed. Anything you know only from them — or from earlier assistant prose describing them — is a note, not evidence. Before you state it as fact or base a decision on it, re-read the source or ask \`context_lookup\`. If you cannot verify it, say explicitly that it is unverified.`;
751
+ 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.";
752
+ 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.";
753
+ 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.";
754
+ 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.";
755
+ 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.";
615
756
 
616
- const CHECKPOINT_EXPLANATION = "**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript: assistant thinking and tool outputs have been removed from the compacted spans, but are preserved in the session and can be recovered.";
757
+ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_NOTE} Retained startup reads and the uncompacted tail remain available as evidence. Recover only hidden information needed for the current task.
758
+ 1. **Restore only information needed to continue.** Re-read project files when you need their current contents; cheap local rereads and recomputations are reasonable. If you need an earlier observation, the source of a finding, or the reason for a conclusion that compaction hid, use \`context_lookup\`. This can avoid repeating slow or unreliable research. Restore inputs, not completed actions: do not redo writes, edits, or other state-changing actions merely because their results are hidden.
759
+ 2. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
760
+ 3. **Distinguish earlier claims from supporting evidence.** Retained assistant prose records what was said, not independent verification. If a task-relevant claim has uncertain provenance or conflicts with new evidence, check its supporting output (using \`context_lookup\` if hidden) or the current source before treating it as established; label unresolved claims unverified. Retrieved reasoning remains a historical hypothesis, and historical outputs do not establish current file or build/test state.`;
617
761
 
618
- const RECOVERY_INSTRUCTIONS = `**Recovering dropped details.** Information removed from your active context is preserved in the session, including earlier thinking and tool outputs. Prefer \`context_lookup\` with a specific question: a subagent searches the transcript in its own context and returns relevant findings. 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. Do not read or grep raw session JSONL files or old dumps through filesystem tools in this conversation — use these recovery tools instead.`;
762
+ const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript. ${RECOVERY_HISTORY_NOTE}`;
619
763
 
620
- const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; if a claim depends on that removed evidence, use `context_lookup` or re-read the source before relying on it.";
764
+ 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}`;
765
+
766
+ 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.";
621
767
 
622
768
  const REORIENT_MESSAGE = "transparent-compact:reorient";
623
- const RECOVERY_RECAP = "**Recovery recap.** Re-read current sources or ask `context_lookup` a specific question about removed history. If its findings are incomplete, use `context_list_entries`, `context_grep`, or `context_show_entry`, following pagination instructions. Do not read raw session JSONL files or old dumps through filesystem tools. Keep these evidence/recovery rules in force as work continues.";
769
+ 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.`;
624
770
 
625
771
  function latestVerbatimCompaction(entries: SessionEntry[]) {
626
772
  for (let i = entries.length - 1; i >= 0; i--) {
@@ -676,6 +822,8 @@ async function buildMechanicalSummary(opts: {
676
822
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
677
823
  readFiles: string[];
678
824
  modifiedFiles: string[];
825
+ startupReads: StartupReads;
826
+ cwd: string;
679
827
  notify: (msg: string) => void;
680
828
  chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
681
829
  }): Promise<string | undefined> {
@@ -683,12 +831,12 @@ async function buildMechanicalSummary(opts: {
683
831
  const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo, lines: opts.spanLines }];
684
832
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
685
833
 
686
- // Size guard: the budget applies to the WHOLE conversation section (base +
687
- // all spans). The fixed tag overhead is computed exactly (tags are known
688
- // strings), so the rendered section is guaranteed <= budget. The base block
689
- // itself is NOT capped — if it alone exceeds the budget, warn.
834
+ // Size guard: the budget covers the conversation section plus retained reads.
835
+ // The base and retained reads are fixed overhead, never trimmed. Either can
836
+ // exceed the budget by itself; warn rather than silently dropping evidence.
690
837
  const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
691
- let overhead = SECTION_HEADER.length + 2;
838
+ const retainedReads = renderStartupReads(opts.startupReads, opts.branchEntries, opts.firstKeptEntryId);
839
+ let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
692
840
  if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
693
841
  overhead += allSpans.reduce(
694
842
  (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,
@@ -710,16 +858,22 @@ async function buildMechanicalSummary(opts: {
710
858
  if (maxChars === null) return undefined;
711
859
  if (maxChars !== undefined && base && base.summary.length > maxChars)
712
860
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
861
+ if (maxChars !== undefined && retainedReads.length > maxChars)
862
+ opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
713
863
  const capped = maxChars === undefined ? lines : capSpans(lines, Math.max(500, maxChars - overhead));
714
864
 
715
865
  const blocks: string[] = [];
716
866
  if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
717
867
  capped.forEach((lines, i) => {
718
868
  const s = allSpans[i];
869
+ const trimmed = lines.length !== s.lines.length || lines.some((line, j) => line !== s.lines[j]);
719
870
  const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
720
- blocks.push(
721
- lines.length > 0 ? `${open}\n${lines.join("\n")}\n${SPAN_CLOSE}` : `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>\n${SPAN_TRIMMED_NOTE}\n${SPAN_CLOSE}`,
722
- );
871
+ blocks.push([
872
+ trimmed ? `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>` : open,
873
+ ...(trimmed ? [SPAN_TRIMMED_NOTE] : []),
874
+ ...lines,
875
+ SPAN_CLOSE,
876
+ ].join("\n"));
723
877
  });
724
878
 
725
879
  const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
@@ -731,8 +885,9 @@ async function buildMechanicalSummary(opts: {
731
885
  opts.notify(MIXED_CONTEXT_WARNING);
732
886
  }
733
887
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
734
- 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 (arguments truncated). Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
888
+ 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.");
735
889
  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.");
890
+ 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.");
736
891
  parts.push(
737
892
  "- 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.",
738
893
  );
@@ -746,12 +901,14 @@ async function buildMechanicalSummary(opts: {
746
901
  // The file lists describe the compacted spans, so they belong above the
747
902
  // verbatim boundary line. That closing line is the LAST line of the
748
903
  // checkpoint; everything after it is pi's retained verbatim tail.
904
+ if (retainedReads) parts.push("", retainedReads);
905
+ const retainedPaths = new Set(opts.startupReads.reads.map((r) => path.resolve(opts.cwd, r.path)));
749
906
  const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
750
907
  if (hasFileLists) parts.push("");
751
908
  if (opts.readFiles.length > 0)
752
- parts.push(`<read-files note="read before compaction; content removed — re-read or use context_lookup">\n${opts.readFiles.map((file) => `${file} (content removed)`).join("\n")}\n</read-files>`);
909
+ parts.push(`<read-files note="read before compaction; unless marked retained, content removed — re-read or use context_lookup">\n${opts.readFiles.map((file) => `${checkpointPath(file, opts.cwd)} (${retainedPaths.has(path.resolve(opts.cwd, file)) ? "startup read output retained in checkpoint or tail; may be partial" : "content removed"})`).join("\n")}\n</read-files>`);
753
910
  if (opts.modifiedFiles.length > 0)
754
- parts.push(`<modified-files note="modified before compaction; current contents NOT in context">\n${opts.modifiedFiles.join("\n")}\n</modified-files>`);
911
+ parts.push(`<modified-files note="modified before compaction; current contents NOT in context">\n${opts.modifiedFiles.map((file) => checkpointPath(file, opts.cwd)).join("\n")}\n</modified-files>`);
755
912
  parts.push("");
756
913
  parts.push(EVIDENCE_BOUNDARY_RULE);
757
914
  parts.push("");
@@ -1225,7 +1382,7 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
1225
1382
  }
1226
1383
 
1227
1384
  function registerDirectTools(pi: ExtensionAPI): void {
1228
- const pre = "Fallback after context_lookup, when its findings are incomplete: ";
1385
+ const pre = "Fallback after context_lookup, when its findings are incomplete; same scope as context_lookup. ";
1229
1386
  const run = (ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, f: (t: Transcript[]) => string) => {
1230
1387
  try {
1231
1388
  const transcript = sessionTranscript(ctx);
@@ -1239,7 +1396,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1239
1396
  name: "context_list_entries",
1240
1397
  label: "Context: list entries",
1241
1398
  description: pre + "List raw session ENTRY headers and previews, including compacted entries, in pages of up to 12000 payload characters, plus cursor notes. Follow all reported continuation parameters (offset and throughEntry).",
1242
- promptSnippet: "Fallback: list session entries when subagent findings are incomplete",
1399
+ promptSnippet: "Fallback: list this conversation's entries for post-compaction recovery",
1243
1400
  parameters: Type.Object(LIST_FIELDS),
1244
1401
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1245
1402
  return run(ctx, (t) => listEntries(t, params));
@@ -1249,7 +1406,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1249
1406
  name: "context_grep",
1250
1407
  label: "Context: grep",
1251
1408
  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.",
1252
- promptSnippet: "Fallback: search session evidence when subagent findings are incomplete",
1409
+ promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
1253
1410
  parameters: Type.Object(GREP_FIELDS),
1254
1411
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1255
1412
  return run(ctx, (t) => grepTranscript(t, params));
@@ -1259,7 +1416,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1259
1416
  name: "context_show_entry",
1260
1417
  label: "Context: show entry",
1261
1418
  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.",
1262
- promptSnippet: "Fallback: retrieve session entry pages when subagent findings are incomplete",
1419
+ promptSnippet: "Fallback: retrieve this conversation's entries for post-compaction recovery",
1263
1420
  parameters: Type.Object(SHOW_FIELDS),
1264
1421
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1265
1422
  return run(ctx, (t) => showEntry(t, params));
@@ -1431,9 +1588,11 @@ export default function (pi: ExtensionAPI) {
1431
1588
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1432
1589
  const spanFrom = toIso(msgTs(allMessages[0]));
1433
1590
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1434
- const spanLines = summarizeMessages(allMessages);
1591
+ const spanLines = summarizeMessages(allMessages, ctx.cwd);
1435
1592
 
1436
- // 3) Build the mechanical summary (no LLM call).
1593
+ // 3) Freeze startup references after the second user prompt, then carry
1594
+ // their original outputs forward outside the trimmable conversation spans.
1595
+ const retained = startupReads(branchEntries, ctx);
1437
1596
  const summary = await buildMechanicalSummary({
1438
1597
  reason, // pi's raw reason, passed through unchanged
1439
1598
  tokensBefore: preparation.tokensBefore,
@@ -1445,6 +1604,8 @@ export default function (pi: ExtensionAPI) {
1445
1604
  firstKeptEntryId: preparation.firstKeptEntryId,
1446
1605
  readFiles,
1447
1606
  modifiedFiles,
1607
+ startupReads: retained,
1608
+ cwd: ctx.cwd,
1448
1609
  notify: (m) => ctx.ui?.notify?.(m, "warning"),
1449
1610
  chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
1450
1611
  });
@@ -1464,6 +1625,7 @@ export default function (pi: ExtensionAPI) {
1464
1625
  kind: MECH_KIND,
1465
1626
  readFiles,
1466
1627
  modifiedFiles,
1628
+ startupReads: retained,
1467
1629
  // Only this compaction's own span (un-capped lines). Earlier spans
1468
1630
  // are re-rendered from the earlier entries' details — no nesting.
1469
1631
  span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
@@ -1485,10 +1647,10 @@ export default function (pi: ExtensionAPI) {
1485
1647
  label: "Context lookup",
1486
1648
  executionMode: "sequential",
1487
1649
  description:
1488
- "Recover information preserved in the session but removed from your active context by verbatim compaction—including thinking, tool outputs, error text, file contents, and earlier decisions. Spawns a subagent that searches the full raw session branch (across all compactions) in its OWN context and returns only relevant findings. Does not search abandoned branches or other sessions. Prefer this tool first; if findings are incomplete, use the bounded context_list_entries, context_grep, and context_show_entry fallback tools. Follow their pagination instructions. Do not read or grep raw session JSONL files or old dumps through filesystem tools. Repeated lookup calls without a non-recovery tool result, user message, or bash execution are limited. The three fallback tools neither increase nor reset the lookup count; narration and thinking do not reset it either.",
1489
- promptSnippet: "Ask a subagent to research dropped context in the session transcript",
1650
+ `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}`,
1651
+ promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
1490
1652
  parameters: Type.Object({
1491
- question: Type.String({ description: "What to find in the dropped context. Be specific (exact error text, file, decision, command output…)." }),
1653
+ 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." }),
1492
1654
  }),
1493
1655
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
1494
1656
  if (cfg.lookupMaxCalls > 0 && consecutiveLookups(ctx, toolCallId) >= cfg.lookupMaxCalls) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "pi": {
54
54
  "extensions": [
55
- "./extensions/transparent-compact.ts"
55
+ "./extensions/index.ts"
56
56
  ],
57
57
  "skills": [
58
58
  "./skills/context-retrieval"
@@ -1,25 +1,53 @@
1
1
  ---
2
2
  name: context-retrieval
3
- description: Recover earlier pi session context through the context_lookup subagent. Use after compaction when exact tool outputs, error text, file contents, thinking, tool-call arguments, or earlier instructions and decisions are needed. Use pi's retained session history for recovery, without creating additional snapshots.
3
+ description: Use context_lookup to recover earlier conversation details hidden by compaction, trace where an earlier finding came from, or investigate contradictions between earlier notes and new evidence.
4
4
  ---
5
5
 
6
6
  # Session context recovery
7
7
 
8
- This skill pairs with `transparent-compact.ts`, which provides:
8
+ ## Applicability
9
9
 
10
- - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and tool outputs are removed from the active model context, not from the raw session history. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. A persistent mandatory re-orientation checklist and recovery recap follow the retained tail; later compactions replace the old generated checklist rather than duplicating it. An inherited opaque base is kept when needed.
11
- - **`context_lookup`** — the preferred first step: 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. There is no local dump or temporary transcript file to manage.
12
- - **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. These are the permitted fallback, not filesystem access to session files.
10
+ Compaction hides earlier details from your current view. The original conversation
11
+ history, including recorded tool outputs and your reasoning, is preserved in the
12
+ session and can be retrieved. Retained startup reads and the uncompacted tail
13
+ remain available as evidence; recover only hidden information needed for the task.
13
14
 
14
- 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. The extension does not register a snapshot tool or command.
15
+ Use the recovery tools for history established by this conversation or its checkpoint,
16
+ not project discovery, requirements never supplied, other sessions, or abandoned branches.
17
+ For unfamiliar project details or missing requirements, inspect project files or
18
+ ask the user instead.
15
19
 
16
- If `context_lookup` is not in your tool list, say that subagent recovery is unavailable. Use the bounded fallback tools if available; otherwise report that limitation. Do not assume the extension is absent solely because `dump_context` is unavailable, and do not search session files manually as a fallback.
20
+ User-requested session audits, debugging, and cross-session analysis are separate
21
+ tasks, not this recovery workflow. Its filesystem restrictions do not apply to
22
+ those tasks; use ordinary file tools as needed for the requested analysis.
23
+
24
+ This skill pairs with the `@foliox/transparent-compact-pi` extension, which provides:
25
+
26
+ - **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
+ - **`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.
29
+
30
+ 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
+
32
+ If `context_lookup` is not in your tool list, say that subagent recovery is unavailable. Use the bounded fallback tools if available; otherwise report that limitation. Do not search session files manually as a fallback for compaction recovery.
17
33
 
18
34
  ## When to use
19
35
 
20
- - After a compaction, you need an exact error message, a full tool output, previously read file content, full tool-call arguments, an earlier instruction or decision, or reasoning that was dropped → call `context_lookup` with a **specific** question.
21
- - A checkpoint or your memory contains a claim based on pre-compaction tool output → re-read the current source or ask `context_lookup` for the historical evidence before relying on the claim. If you cannot verify it, explicitly label it unverified.
22
- - Before a long, tool-heavy task → no extra snapshot is required for recovery. Pi's raw session history already retains finalized entries. Follow the mandatory post-tail re-orientation checklist after compaction: re-read required project documents before planning or acting, even if earlier prose says you already read them. The checklist and recovery recap remain in context on subsequent turns; the evidence/recovery rules continue to apply.
36
+ - You need an earlier output, exact error, previously read content, full tool-call arguments, instruction, decision, or reasoning hidden by compaction.
37
+ - You are unsure where an earlier finding came from, what a command actually printed, or why you reached a conclusion.
38
+ - Earlier notes conflict with new evidence and you need to check the historical evidence behind them.
39
+
40
+ Ask `context_lookup` a **specific historical question** to recover hidden supporting
41
+ evidence. This can avoid repeating slow or unreliable research. For example:
42
+ "Where did our earlier Holi 2026 date come from: a
43
+ published source or our own computation? Include the observed output and ENTRY id."
44
+
45
+ ### Lookup or inspect the source?
46
+
47
+ - Re-read project files when you need their current contents.
48
+ - Prefer lookup when you need what was observed earlier, or when recovering earlier external research or expensive computations would avoid repeating slow or unreliable work.
49
+ - Cheap local rereads (including downloaded sources) and recomputations remain reasonable; needing a current external fact may require fresh research.
50
+ - Retained prose can guide continuation without re-verifying every fact. When uncertainty or a contradiction matters to the current task, check the supporting output or verify current state; label unresolved claims unverified. Retrieval establishes what was recorded, not whether an earlier conclusion was correct.
23
51
 
24
52
  ## How to ask
25
53
 
@@ -27,7 +55,7 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
27
55
  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." })
28
56
  ```
29
57
 
30
- For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically; there is no dump-selection argument. 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 the search through filesystem tools.
58
+ 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.
31
59
 
32
60
  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.
33
61
 
@@ -55,7 +83,7 @@ all continuation parameters printed at the end of a limited page:
55
83
 
56
84
  Listing/grep cursors also report `throughEntry`: retain this original last-entry
57
85
  id on subsequent pages, so newly appended calls/results cannot keep expanding
58
- the search. The source is rendered afresh, without a snapshot. If you change
86
+ the search. The source is rendered afresh. If you change
59
87
  search/context parameters or navigate to another branch, restart at `offset=0`
60
88
  (and `charOffset=0` for grep) without `throughEntry`. If grep reports an invalid
61
89
  `charOffset`, retry that match at the same `offset` with `charOffset=0` and your
@@ -63,15 +91,15 @@ intended context parameters.
63
91
 
64
92
  ## Rules
65
93
 
66
- 1. **Never grep or read session JSONL files or old context dumps through filesystem tools in the main conversation for recovery.** Prefer `context_lookup`; when its findings are incomplete, use the bounded fallback tools above. Raw filesystem recovery would refill the compacted context.
94
+ 1. **For recovery of details hidden by compaction, do not read or grep raw session JSONL files through filesystem tools.** Prefer `context_lookup`; when its findings are incomplete, use the bounded fallback tools above. Raw filesystem recovery would refill the compacted context. This restriction does not apply to user-requested session audits, debugging, or cross-session analysis.
67
95
  2. Ask narrowly scoped questions using exact error strings, file paths, function names, or the command whose output you need. Recover tightly related details together; use separate queries for independent facts. Ask the subagent for evidence, not for a solution to the broader task.
68
96
  3. Findings cite ENTRY ids and the logical transcript name. Retain these citations when relying on recovered facts. The renderer preserves full thinking, text, tool-call arguments, and tool results, although individual search results have output limits.
69
97
  4. Distinguish **user instructions**, **observed tool output**, and **reasoning at the time**. A recovered `[thinking]` block is a historical hypothesis, not verified fact. Earlier assistant prose is not independently observed evidence either.
70
- 5. Historical tool output proves what was observed then, not what is true now. Re-read any file you are about to modify, review uncommitted work, and re-verify current build/test state as required by the checkpoint.
98
+ 5. Historical tool output proves what was observed then, not what is true now. Review uncommitted work and re-verify current build/test state when needed; compaction alone does not require rereading edit targets.
71
99
  6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive.
72
100
 
73
- ## Explicit snapshot requests
101
+ ## Independent exports
74
102
 
75
- If the user asks to save/dump/snapshot context, explain that this extension uses pi's retained session history for recovery and provides no separate snapshot tool. Do not call `dump_context` or claim a new snapshot was saved. If the user needs an independent export, pi provides `/export`; review exports for sensitive content before sharing.
103
+ Pi provides `/export` for independent session exports; review exports for sensitive content before sharing.
76
104
 
77
105
  Session history and recovered findings can contain credentials, private code, and conversation details. Do not commit or share them without the user's explicit approval.