@foliox/transparent-compact-pi 0.8.5 → 0.8.6
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 +31 -7
- package/README.md +30 -9
- package/docs/DESIGN.md +71 -20
- package/extensions/{transparent-compact.ts → index.ts} +158 -30
- package/package.json +2 -2
- package/skills/context-retrieval/SKILL.md +31 -15
package/CHANGELOG.md
CHANGED
|
@@ -2,16 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased — initial release preparation
|
|
4
4
|
|
|
5
|
+
- Scope recovery guidance to specific earlier details lost to compaction in the
|
|
6
|
+
current conversation, not startup, project discovery, or missing requirements.
|
|
7
|
+
Filesystem restrictions apply only to that recovery workflow, not user-requested
|
|
8
|
+
session audits, debugging, or cross-session analysis. Remove the misleading
|
|
9
|
+
pre-task skill trigger and align lookup, fallback, and checkpoint descriptions.
|
|
10
|
+
- Remove obsolete recovery-interface guidance and legacy metadata rendering.
|
|
11
|
+
Agent-facing instructions describe only the current session-backed tools;
|
|
12
|
+
independent exports are documented through Pi's `/export`.
|
|
13
|
+
|
|
14
|
+
- Rename the extension entry point to `extensions/index.ts` so Pi's compact
|
|
15
|
+
extension list shows the npm package name without a `:transparent-compact.ts` suffix.
|
|
16
|
+
|
|
5
17
|
- Deterministic checkpoints retain user messages and assistant prose, subject to
|
|
6
18
|
a size guard; thinking, full tool outputs, and arguments remain in Pi's session.
|
|
19
|
+
- Startup text reads whose names appear in AGENTS/CLAUDE instructions are retained
|
|
20
|
+
verbatim, including pagination chunks. Selection scans the first user-prompt
|
|
21
|
+
interval without model calls, agent action or filesystem reads, then freezes
|
|
22
|
+
after the second prompt. Later compactions carry the outputs forward separately
|
|
23
|
+
from conversation spans, without duplicating reads still in the recent tail.
|
|
24
|
+
Retained reads count as fixed cap overhead but are never silently trimmed.
|
|
25
|
+
- Remove the required-document and edit-target reread checklist. Recovery guidance
|
|
26
|
+
now asks only for missing task-relevant evidence; retained reads remain usable.
|
|
27
|
+
- Newly compacted custom messages become bounded type stubs marked `content
|
|
28
|
+
removed`, regardless of their source extension. Bodies remain recoverable from
|
|
29
|
+
raw session history; previously saved spans are not rewritten. Managed
|
|
30
|
+
re-orientation messages continue to be regenerated instead.
|
|
7
31
|
- Tool signatures record per-call `ok`, `error`, or `unknown` outcomes from
|
|
8
32
|
matched tool-result metadata, always marking output as removed. Missing or
|
|
9
33
|
ambiguous outcomes are never inferred, including unlabelled older spans.
|
|
10
|
-
- Read-file entries
|
|
34
|
+
- Read-file entries distinguish retained startup reads from removed content; a closing evidence rule
|
|
11
35
|
requires lookup or re-reading before relying on removed outputs or document rules.
|
|
12
36
|
- The instruction envelope now has recovery explanations before all compacted
|
|
13
|
-
spans, one evidence-boundary warning after them, and
|
|
14
|
-
|
|
37
|
+
spans, one evidence-boundary warning after them, and numbered
|
|
38
|
+
recovery reminders plus brief recovery recap after the retained tail.
|
|
15
39
|
The checklist is persisted and remains active after the first response. Later
|
|
16
40
|
compactions regenerate the envelope: old generated checklists are neither
|
|
17
41
|
summarized into spans nor replayed from the retained tail. Raw originals remain
|
|
@@ -29,7 +53,8 @@
|
|
|
29
53
|
after applying a summary cannot restore earlier model-summarized context to verbatim.
|
|
30
54
|
- Session-backed `context_lookup` searches the full raw active branch across all
|
|
31
55
|
compactions, using an in-memory transcript with authoritative entry attribution.
|
|
32
|
-
-
|
|
56
|
+
- Transcript rendering uses retained session history in memory, without additional
|
|
57
|
+
files, ownership matching, or pruning.
|
|
33
58
|
- Optional `MECH_COMPACT_LOOKUP_SESSION_FILE` supports full-session recovery from
|
|
34
59
|
pruned harness forks, with explicit failures for invalid overrides.
|
|
35
60
|
- Subagent lookup provides list, grep, and entry-retrieval tools; exhausted lookups
|
|
@@ -83,8 +108,7 @@
|
|
|
83
108
|
Non-interactive mode warns and caps; cancellation never falls through to summary.
|
|
84
109
|
For unattended interactive sessions, use `/cap-compaction on` to avoid waiting
|
|
85
110
|
for trim dialogs. The `warn` default and conversion factor are unchanged.
|
|
86
|
-
- Removed
|
|
87
|
-
old dump-directory and git-ignore warning settings are unused.
|
|
111
|
+
- Removed obsolete file-backed recovery interfaces and their configuration.
|
|
88
112
|
- Bundled `context-retrieval` skill describes session-backed evidence recovery,
|
|
89
113
|
branch scope, historical provenance, and re-verification after compaction.
|
|
90
114
|
- Deterministic tests cover session recovery, overrides, attribution, size guards,
|
|
@@ -95,6 +119,6 @@
|
|
|
95
119
|
cursor-error recovery, truncation boundaries, provider caching options, and
|
|
96
120
|
real Pi agent-turn persistence ordering with a stubbed model (no live inference).
|
|
97
121
|
- Preliminary synthetic pilot figures are preserved as historical results from
|
|
98
|
-
the
|
|
122
|
+
the earlier file-backed implementation, not measurements of the current implementation.
|
|
99
123
|
|
|
100
124
|
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
|
|
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,28 @@ 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.
|
|
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
|
+
### Automatic startup-read retention
|
|
69
|
+
|
|
70
|
+
Successful text reads between the first and second user prompts are retained when
|
|
71
|
+
their paths or filenames appear in AGENTS.md / CLAUDE.md instructions. Selection
|
|
72
|
+
is purely mechanical: no model call, agent tagging, or extra filesystem reads.
|
|
73
|
+
Original output chunks, including paginated reads, survive in a separate checkpoint
|
|
74
|
+
section and carry forward across later compactions. Copies still in the recent
|
|
75
|
+
tail are not duplicated. If compaction happens before the second prompt, collection
|
|
76
|
+
continues until that prompt arrives.
|
|
77
|
+
|
|
78
|
+
This is a literal filename-matching heuristic, not an interpretation of required
|
|
79
|
+
reading. It does not capture every possible reference or fill in incomplete reads.
|
|
80
|
+
The agent is no longer given a required-document reread checklist; recovery is for
|
|
81
|
+
missing task-relevant evidence. See [selection details](docs/DESIGN.md#retained-startup-reads).
|
|
82
|
+
|
|
64
83
|
### Select the compaction method
|
|
65
84
|
|
|
66
85
|
```text
|
|
@@ -85,7 +104,7 @@ See [how cap trimming works](docs/DESIGN.md#how-cap-trimming-works) for the remo
|
|
|
85
104
|
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
105
|
If you find that in normal usage you frequently work over the compaction cap, other compaction tools are likely to be more suitable.
|
|
87
106
|
|
|
88
|
-
The default is **`warn 25%`**: a conversation-
|
|
107
|
+
The default is **`warn 25%`**: a conversation-and-retained-reads budget estimated at 25% of
|
|
89
108
|
the current model's context window, using **4 characters per token**, not an
|
|
90
109
|
exact tokenizer. When content would actually be trimmed, choose **Apply trimming**,
|
|
91
110
|
**Disable cap for this session**, **Change budget**, or **Cancel compaction**. Disabling persists as `off`, rather than
|
|
@@ -112,8 +131,10 @@ Tokens are estimated with `ceil(chars / 4)`, not an exact tokenizer. For a
|
|
|
112
131
|
characters.
|
|
113
132
|
|
|
114
133
|
The budget is a size guard, not a guarantee that the whole model context fits.
|
|
115
|
-
Instructions and file lists remain outside it.
|
|
116
|
-
|
|
134
|
+
Instructions and file lists remain outside it. Retained startup reads count as
|
|
135
|
+
fixed overhead but are never trimmed; if they alone exceed the budget, the
|
|
136
|
+
extension warns and keeps them. Disabling the cap still removes thinking and
|
|
137
|
+
unselected tool outputs and abbreviates tool-call signatures.
|
|
117
138
|
It may leave too much context for the model, particularly during overflow recovery.
|
|
118
139
|
|
|
119
140
|
With no interactive UI, `warn` emits a warning and applies the cap. TUI and
|
|
@@ -131,7 +152,7 @@ starting Pi:
|
|
|
131
152
|
|
|
132
153
|
| Variable | Default | Meaning |
|
|
133
154
|
|---|---|---|
|
|
134
|
-
| `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset (uses percentage budget) | Initial conversation-
|
|
155
|
+
| `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset (uses percentage budget) | Initial conversation-and-retained-reads character budget override; takes precedence over the percentage setting. |
|
|
135
156
|
| `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
157
|
| `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
158
|
| `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 +187,8 @@ migration. The override is extension configuration, not a tool argument or a
|
|
|
166
187
|
filesystem search route for the main agent.
|
|
167
188
|
|
|
168
189
|
The character budget is not a token limit or a hard cap on the whole checkpoint.
|
|
169
|
-
Instructions and file lists sit outside the
|
|
170
|
-
|
|
190
|
+
Instructions and file lists sit outside the budget; an inherited base and retained
|
|
191
|
+
startup reads are uncapped, and the line budget has a 500-character minimum. Tune it
|
|
171
192
|
alongside the model's context window and Pi's `compaction.keepRecentTokens`.
|
|
172
193
|
|
|
173
194
|
### Local inference engines
|
package/docs/DESIGN.md
CHANGED
|
@@ -12,14 +12,54 @@ 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;
|
|
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,
|
|
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
|
|
22
|
-
|
|
22
|
+
agent to recover missing evidence when needed. These labels describe tool
|
|
23
|
+
results, not a guarantee that tests passed. There is no required-document reread
|
|
24
|
+
checklist: retained reads remain available as evidence.
|
|
25
|
+
|
|
26
|
+
All newly compacted custom messages follow the same stub policy, regardless of
|
|
27
|
+
extension, display setting, or content format. Long type names are abbreviated
|
|
28
|
+
like tool-call arguments. This applies even with the cap disabled. Previously
|
|
29
|
+
saved spans are not rewritten; older custom-message bodies may remain in them.
|
|
30
|
+
|
|
31
|
+
### Retained startup reads
|
|
32
|
+
|
|
33
|
+
On the first verbatim compaction, the extension scans successful text-only `read`
|
|
34
|
+
call/result pairs between the first and second user messages on the active branch.
|
|
35
|
+
It retains outputs whose file paths or bare names occur literally in AGENTS/CLAUDE
|
|
36
|
+
context files supplied by Pi, or in AGENTS/CLAUDE files read during that interval.
|
|
37
|
+
`AGENTS.override.md` is recognized too. Named project-instruction blocks in the
|
|
38
|
+
rendered system prompt provide a fallback when structured context files are not
|
|
39
|
+
available. No files are opened and no model or agent action is involved.
|
|
40
|
+
|
|
41
|
+
Matching accepts absolute paths, paths relative to the working directory or
|
|
42
|
+
instruction file, and standalone basenames. It rejects substrings of other paths
|
|
43
|
+
or filenames. A bare basename can select multiple same-named files. This is a
|
|
44
|
+
lexical heuristic, not a required-reading parser: optional links can qualify;
|
|
45
|
+
indirect references, shell reads, nested tool calls and reads after the second
|
|
46
|
+
user message do not. Custom messages do not close the startup interval.
|
|
47
|
+
|
|
48
|
+
All selected output chunks are preserved verbatim, with entry IDs, paths, offsets
|
|
49
|
+
and limits. Pagination/truncation notices are retained too; retention never
|
|
50
|
+
invents missing pages or claims a partial read is a complete document. Failed,
|
|
51
|
+
ambiguous and non-text results are excluded. Selection respects explicit context
|
|
52
|
+
omissions/replacements. It does not check on-disk freshness.
|
|
53
|
+
|
|
54
|
+
The selection is stored in compaction details, separately from conversation spans.
|
|
55
|
+
Subsequent verbatim compactions carry it forward unchanged, without re-compacting
|
|
56
|
+
checkpoint text. If the second user message has not arrived yet, selection remains
|
|
57
|
+
open: later compactions scan the startup interval again and add newly qualifying
|
|
58
|
+
reads until it closes. Reads still in the uncompacted tail are not duplicated in
|
|
59
|
+
the checkpoint; they move into its retained-read section when the cut passes them.
|
|
60
|
+
Reload, resume and branch navigation follow the stored state on the active branch.
|
|
61
|
+
An older checkpoint without retention metadata initializes selection from the
|
|
62
|
+
original branch, not from its summary prose.
|
|
23
63
|
|
|
24
64
|
#### How cap trimming works
|
|
25
65
|
|
|
@@ -30,8 +70,10 @@ on them. These labels describe tool results, not a guarantee that tests passed.
|
|
|
30
70
|
oldest first.
|
|
31
71
|
3. As a last resort, remove the oldest remaining content, including user messages.
|
|
32
72
|
|
|
33
|
-
|
|
34
|
-
the
|
|
73
|
+
Retained startup reads count as fixed budget overhead and are never trimmed.
|
|
74
|
+
Like an inherited base, they can exceed the budget by themselves; in that case
|
|
75
|
+
the extension warns and preserves them. The conversation-line budget still has
|
|
76
|
+
a 500-character minimum. Originals remain recoverable from the session.
|
|
35
77
|
|
|
36
78
|
|
|
37
79
|
### Session-backed lookup
|
|
@@ -72,6 +114,18 @@ by provider.
|
|
|
72
114
|
|
|
73
115
|
### Recover historical details
|
|
74
116
|
|
|
117
|
+
Recovery is for a specific detail previously present on this conversation's active
|
|
118
|
+
branch and now missing because of compaction. The visible conversation or checkpoint
|
|
119
|
+
must establish relevant earlier history; the agent should not call recovery tools
|
|
120
|
+
to discover whether that history exists. Session startup, project discovery, missing
|
|
121
|
+
requirements, and information never supplied are not recovery triggers: inspect
|
|
122
|
+
project files or ask the user instead.
|
|
123
|
+
|
|
124
|
+
For this recovery workflow, use the recovery tools rather than reading raw session
|
|
125
|
+
files through filesystem tools. This restriction does not apply to user-requested
|
|
126
|
+
session audits, debugging, or cross-session analysis, which can use ordinary file
|
|
127
|
+
tools. Lookup itself still cannot search other sessions or abandoned branches.
|
|
128
|
+
|
|
75
129
|
The extension registers a subagent lookup and three direct-search fallback tools:
|
|
76
130
|
|
|
77
131
|
| Tool | Purpose |
|
|
@@ -111,23 +165,19 @@ instructions that must be prominent at the actual point of resumption:
|
|
|
111
165
|
|
|
112
166
|
```text
|
|
113
167
|
Checkpoint introduction: what was removed + full recovery instructions
|
|
114
|
-
All compacted spans (oldest first), then
|
|
168
|
+
All compacted spans (oldest first), then retained startup reads and file lists
|
|
115
169
|
One evidence-boundary warning + start-of-verbatim-tail marker
|
|
116
170
|
Retained verbatim tail
|
|
117
171
|
Any pending new user input
|
|
118
|
-
|
|
172
|
+
Task-relevant recovery reminders + brief recovery recap
|
|
119
173
|
```
|
|
120
174
|
|
|
121
|
-
The
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
|
175
|
+
The recovery reminders identify retained startup reads and the uncompacted tail
|
|
176
|
+
as available evidence. They ask for recovery only when task-relevant inputs are
|
|
177
|
+
missing, not for rediscovery of reading requirements or blanket document rereads.
|
|
178
|
+
They also distinguish restoring inputs from repeating completed writes, call for
|
|
179
|
+
inspecting Git state, and require verification before relying on removed evidence.
|
|
180
|
+
There is no blanket edit-target reread. It is a saved
|
|
131
181
|
custom message tagged with the current compaction entry ID, not a temporary nudge:
|
|
132
182
|
subsequent responses and user turns retain it in history before the work that
|
|
133
183
|
followed it. `before_agent_start` adds it on normal starts/resume when missing;
|
|
@@ -145,8 +195,9 @@ Subsequent verbatim compactions skip these managed messages when building spans,
|
|
|
145
195
|
then regenerate one envelope around the entire accumulated compacted context.
|
|
146
196
|
Old generated checklists therefore do not accumulate inside spans or the active
|
|
147
197
|
tail. Their original entries remain in raw session history for recovery/audit.
|
|
148
|
-
|
|
149
|
-
|
|
198
|
+
User and assistant prose is never stripped by matching instruction text. Other
|
|
199
|
+
custom messages become type stubs regardless of whether their content resembles
|
|
200
|
+
instructions. Opaque inherited model summaries/legacy checkpoints are likewise not rewritten
|
|
150
201
|
to remove text that looks like an old instruction envelope.
|
|
151
202
|
|
|
152
203
|
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
|
|
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-
|
|
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
|
|
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;
|
|
@@ -490,7 +486,8 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
|
490
486
|
case "custom":
|
|
491
487
|
// Our instruction envelope is regenerated, not conversation prose.
|
|
492
488
|
// Keep originals in raw history, but never carry old checklists into spans.
|
|
493
|
-
if (m.customType !== REORIENT_MESSAGE)
|
|
489
|
+
if (m.customType !== REORIENT_MESSAGE)
|
|
490
|
+
lines.push(`[Custom message]: ${toolCallSignature("custom", { type: m.customType })} [content removed — use context_lookup]`);
|
|
494
491
|
break;
|
|
495
492
|
case "branchSummary":
|
|
496
493
|
case "compactionSummary":
|
|
@@ -503,6 +500,124 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
|
503
500
|
return lines;
|
|
504
501
|
}
|
|
505
502
|
|
|
503
|
+
// Startup reference retention is a lexical heuristic, not an interpretation of
|
|
504
|
+
// required-reading prose. Snapshot actual text read results; never open files.
|
|
505
|
+
interface StartupRead {
|
|
506
|
+
entryId: string;
|
|
507
|
+
path: string;
|
|
508
|
+
offset?: number;
|
|
509
|
+
limit?: number;
|
|
510
|
+
text: string[];
|
|
511
|
+
}
|
|
512
|
+
interface StartupReads {
|
|
513
|
+
version: 1;
|
|
514
|
+
closed: boolean;
|
|
515
|
+
reads: StartupRead[];
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function isInstructionFile(file: string): boolean {
|
|
519
|
+
return /^(AGENTS(?:\.override)?|CLAUDE)\.md$/i.test(path.basename(file));
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function mentionsPath(content: string, name: string): boolean {
|
|
523
|
+
if (!name) return false;
|
|
524
|
+
// A bare name can match, but not as a substring of another path or filename.
|
|
525
|
+
// Permit sentence-final punctuation, Markdown delimiters and link anchors.
|
|
526
|
+
const word = /[\p{L}\p{N}_./\\-]/u;
|
|
527
|
+
for (let at = content.indexOf(name); at >= 0; at = content.indexOf(name, at + 1)) {
|
|
528
|
+
const end = at + name.length;
|
|
529
|
+
const before = content[at - 1];
|
|
530
|
+
const after = content[end];
|
|
531
|
+
if ((!before || !word.test(before)) &&
|
|
532
|
+
(!after || !word.test(after) || (after === "." && (!content[end + 1] || /\s/.test(content[end + 1]))))) return true;
|
|
533
|
+
}
|
|
534
|
+
return false;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function startupReads(entries: SessionEntry[], ctx: ExtensionContext): StartupReads {
|
|
538
|
+
const latest = entries.findLast((e) => e.type === "compaction");
|
|
539
|
+
const previous = latest?.type === "compaction" &&
|
|
540
|
+
(latest.details as { kind?: string })?.kind === MECH_KIND
|
|
541
|
+
? (latest.details as { startupReads?: StartupReads }).startupReads : undefined;
|
|
542
|
+
// Once the second user prompt has arrived, the selection and output bytes are
|
|
543
|
+
// frozen. Repeated compaction does not parse or compact an earlier checkpoint.
|
|
544
|
+
if (previous?.version === 1 && previous.closed) return previous;
|
|
545
|
+
|
|
546
|
+
const prompts = entries.filter((e) => e.type === "message" && e.message.role === "user");
|
|
547
|
+
const first = prompts[0] ? entries.indexOf(prompts[0]) : -1;
|
|
548
|
+
const second = prompts[1] ? entries.indexOf(prompts[1]) : entries.length;
|
|
549
|
+
const state: StartupReads = { version: 1, closed: prompts.length >= 2, reads: previous?.reads.slice() ?? [] };
|
|
550
|
+
if (first < 0) return state;
|
|
551
|
+
|
|
552
|
+
const sources = (ctx.getSystemPromptOptions?.().contextFiles ?? [])
|
|
553
|
+
.filter((f) => isInstructionFile(f.path)).map((f) => ({ path: f.path, content: f.content }));
|
|
554
|
+
// Older/custom contexts may expose only the rendered prompt. Restrict fallback
|
|
555
|
+
// extraction to named project-instruction blocks, never arbitrary prompt prose.
|
|
556
|
+
if (sources.length === 0) {
|
|
557
|
+
for (const match of (ctx.getSystemPrompt?.() ?? "").matchAll(/<project_instructions path="([^"]+)">\n?([\s\S]*?)<\/project_instructions>/g)) {
|
|
558
|
+
if (isInstructionFile(match[1])) sources.push({ path: match[1], content: match[2] });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// Respect explicit context omissions/replacements when selecting original
|
|
563
|
+
// reads. Raw session text remains recoverable, but is not silently resurrected.
|
|
564
|
+
const edits = new Map(entries.filter((e) => e.type === "context_edit").map((e) => [e.targetId, e.replacement]));
|
|
565
|
+
const pending = new Map<string, { name: string; args: Record<string, any> } | null>();
|
|
566
|
+
const reads: StartupRead[] = [];
|
|
567
|
+
for (const entry of entries.slice(first + 1, second)) {
|
|
568
|
+
if (entry.type !== "message" || edits.get(entry.id) === null) continue;
|
|
569
|
+
const msg = entry.message;
|
|
570
|
+
const content = edits.get(entry.id)?.content ?? (msg as { content?: unknown }).content;
|
|
571
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
572
|
+
if (!Array.isArray(blocks)) continue;
|
|
573
|
+
if (msg.role === "assistant") {
|
|
574
|
+
for (const b of blocks) {
|
|
575
|
+
if (b.type !== "toolCall" || typeof b.id !== "string") continue;
|
|
576
|
+
pending.set(b.id, pending.has(b.id) ? null : { name: b.name, args: b.arguments ?? {} });
|
|
577
|
+
}
|
|
578
|
+
} else if (msg.role === "toolResult") {
|
|
579
|
+
const call = pending.get(msg.toolCallId);
|
|
580
|
+
if (!call || call.name !== msg.toolName) continue;
|
|
581
|
+
pending.delete(msg.toolCallId);
|
|
582
|
+
if (call.name !== "read" || msg.isError !== false || typeof call.args.path !== "string" ||
|
|
583
|
+
blocks.length === 0 || blocks.some((b) => b.type !== "text" || typeof b.text !== "string")) continue;
|
|
584
|
+
const read: StartupRead = { entryId: entry.id, path: call.args.path,
|
|
585
|
+
...(typeof call.args.offset === "number" ? { offset: call.args.offset } : {}),
|
|
586
|
+
...(typeof call.args.limit === "number" ? { limit: call.args.limit } : {}),
|
|
587
|
+
text: blocks.map((b) => b.text) };
|
|
588
|
+
reads.push(read);
|
|
589
|
+
// Also recognize instruction files explicitly read during startup, e.g.
|
|
590
|
+
// nested AGENTS.md files not automatically loaded into the system prompt.
|
|
591
|
+
if (isInstructionFile(read.path)) sources.push({ path: read.path, content: read.text.join("\n") });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
const known = new Set(state.reads.map((r) => r.entryId));
|
|
595
|
+
for (const read of reads) {
|
|
596
|
+
const absolute = path.resolve(ctx.cwd, read.path);
|
|
597
|
+
const names = [read.path, absolute, path.relative(ctx.cwd, absolute), path.basename(absolute)];
|
|
598
|
+
if (!known.has(read.entryId) && sources.some((source) =>
|
|
599
|
+
[...names, path.relative(path.dirname(path.resolve(ctx.cwd, source.path)), absolute)]
|
|
600
|
+
.some((name) => mentionsPath(source.content, name)))) {
|
|
601
|
+
state.reads.push(read);
|
|
602
|
+
known.add(read.entryId);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
return state;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstKeptEntryId?: string): string {
|
|
609
|
+
const cut = entries.findIndex((e) => e.id === firstKeptEntryId);
|
|
610
|
+
const tail = new Set(cut < 0 ? [] : entries.slice(cut).map((e) => e.id));
|
|
611
|
+
const retained = state.reads.filter((r) => !tail.has(r.entryId));
|
|
612
|
+
if (retained.length === 0) return "";
|
|
613
|
+
return ["### Retained startup reads",
|
|
614
|
+
"Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool stubs marked 'output removed' refer to the conversation spans, not these retained copies.",
|
|
615
|
+
...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}`}>
|
|
616
|
+
${r.text.join("\n")}
|
|
617
|
+
</retained-read>`),
|
|
618
|
+
].join("\n\n");
|
|
619
|
+
}
|
|
620
|
+
|
|
506
621
|
const SECTION_HEADER = "### Compacted conversation (oldest first)";
|
|
507
622
|
const SPAN_CLOSE = "</compacted-span>";
|
|
508
623
|
const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
|
|
@@ -606,21 +721,21 @@ function capSpans(spans: string[][], budget: number): string[][] {
|
|
|
606
721
|
return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
|
|
607
722
|
}
|
|
608
723
|
|
|
609
|
-
const REORIENT_BLOCK = `**Post-compaction re-orientation
|
|
610
|
-
1.
|
|
611
|
-
2.
|
|
612
|
-
3.
|
|
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.`;
|
|
724
|
+
const REORIENT_BLOCK = `**Post-compaction re-orientation.** Retained startup reads and the uncompacted tail remain available as evidence. Recover only missing information needed for the current task.
|
|
725
|
+
1. Re-acquire 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.
|
|
726
|
+
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.
|
|
727
|
+
3. **Treat knowledge from removed evidence as unverified.** Thinking and tool outputs were removed from the compacted spans, except for the separately retained startup reads. The uncompacted tail is unchanged. Anything you know only from removed material — or from earlier assistant prose describing it — 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.`;
|
|
615
728
|
|
|
616
729
|
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.";
|
|
617
730
|
|
|
618
|
-
const
|
|
731
|
+
const RECOVERY_FILESYSTEM_RULE = "For recovery of details lost from the context in this session due to compaction, do not read or grep raw session JSONL files through filesystem tools; use the recovery tools instead.";
|
|
732
|
+
|
|
733
|
+
const RECOVERY_INSTRUCTIONS = `**Recovering dropped details.** Information removed from your active context is preserved in this conversation's history, including earlier thinking and tool outputs. Recover only specific details previously present on this conversation's active branch and now missing because of compaction, not information never supplied. Prefer \`context_lookup\` for this recovery 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. ${RECOVERY_FILESYSTEM_RULE}`;
|
|
619
734
|
|
|
620
735
|
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.";
|
|
621
736
|
|
|
622
737
|
const REORIENT_MESSAGE = "transparent-compact:reorient";
|
|
623
|
-
const RECOVERY_RECAP =
|
|
738
|
+
const RECOVERY_RECAP = `**Recovery recap.** When needed evidence from earlier in this conversation is missing because of compaction, re-read its source or ask \`context_lookup\` a specific question about that removed history. Missing requirements or unfamiliar project details are not evidence of forgotten history: inspect project files or ask the user instead. If its 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
739
|
|
|
625
740
|
function latestVerbatimCompaction(entries: SessionEntry[]) {
|
|
626
741
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
@@ -676,6 +791,8 @@ async function buildMechanicalSummary(opts: {
|
|
|
676
791
|
firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
|
|
677
792
|
readFiles: string[];
|
|
678
793
|
modifiedFiles: string[];
|
|
794
|
+
startupReads: StartupReads;
|
|
795
|
+
cwd: string;
|
|
679
796
|
notify: (msg: string) => void;
|
|
680
797
|
chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
|
|
681
798
|
}): Promise<string | undefined> {
|
|
@@ -683,12 +800,12 @@ async function buildMechanicalSummary(opts: {
|
|
|
683
800
|
const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo, lines: opts.spanLines }];
|
|
684
801
|
const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
|
|
685
802
|
|
|
686
|
-
// Size guard: the budget
|
|
687
|
-
//
|
|
688
|
-
//
|
|
689
|
-
// itself is NOT capped — if it alone exceeds the budget, warn.
|
|
803
|
+
// Size guard: the budget covers the conversation section plus retained reads.
|
|
804
|
+
// The base and retained reads are fixed overhead, never trimmed. Either can
|
|
805
|
+
// exceed the budget by itself; warn rather than silently dropping evidence.
|
|
690
806
|
const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
|
|
691
|
-
|
|
807
|
+
const retainedReads = renderStartupReads(opts.startupReads, opts.branchEntries, opts.firstKeptEntryId);
|
|
808
|
+
let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
|
|
692
809
|
if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
|
|
693
810
|
overhead += allSpans.reduce(
|
|
694
811
|
(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,6 +827,8 @@ async function buildMechanicalSummary(opts: {
|
|
|
710
827
|
if (maxChars === null) return undefined;
|
|
711
828
|
if (maxChars !== undefined && base && base.summary.length > maxChars)
|
|
712
829
|
opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
|
|
830
|
+
if (maxChars !== undefined && retainedReads.length > maxChars)
|
|
831
|
+
opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
|
|
713
832
|
const capped = maxChars === undefined ? lines : capSpans(lines, Math.max(500, maxChars - overhead));
|
|
714
833
|
|
|
715
834
|
const blocks: string[] = [];
|
|
@@ -733,6 +852,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
733
852
|
parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
|
|
734
853
|
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.");
|
|
735
854
|
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.");
|
|
855
|
+
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
856
|
parts.push(
|
|
737
857
|
"- 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
858
|
);
|
|
@@ -746,10 +866,12 @@ async function buildMechanicalSummary(opts: {
|
|
|
746
866
|
// The file lists describe the compacted spans, so they belong above the
|
|
747
867
|
// verbatim boundary line. That closing line is the LAST line of the
|
|
748
868
|
// checkpoint; everything after it is pi's retained verbatim tail.
|
|
869
|
+
if (retainedReads) parts.push("", retainedReads);
|
|
870
|
+
const retainedPaths = new Set(opts.startupReads.reads.map((r) => path.resolve(opts.cwd, r.path)));
|
|
749
871
|
const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
|
|
750
872
|
if (hasFileLists) parts.push("");
|
|
751
873
|
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>`);
|
|
874
|
+
parts.push(`<read-files note="read before compaction; unless marked retained, content removed — re-read or use context_lookup">\n${opts.readFiles.map((file) => `${file} (${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
875
|
if (opts.modifiedFiles.length > 0)
|
|
754
876
|
parts.push(`<modified-files note="modified before compaction; current contents NOT in context">\n${opts.modifiedFiles.join("\n")}\n</modified-files>`);
|
|
755
877
|
parts.push("");
|
|
@@ -1225,7 +1347,7 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
|
|
|
1225
1347
|
}
|
|
1226
1348
|
|
|
1227
1349
|
function registerDirectTools(pi: ExtensionAPI): void {
|
|
1228
|
-
const pre = "Fallback after context_lookup, when its findings are incomplete: ";
|
|
1350
|
+
const pre = "Fallback after context_lookup, when its findings are incomplete: recover specific earlier details lost to compaction on this conversation's active branch, not project discovery or information never supplied. Cannot search other sessions or abandoned branches. ";
|
|
1229
1351
|
const run = (ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, f: (t: Transcript[]) => string) => {
|
|
1230
1352
|
try {
|
|
1231
1353
|
const transcript = sessionTranscript(ctx);
|
|
@@ -1239,7 +1361,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1239
1361
|
name: "context_list_entries",
|
|
1240
1362
|
label: "Context: list entries",
|
|
1241
1363
|
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
|
|
1364
|
+
promptSnippet: "Fallback: list this conversation's entries for post-compaction recovery",
|
|
1243
1365
|
parameters: Type.Object(LIST_FIELDS),
|
|
1244
1366
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1245
1367
|
return run(ctx, (t) => listEntries(t, params));
|
|
@@ -1249,7 +1371,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1249
1371
|
name: "context_grep",
|
|
1250
1372
|
label: "Context: grep",
|
|
1251
1373
|
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
|
|
1374
|
+
promptSnippet: "Fallback: search this conversation's evidence lost through compaction",
|
|
1253
1375
|
parameters: Type.Object(GREP_FIELDS),
|
|
1254
1376
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1255
1377
|
return run(ctx, (t) => grepTranscript(t, params));
|
|
@@ -1259,7 +1381,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1259
1381
|
name: "context_show_entry",
|
|
1260
1382
|
label: "Context: show entry",
|
|
1261
1383
|
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
|
|
1384
|
+
promptSnippet: "Fallback: retrieve this conversation's entries for post-compaction recovery",
|
|
1263
1385
|
parameters: Type.Object(SHOW_FIELDS),
|
|
1264
1386
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1265
1387
|
return run(ctx, (t) => showEntry(t, params));
|
|
@@ -1433,7 +1555,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1433
1555
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
1434
1556
|
const spanLines = summarizeMessages(allMessages);
|
|
1435
1557
|
|
|
1436
|
-
// 3)
|
|
1558
|
+
// 3) Freeze startup references after the second user prompt, then carry
|
|
1559
|
+
// their original outputs forward outside the trimmable conversation spans.
|
|
1560
|
+
const retained = startupReads(branchEntries, ctx);
|
|
1437
1561
|
const summary = await buildMechanicalSummary({
|
|
1438
1562
|
reason, // pi's raw reason, passed through unchanged
|
|
1439
1563
|
tokensBefore: preparation.tokensBefore,
|
|
@@ -1445,6 +1569,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1445
1569
|
firstKeptEntryId: preparation.firstKeptEntryId,
|
|
1446
1570
|
readFiles,
|
|
1447
1571
|
modifiedFiles,
|
|
1572
|
+
startupReads: retained,
|
|
1573
|
+
cwd: ctx.cwd,
|
|
1448
1574
|
notify: (m) => ctx.ui?.notify?.(m, "warning"),
|
|
1449
1575
|
chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
|
|
1450
1576
|
});
|
|
@@ -1464,6 +1590,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1464
1590
|
kind: MECH_KIND,
|
|
1465
1591
|
readFiles,
|
|
1466
1592
|
modifiedFiles,
|
|
1593
|
+
startupReads: retained,
|
|
1467
1594
|
// Only this compaction's own span (un-capped lines). Earlier spans
|
|
1468
1595
|
// are re-rendered from the earlier entries' details — no nesting.
|
|
1469
1596
|
span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
|
|
@@ -1485,10 +1612,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1485
1612
|
label: "Context lookup",
|
|
1486
1613
|
executionMode: "sequential",
|
|
1487
1614
|
description:
|
|
1488
|
-
"Recover
|
|
1489
|
-
|
|
1615
|
+
"Recover a specific detail previously present earlier on this conversation's active branch but now missing because of compaction, including thinking, tool outputs, error text, file contents, or earlier decisions. Use only when the visible conversation or compaction checkpoint establishes relevant earlier history; do not call this tool to discover whether such history exists. Not for session startup, new-project orientation, missing requirements, or information never supplied: inspect project files or ask the user instead. Spawns a subagent that searches this conversation's full raw active branch (across all compactions) in its OWN context and returns relevant findings. Does not search abandoned branches or other sessions. For this recovery workflow, 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. " +
|
|
1616
|
+
RECOVERY_FILESYSTEM_RULE + "",
|
|
1617
|
+
promptSnippet: "Recover specific earlier conversation details lost through compaction",
|
|
1490
1618
|
parameters: Type.Object({
|
|
1491
|
-
question: Type.String({ description: "
|
|
1619
|
+
question: Type.String({ description: "The specific detail from earlier in this conversation that compaction removed (exact error text, previously read file, decision, command output…)." }),
|
|
1492
1620
|
}),
|
|
1493
1621
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1494
1622
|
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.
|
|
3
|
+
"version": "0.8.6",
|
|
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/
|
|
55
|
+
"./extensions/index.ts"
|
|
56
56
|
],
|
|
57
57
|
"skills": [
|
|
58
58
|
"./skills/context-retrieval"
|
|
@@ -1,25 +1,41 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: context-retrieval
|
|
3
|
-
description:
|
|
3
|
+
description: Use context_lookup when compaction has removed a specific detail from earlier in this same conversation and that detail is needed again. Not for session startup, project discovery, missing requirements, or auditing session files.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Session context recovery
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
## Applicability
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
Use this skill only to recover a specific detail previously present on this
|
|
11
|
+
conversation's active branch and now missing because of compaction. The visible
|
|
12
|
+
conversation or compaction checkpoint must establish relevant earlier history;
|
|
13
|
+
do not call recovery tools to discover whether such history exists. Missing
|
|
14
|
+
requirements or an unfamiliar project do not imply forgotten context: inspect
|
|
15
|
+
project files or ask the user instead.
|
|
13
16
|
|
|
14
|
-
|
|
17
|
+
Retained startup reads and the uncompacted tail remain available as evidence.
|
|
18
|
+
Do not recover information that is still visible, or information never supplied.
|
|
19
|
+
These tools cannot search other sessions or abandoned branches.
|
|
15
20
|
|
|
16
|
-
|
|
21
|
+
User-requested session audits, debugging, and cross-session analysis are separate
|
|
22
|
+
tasks, not this recovery workflow. Its filesystem restrictions do not apply to
|
|
23
|
+
those tasks; use ordinary file tools as needed for the requested analysis.
|
|
24
|
+
|
|
25
|
+
This skill pairs with the `@foliox/transparent-compact-pi` extension, which provides:
|
|
26
|
+
|
|
27
|
+
- **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.
|
|
28
|
+
- **`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.
|
|
29
|
+
- **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 lost to compaction, these are the permitted fallback, not filesystem access to session files.
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
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
34
|
|
|
18
35
|
## When to use
|
|
19
36
|
|
|
20
37
|
- 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
|
|
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.
|
|
38
|
+
- A compaction checkpoint contains a claim whose supporting tool output was removed → re-read the current source or ask `context_lookup` for that historical evidence before relying on the claim. If you cannot verify it, explicitly label it unverified.
|
|
23
39
|
|
|
24
40
|
## How to ask
|
|
25
41
|
|
|
@@ -27,7 +43,7 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
|
|
|
27
43
|
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
44
|
```
|
|
29
45
|
|
|
30
|
-
For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically
|
|
46
|
+
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
47
|
|
|
32
48
|
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
49
|
|
|
@@ -55,7 +71,7 @@ all continuation parameters printed at the end of a limited page:
|
|
|
55
71
|
|
|
56
72
|
Listing/grep cursors also report `throughEntry`: retain this original last-entry
|
|
57
73
|
id on subsequent pages, so newly appended calls/results cannot keep expanding
|
|
58
|
-
the search. The source is rendered afresh
|
|
74
|
+
the search. The source is rendered afresh. If you change
|
|
59
75
|
search/context parameters or navigate to another branch, restart at `offset=0`
|
|
60
76
|
(and `charOffset=0` for grep) without `throughEntry`. If grep reports an invalid
|
|
61
77
|
`charOffset`, retry that match at the same `offset` with `charOffset=0` and your
|
|
@@ -63,15 +79,15 @@ intended context parameters.
|
|
|
63
79
|
|
|
64
80
|
## Rules
|
|
65
81
|
|
|
66
|
-
1. **
|
|
82
|
+
1. **For recovery of details lost to 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
83
|
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
84
|
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
85
|
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.
|
|
86
|
+
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
87
|
6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive.
|
|
72
88
|
|
|
73
|
-
##
|
|
89
|
+
## Independent exports
|
|
74
90
|
|
|
75
|
-
|
|
91
|
+
Pi provides `/export` for independent session exports; review exports for sensitive content before sharing.
|
|
76
92
|
|
|
77
93
|
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.
|