@foliox/transparent-compact-pi 0.8.7 → 0.8.9
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 +20 -1
- package/README.md +9 -1
- package/docs/DESIGN.md +57 -10
- package/extensions/index.ts +132 -13
- package/package.json +1 -1
- package/skills/context-retrieval/SKILL.md +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased — initial release preparation
|
|
4
4
|
|
|
5
|
+
- Raise the default lookup budget from 10 to 25 substantive search turns (75 total
|
|
6
|
+
search-phase model calls, plus a final tool-free write-up). Keep the consecutive
|
|
7
|
+
lookup limit at 1. Mark plain-text answers after the paging-only budget warning
|
|
8
|
+
as potentially incomplete and include fallback guidance. Instruct the subagent
|
|
9
|
+
not to turn incomplete searches into claims that evidence was never recorded.
|
|
10
|
+
- Advertise the retrieval skill as guidance on targeting evidence, phrasing lookup
|
|
11
|
+
questions, and handling incomplete findings, without a mandatory preflight read.
|
|
12
|
+
|
|
13
|
+
- Replace misleading file-list content-absence claims with compact retained-evidence
|
|
14
|
+
labels, recomputed from Pi's projected tail at each checkpoint. Distinguish full,
|
|
15
|
+
partial, and uncertain reads; visible write payloads; and subsequent tracked
|
|
16
|
+
changes. Preserve startup-read labels and give modified paths a narrowly factual
|
|
17
|
+
negative label when no retained read/write evidence is established. Read-list
|
|
18
|
+
headers state the negative default once instead of repeating it per path. No
|
|
19
|
+
extra filesystem reads, model calls, or source-content duplication.
|
|
20
|
+
- Add a narrow safeguard before whole-file `write` replacement: reread unless
|
|
21
|
+
current contents are already visible, and do not reconstruct unchanged sections
|
|
22
|
+
from memory. Small exact-match edits do not require a blanket reread.
|
|
23
|
+
|
|
5
24
|
- Advertise recovery positively as retrieving history hidden by compaction, with
|
|
6
25
|
explicit provenance and contradiction triggers in the lookup description, skill,
|
|
7
26
|
and post-compaction reminders. Distinguish historical observations from current
|
|
@@ -82,7 +101,7 @@
|
|
|
82
101
|
budget when they use previously issued, single-use cursors with unchanged
|
|
83
102
|
effective parameters. New searches, mixed batches, invented/replayed cursors,
|
|
84
103
|
and duplicate continuations still count. A separate ceiling allows at most
|
|
85
|
-
3× the configured budget in search-phase model calls (
|
|
104
|
+
3× the configured budget in search-phase model calls (75 by default), plus
|
|
86
105
|
one final tool-free write-up. This is a safety guard, not a measured optimum;
|
|
87
106
|
no telemetry or subagent trace is persisted.
|
|
88
107
|
- Paging guidance now asks for continuation only when omitted evidence matters,
|
package/README.md
CHANGED
|
@@ -72,6 +72,14 @@ earlier notes and new evidence. Prefer lookup for historical observations or to
|
|
|
72
72
|
avoid repeating costly research; inspect project files for current contents.
|
|
73
73
|
Cheap local rereads and recomputations remain reasonable.
|
|
74
74
|
|
|
75
|
+
File lists now distinguish source output retained in the recent tail, partial
|
|
76
|
+
reads, and reads followed by tracked changes. Modified paths without retained
|
|
77
|
+
read/write evidence are marked `no read-tool output in tail`; these annotations
|
|
78
|
+
are checkpoint-time evidence, not guarantees of current filesystem state.
|
|
79
|
+
Before replacing an existing file with `write`, the agent is told to reread it
|
|
80
|
+
unless current contents are already visible, rather than reconstruct unchanged
|
|
81
|
+
sections from memory. Small exact-match edits have no blanket reread requirement.
|
|
82
|
+
|
|
75
83
|
### Automatic startup-read retention
|
|
76
84
|
|
|
77
85
|
Successful text reads between the first and second user prompts are retained when
|
|
@@ -162,7 +170,7 @@ starting Pi:
|
|
|
162
170
|
| `MECH_COMPACT_MAX_SUMMARY_CHARS` | Unset (uses percentage budget) | Initial conversation-and-retained-reads character budget override; takes precedence over the percentage setting. |
|
|
163
171
|
| `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. |
|
|
164
172
|
| `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. |
|
|
165
|
-
| `MECH_COMPACT_LOOKUP_TURNS` | `
|
|
173
|
+
| `MECH_COMPACT_LOOKUP_TURNS` | `25` | Maximum substantive search turns. Valid continuation-only turns are exempt; total search-phase model calls are capped at 3× this budget (75 by default), plus one tool-free write-up on exhaustion. |
|
|
166
174
|
| `MECH_COMPACT_LOOKUP_MAX_CALLS` | `1` | Maximum consecutive lookup attempts. `0` means unlimited; see [recovery reset rules](docs/DESIGN.md#recover-historical-details). Invalid values fall back to 1. |
|
|
167
175
|
| `MECH_COMPACT_LOOKUP_SESSION_FILE` | Unset | Optional absolute path to a full session JSONL, replacing the current branch as the lookup source. Intended for harnesses using pruned forks. |
|
|
168
176
|
|
package/docs/DESIGN.md
CHANGED
|
@@ -16,7 +16,7 @@ extension builds a checkpoint without changing that boundary or calling a model:
|
|
|
16
16
|
| Custom messages | Short type stubs marked `content removed`; bodies remain in the raw session. Managed re-orientation messages are regenerated instead. |
|
|
17
17
|
| Recent conversation | Pi keeps its normal verbatim tail. |
|
|
18
18
|
| Earlier compacted spans | Re-rendered chronologically, without repeated model summarization. |
|
|
19
|
-
| Read/modified file lists |
|
|
19
|
+
| Read/modified file lists | Cumulative operation lists with checkpoint-relative retained-evidence annotations. |
|
|
20
20
|
|
|
21
21
|
Checkpoints label tool outcomes as `ok`, `error`, or `unknown` and remind the
|
|
22
22
|
agent to recover missing evidence when needed. These labels describe tool
|
|
@@ -40,6 +40,42 @@ extension, display setting, or content format. Long type names are abbreviated
|
|
|
40
40
|
like tool-call arguments. This applies even with the cap disabled. Previously
|
|
41
41
|
saved spans are not rewritten; older custom-message bodies may remain in them.
|
|
42
42
|
|
|
43
|
+
### File-list evidence annotations
|
|
44
|
+
|
|
45
|
+
The lists record reads and modifications in compacted history, not an exhaustive
|
|
46
|
+
inventory of current file contents. At every checkpoint, the extension checks
|
|
47
|
+
Pi's model-context projection from `firstKeptEntryId` onward. The turn prefix is
|
|
48
|
+
being compacted and is not treated as retained evidence. Context omissions and
|
|
49
|
+
replacements are respected; replacement read text has unknown completeness.
|
|
50
|
+
No filesystem reads or model calls are made for annotation.
|
|
51
|
+
|
|
52
|
+
Successful, unambiguously paired `read` results receive `(full read in tail)`,
|
|
53
|
+
`(partial read in tail)`, or `(read output in tail)` when completeness is uncertain.
|
|
54
|
+
For Pi's read contract, offset/limit alone does not imply partialness: an offset of
|
|
55
|
+
1 with a limit beyond EOF can still be complete. Truncation metadata and continuation
|
|
56
|
+
notices are checked. Separate partial pages are not combined into a full-file claim.
|
|
57
|
+
A later partial read does not hide an earlier complete snapshot with no intervening
|
|
58
|
+
tracked modification.
|
|
59
|
+
|
|
60
|
+
Successful writes with a visible full payload receive `(write content in tail)`.
|
|
61
|
+
Recorded subsequent edits/writes invalidate earlier snapshots and produce labels
|
|
62
|
+
such as `(read in tail, then edited)`. Mutation metadata can invalidate a snapshot
|
|
63
|
+
even when the mutation's message was omitted, but cannot restore omitted source
|
|
64
|
+
contents. Nested calls can invalidate snapshots, not supply visible file contents.
|
|
65
|
+
Same-path sibling operations may run concurrently, so ambiguous read/write versus
|
|
66
|
+
mutation ordering receives `(read in tail; order uncertain)` or the write equivalent
|
|
67
|
+
instead of treating result order as proof of freshness.
|
|
68
|
+
|
|
69
|
+
Modified paths without retained read/write evidence receive `(no read-tool output
|
|
70
|
+
in tail)`, unless a selected startup read is retained separately. Startup reads
|
|
71
|
+
keep their existing positive annotation. Unmodified paths without established
|
|
72
|
+
retained evidence remain unannotated; the read-list header states the default once:
|
|
73
|
+
"unless annotated, no retained read-tool output identified". A bare path does not
|
|
74
|
+
establish that document contents are still visible. The shared explanation states that labels
|
|
75
|
+
apply as of this checkpoint, not to live filesystem state; shell reads/changes and
|
|
76
|
+
external modifications are not inferred. File contents are never duplicated into
|
|
77
|
+
these lists, and annotations are recomputed rather than persisted as file metadata.
|
|
78
|
+
|
|
43
79
|
### Retained startup reads
|
|
44
80
|
|
|
45
81
|
On the first verbatim compaction, the extension scans successful text-only `read`
|
|
@@ -118,12 +154,17 @@ copy, or cleanup is needed. They share the fallback tools' paginated search
|
|
|
118
154
|
functions. Individual results and the final answer have size limits. Follow
|
|
119
155
|
pages only when omitted content is needed, not to exhaust every match or entry.
|
|
120
156
|
|
|
121
|
-
|
|
122
|
-
queries, changed parameters, or replayed cursors do. A separate
|
|
123
|
-
search-phase model calls at three times the configured turn budget
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
157
|
+
The default substantive search budget is 25 turns. Valid continuation-only turns
|
|
158
|
+
do not spend it; new queries, changed parameters, or replayed cursors do. A separate
|
|
159
|
+
ceiling caps all search-phase model calls at three times the configured turn budget
|
|
160
|
+
(75 by default). A turn may batch multiple tool calls; these are not individual
|
|
161
|
+
search counts. When either budget ends searching, one final tool-free model call
|
|
162
|
+
writes up partial findings; a failed write-up falls back to the latest text,
|
|
163
|
+
explicitly labeled incomplete. A plain-text answer after the paging-only budget
|
|
164
|
+
warning also carries an incomplete-findings marker and fallback guidance, without
|
|
165
|
+
an extra write-up call. Both normal-answer and forced-write-up instructions distinguish
|
|
166
|
+
unreached evidence from absence: an incomplete search does not establish that the
|
|
167
|
+
answer was never recorded. Lookup requests use normal provider caching
|
|
127
168
|
defaults rather than forcing caching off; actual cache behavior and savings vary
|
|
128
169
|
by provider.
|
|
129
170
|
|
|
@@ -137,8 +178,10 @@ These triggers are advertised in the tool description and conditionally explaine
|
|
|
137
178
|
in post-compaction reminders, not just in the skill body. Reminders lead with
|
|
138
179
|
restoring task-relevant inputs, current-file reads, and cheap recomputation;
|
|
139
180
|
compaction alone is not a lookup trigger. Advertising and re-orientation use
|
|
140
|
-
separate wording. The skill description
|
|
141
|
-
|
|
181
|
+
separate wording. The skill description advertises procedural guidance for targeting
|
|
182
|
+
earlier evidence, phrasing lookup questions, and handling incomplete findings,
|
|
183
|
+
without requiring a skill read before every lookup. This is guidance, not a
|
|
184
|
+
guarantee of model compliance.
|
|
142
185
|
|
|
143
186
|
Re-read project files for their current contents. Prefer lookup for what was
|
|
144
187
|
observed earlier or to avoid repeating slow external research or expensive
|
|
@@ -212,7 +255,11 @@ a claim as established. Retained prose can guide continuation without re-verifyi
|
|
|
212
255
|
every fact; unresolved claims should be labelled unverified, and retrieved reasoning
|
|
213
256
|
remains a historical hypothesis. Historical outputs do not establish current file
|
|
214
257
|
or build/test state.
|
|
215
|
-
There is no blanket edit-target reread.
|
|
258
|
+
There is no blanket edit-target reread. Before replacing an existing file with
|
|
259
|
+
`write`, the guidance requires rereading unless current contents are already in
|
|
260
|
+
view, and forbids reconstructing unchanged sections from memory. Small exact-match
|
|
261
|
+
edits and newly created files do not acquire a blanket reread requirement.
|
|
262
|
+
It is a saved
|
|
216
263
|
custom message tagged with the current compaction entry ID, not a temporary nudge:
|
|
217
264
|
subsequent responses and user turns retain it in history before the work that
|
|
218
265
|
followed it. `before_agent_start` adds it on normal starts/resume when missing;
|
package/extensions/index.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* MECH_COMPACT_MAX_SUMMARY_CHARS initial character budget override (takes precedence over percent)
|
|
12
12
|
* MECH_COMPACT_MAX_SUMMARY_PERCENT initial percentage of model context (default 25; >0, <=100)
|
|
13
13
|
* MECH_COMPACT_LOOKUP_MODEL "provider/modelId" for the lookup subagent
|
|
14
|
-
* MECH_COMPACT_LOOKUP_TURNS max substantive search turns (default
|
|
14
|
+
* MECH_COMPACT_LOOKUP_TURNS max substantive search turns (default 25).
|
|
15
15
|
* Valid continuation-only turns are exempt;
|
|
16
16
|
* total search-phase calls capped at 3x this,
|
|
17
17
|
* plus one final write-up on exhaustion
|
|
@@ -25,11 +25,13 @@
|
|
|
25
25
|
|
|
26
26
|
import * as fs from "node:fs";
|
|
27
27
|
import * as path from "node:path";
|
|
28
|
+
import { homedir } from "node:os";
|
|
29
|
+
import { fileURLToPath } from "node:url";
|
|
28
30
|
import { Type } from "typebox";
|
|
29
31
|
import { contentText, normalizeContext, uuidv7 } from "@earendil-works/pi-ai";
|
|
30
32
|
import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-works/pi-ai";
|
|
31
33
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
32
|
-
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
34
|
+
import { buildSessionProjection, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
33
35
|
import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
34
36
|
|
|
35
37
|
// ============================================================================
|
|
@@ -77,7 +79,7 @@ const cfg = {
|
|
|
77
79
|
defaultCapBudget: (process.env.MECH_COMPACT_MAX_SUMMARY_CHARS
|
|
78
80
|
? { unit: "chars", value: intFromEnv("MECH_COMPACT_MAX_SUMMARY_CHARS", 80_000) }
|
|
79
81
|
: { unit: "percent", value: percentFromEnv("MECH_COMPACT_MAX_SUMMARY_PERCENT", 25) }) as CapBudget,
|
|
80
|
-
lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS",
|
|
82
|
+
lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 25),
|
|
81
83
|
lookupMaxCalls: lookupMaxCallsFromEnv(),
|
|
82
84
|
lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
|
|
83
85
|
argSnippetChars: 160,
|
|
@@ -645,6 +647,108 @@ ${r.text.join("\n")}
|
|
|
645
647
|
].join("\n\n");
|
|
646
648
|
}
|
|
647
649
|
|
|
650
|
+
// File annotations describe evidence, not a guarantee of filesystem freshness.
|
|
651
|
+
// Use Pi's projection for visibility, but recorded mutations can invalidate a
|
|
652
|
+
// snapshot even when the mutation's message was subsequently omitted.
|
|
653
|
+
interface FileEvidence {
|
|
654
|
+
kind: "read" | "write";
|
|
655
|
+
completeness?: "full" | "partial" | "unknown";
|
|
656
|
+
changed?: "edit" | "write";
|
|
657
|
+
orderUncertain?: boolean;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function fileEvidenceKey(file: string, cwd: string): string {
|
|
661
|
+
// Lexical normalization only: no stat/realpath, and no symlink-equivalence claim.
|
|
662
|
+
let normalized = file.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
|
|
663
|
+
if (normalized === "~") normalized = homedir();
|
|
664
|
+
else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) normalized = path.join(homedir(), normalized.slice(2));
|
|
665
|
+
if (normalized.startsWith("file://")) {
|
|
666
|
+
try { normalized = fileURLToPath(normalized); } catch { /* Unknown path syntax: keep it literal. */ }
|
|
667
|
+
}
|
|
668
|
+
return path.resolve(cwd, normalized);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function readCompleteness(args: Record<string, any>, message: Record<string, any>, replaced: boolean): "full" | "partial" | "unknown" {
|
|
672
|
+
const blocks = message.content;
|
|
673
|
+
if (replaced || !Array.isArray(blocks) || blocks.length !== 1 || blocks[0].type !== "text" || typeof blocks[0].text !== "string") return "unknown";
|
|
674
|
+
const text = blocks[0].text;
|
|
675
|
+
if (/^Read image file \[/.test(text)) return "unknown";
|
|
676
|
+
const truncation = message.details?.truncation;
|
|
677
|
+
if (truncation?.firstLineExceedsLimit) return "unknown"; // Only a warning, not file contents.
|
|
678
|
+
// Pi's read tool supplies these notices for both default and explicit limits.
|
|
679
|
+
if (truncation?.truncated === true || /\[(?:Showing lines [^\n]*Use offset=\d+ to continue\.|\d+ more lines in file\. Use offset=\d+ to continue\.)\]\s*$/.test(text)) return "partial";
|
|
680
|
+
const offset = args.offset ?? 1;
|
|
681
|
+
if (!Number.isInteger(offset) || offset < 1 || (args.limit != null && (!Number.isInteger(args.limit) || args.limit < 1))) return "unknown";
|
|
682
|
+
if (offset > 1) return "partial";
|
|
683
|
+
// A limit is not proof of partialness: without a continuation notice Pi reached EOF.
|
|
684
|
+
// Unknown argument schemas are not assumed to have Pi's read semantics.
|
|
685
|
+
return Object.keys(args).every((key) => ["path", "offset", "limit"].includes(key)) ? "full" : "unknown";
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function retainedFileEvidence(entries: SessionEntry[], firstKeptEntryId: string | undefined, cwd: string): Map<string, FileEvidence> {
|
|
689
|
+
const evidence = new Map<string, FileEvidence>();
|
|
690
|
+
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
691
|
+
if (cut < 0) return evidence;
|
|
692
|
+
const visible = new Map(buildSessionProjection(entries).entries.map((entry) => [entry.sourceEntry.id, entry.messages]));
|
|
693
|
+
const pending = new Map<string, { name: string; args: Record<string, any>; visible: boolean; orderUncertain: boolean } | null>();
|
|
694
|
+
const changed = (name: "edit" | "write", args: Record<string, any>) => {
|
|
695
|
+
if (typeof args.path !== "string") return;
|
|
696
|
+
const previous = evidence.get(fileEvidenceKey(args.path, cwd));
|
|
697
|
+
if (previous) previous.changed = name;
|
|
698
|
+
};
|
|
699
|
+
for (const entry of entries.slice(cut)) {
|
|
700
|
+
if (entry.type !== "message") continue;
|
|
701
|
+
const raw = entry.message as unknown as Record<string, any>;
|
|
702
|
+
const projected = visible.get(entry.id)?.find((message) => message.role === raw.role) as Record<string, any> | undefined;
|
|
703
|
+
if (raw.role === "assistant") {
|
|
704
|
+
const blocks = Array.isArray(raw.content) ? raw.content : [];
|
|
705
|
+
for (const block of blocks) {
|
|
706
|
+
if (block.type !== "toolCall" || typeof block.id !== "string") continue;
|
|
707
|
+
// Sibling calls may execute concurrently; result order is not read/write order.
|
|
708
|
+
const orderUncertain = typeof block.arguments?.path === "string" && blocks.some((other: any) =>
|
|
709
|
+
other !== block && other.type === "toolCall" && ["write", "edit"].includes(other.name) &&
|
|
710
|
+
typeof other.arguments?.path === "string" &&
|
|
711
|
+
fileEvidenceKey(other.arguments.path, cwd) === fileEvidenceKey(block.arguments.path, cwd));
|
|
712
|
+
const shown = projected?.content?.filter?.((b: any) => b.type === "toolCall" && b.id === block.id);
|
|
713
|
+
const sameCall = shown?.length === 1 && shown[0].name === block.name &&
|
|
714
|
+
JSON.stringify(shown[0].arguments) === JSON.stringify(block.arguments);
|
|
715
|
+
pending.set(block.id, pending.has(block.id) ? null : { name: block.name, args: block.arguments ?? {}, visible: sameCall, orderUncertain });
|
|
716
|
+
}
|
|
717
|
+
} else if (raw.role === "toolResult") {
|
|
718
|
+
const call = pending.get(raw.toolCallId);
|
|
719
|
+
pending.delete(raw.toolCallId);
|
|
720
|
+
if (call && call.name === raw.toolName && typeof call.args.path === "string" && raw.isError === false) {
|
|
721
|
+
const key = fileEvidenceKey(call.args.path, cwd);
|
|
722
|
+
if (call.name === "write" || call.name === "edit") changed(call.name, call.args);
|
|
723
|
+
if (call.visible && projected && call.name === "read") {
|
|
724
|
+
const completeness = readCompleteness(call.args, projected, projected.content !== raw.content);
|
|
725
|
+
const previous = evidence.get(key);
|
|
726
|
+
// A later partial read does not hide an earlier complete snapshot.
|
|
727
|
+
if (!previous || previous.changed || previous.orderUncertain || (previous.kind === "read" && previous.completeness !== "full"))
|
|
728
|
+
evidence.set(key, { kind: "read", completeness, orderUncertain: call.orderUncertain });
|
|
729
|
+
} else if (call.visible && call.name === "write" && typeof call.args.content === "string") {
|
|
730
|
+
evidence.set(key, { kind: "write", orderUncertain: call.orderUncertain });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
// Nested calls have metadata but no model-visible read outputs or write payloads.
|
|
734
|
+
for (const nested of raw.nestedCalls?.calls ?? []) {
|
|
735
|
+
if (nested.status === "ok" && (nested.name === "edit" || nested.name === "write")) changed(nested.name, nested.arguments ?? {});
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return evidence;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function fileEvidenceLabel(evidence: FileEvidence | undefined): string | undefined {
|
|
743
|
+
if (!evidence) return;
|
|
744
|
+
if (evidence.orderUncertain) return `${evidence.kind} in tail; order uncertain`;
|
|
745
|
+
if (evidence.changed) return `${evidence.kind} in tail, then ${evidence.changed === "edit" ? "edited" : "written"}`;
|
|
746
|
+
if (evidence.kind === "write") return "write content in tail";
|
|
747
|
+
return evidence.completeness === "unknown" ? "read output in tail" : `${evidence.completeness} read in tail`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const FILE_LIST_EXPLANATION = "File lists record earlier operations. Read/write annotations describe retained evidence as of this checkpoint, not live filesystem state; unannotated paths do not establish content visibility.";
|
|
751
|
+
|
|
648
752
|
const SECTION_HEADER = "### Compacted conversation (oldest first)";
|
|
649
753
|
const SPAN_CLOSE = "</compacted-span>";
|
|
650
754
|
const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
|
|
@@ -755,7 +859,7 @@ const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by t
|
|
|
755
859
|
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.";
|
|
756
860
|
|
|
757
861
|
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.
|
|
862
|
+
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. **Before using \`write\` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.**
|
|
759
863
|
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
864
|
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.`;
|
|
761
865
|
|
|
@@ -902,13 +1006,24 @@ async function buildMechanicalSummary(opts: {
|
|
|
902
1006
|
// verbatim boundary line. That closing line is the LAST line of the
|
|
903
1007
|
// checkpoint; everything after it is pi's retained verbatim tail.
|
|
904
1008
|
if (retainedReads) parts.push("", retainedReads);
|
|
905
|
-
const retainedPaths = new Set(opts.startupReads.reads.map((r) =>
|
|
1009
|
+
const retainedPaths = new Set(opts.startupReads.reads.map((r) => fileEvidenceKey(r.path, opts.cwd)));
|
|
906
1010
|
const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
|
|
907
|
-
if (hasFileLists)
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
1011
|
+
if (hasFileLists) {
|
|
1012
|
+
const evidence = retainedFileEvidence(opts.branchEntries, opts.firstKeptEntryId, opts.cwd);
|
|
1013
|
+
const knownTail = opts.branchEntries.some((entry) => entry.id === opts.firstKeptEntryId);
|
|
1014
|
+
const fileLine = (file: string, modified: boolean): string => {
|
|
1015
|
+
const key = fileEvidenceKey(file, opts.cwd);
|
|
1016
|
+
const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
|
|
1017
|
+
? "startup read output retained in checkpoint or tail; may be partial"
|
|
1018
|
+
: modified && knownTail ? "no read-tool output in tail" : undefined);
|
|
1019
|
+
return `${checkpointPath(file, opts.cwd)}${label ? ` (${label})` : ""}`;
|
|
1020
|
+
};
|
|
1021
|
+
parts.push("", FILE_LIST_EXPLANATION);
|
|
1022
|
+
if (opts.readFiles.length > 0)
|
|
1023
|
+
parts.push(`<read-files note="reads in compacted history; unless annotated, no retained read-tool output identified">\n${opts.readFiles.map((file) => fileLine(file, false)).join("\n")}\n</read-files>`);
|
|
1024
|
+
if (opts.modifiedFiles.length > 0)
|
|
1025
|
+
parts.push(`<modified-files note="modified in compacted history">\n${opts.modifiedFiles.map((file) => fileLine(file, true)).join("\n")}\n</modified-files>`);
|
|
1026
|
+
}
|
|
912
1027
|
parts.push("");
|
|
913
1028
|
parts.push(EVIDENCE_BOUNDARY_RULE);
|
|
914
1029
|
parts.push("");
|
|
@@ -1125,7 +1240,8 @@ function lookupPartialFindings(text: string, marker: string): string {
|
|
|
1125
1240
|
|
|
1126
1241
|
const LOOKUP_WRITEUP_PROMPT =
|
|
1127
1242
|
"Search is finished; no further tool calls are allowed. Report what you found so far: the facts you confirmed (with ENTRY ids), " +
|
|
1128
|
-
"what you
|
|
1243
|
+
"what you could not locate in the material searched, and where you'd look next. " +
|
|
1244
|
+
"Budget exhaustion or an incomplete search does not establish absence from the transcript.";
|
|
1129
1245
|
|
|
1130
1246
|
const LOOKUP_SYSTEM_PROMPT = `You are a context-lookup subagent for a coding agent whose main context was compacted by verbatim compaction. The full pre-compaction transcript — including assistant thinking blocks and complete tool outputs that were REMOVED from the main context — is in the transcript files named in the request.
|
|
1131
1247
|
|
|
@@ -1142,7 +1258,7 @@ Final answer rules (your final message is the ONLY text the main agent sees):
|
|
|
1142
1258
|
- Return only the important findings. Do not narrate your search process.
|
|
1143
1259
|
- Quote exact error messages, paths, values, and code verbatim where they matter.
|
|
1144
1260
|
- Cite the ENTRY id (and file) for each finding so the main agent can verify.
|
|
1145
|
-
-
|
|
1261
|
+
- A failed or incomplete search does not establish absence from the transcript. Distinguish "not found in the material searched" from "absent from the transcript". If the search was incomplete or budget-limited, state what you did not reach or confirm; do not claim the answer was never recorded or that the session ended before it occurred.
|
|
1146
1262
|
|
|
1147
1263
|
Provenance rules — label each finding with its source type:
|
|
1148
1264
|
- "user instruction" — what the user asked, pasted, or confirmed
|
|
@@ -1274,7 +1390,10 @@ async function runLookupSubagent(opts: {
|
|
|
1274
1390
|
if (text) lastText = text;
|
|
1275
1391
|
|
|
1276
1392
|
if (toolCalls.length === 0) {
|
|
1277
|
-
|
|
1393
|
+
const answer = text || "(subagent returned no answer)";
|
|
1394
|
+
return pagingOnlyNotified
|
|
1395
|
+
? lookupPartialFindings(answer, `[subagent reached the ${searchLimit}; findings may be incomplete]`)
|
|
1396
|
+
: truncateHead(answer, cfg.lookupAnswerMaxChars);
|
|
1278
1397
|
}
|
|
1279
1398
|
|
|
1280
1399
|
// Check the whole batch against cursors issued BEFORE this response.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: context-retrieval
|
|
3
|
-
description:
|
|
3
|
+
description: "Guidance for using context_lookup after compaction: how to target earlier evidence, phrase effective lookup questions, and handle incomplete findings."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Session context recovery
|
|
@@ -95,7 +95,7 @@ intended context parameters.
|
|
|
95
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.
|
|
96
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.
|
|
97
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.
|
|
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
|
|
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. **Before using `write` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.** This is not a blanket reread requirement for small exact-match `edit`s. File-list annotations describe retained evidence as of the checkpoint, not live filesystem state; a read or write payload may already be visible in the tail.
|
|
99
99
|
6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive.
|
|
100
100
|
|
|
101
101
|
## Independent exports
|