@foliox/transparent-compact-pi 0.8.6 → 0.8.8
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 +33 -4
- package/README.md +15 -0
- package/docs/DESIGN.md +87 -12
- package/extensions/index.ts +188 -39
- package/package.json +1 -1
- package/skills/context-retrieval/SKILL.md +27 -15
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased — initial release preparation
|
|
4
4
|
|
|
5
|
-
-
|
|
5
|
+
- Replace misleading file-list content-absence claims with compact retained-evidence
|
|
6
|
+
labels, recomputed from Pi's projected tail at each checkpoint. Distinguish full,
|
|
7
|
+
partial, and uncertain reads; visible write payloads; and subsequent tracked
|
|
8
|
+
changes. Preserve startup-read labels and give modified paths a narrowly factual
|
|
9
|
+
negative label when no retained read/write evidence is established. Read-list
|
|
10
|
+
headers state the negative default once instead of repeating it per path. No
|
|
11
|
+
extra filesystem reads, model calls, or source-content duplication.
|
|
12
|
+
- Add a narrow safeguard before whole-file `write` replacement: reread unless
|
|
13
|
+
current contents are already visible, and do not reconstruct unchanged sections
|
|
14
|
+
from memory. Small exact-match edits do not require a blanket reread.
|
|
15
|
+
|
|
16
|
+
- Advertise recovery positively as retrieving history hidden by compaction, with
|
|
17
|
+
explicit provenance and contradiction triggers in the lookup description, skill,
|
|
18
|
+
and post-compaction reminders. Distinguish historical observations from current
|
|
19
|
+
source contents; allow cheap rereads/recomputations and avoid blanket fact
|
|
20
|
+
re-verification. Re-orientation leads with ordinary input restoration and makes
|
|
21
|
+
lookup conditional on a hidden historical need, rather than reusing the tool
|
|
22
|
+
advertisement. Shorten fallback descriptions by referring to lookup's scope
|
|
23
|
+
rather than repeating it. Keep recovery scope, fallback, and filesystem boundaries.
|
|
24
|
+
|
|
25
|
+
- Make compaction tool signatures leaner: short outcome labels, relative project
|
|
26
|
+
paths, write sizes and edit counts instead of payload previews, and a single
|
|
27
|
+
ellipsis for abbreviated arguments. Keep bash previews at 160 characters and
|
|
28
|
+
preserve complete file-tool paths. Bound user bash-execution stubs too. Raw
|
|
29
|
+
history, retained outputs, and user/assistant prose are unchanged.
|
|
30
|
+
- Mark all size-trimmed spans, including partial removals and shortened user
|
|
31
|
+
messages; no longer label originally empty spans as trimmed.
|
|
32
|
+
|
|
33
|
+
- Scope recovery guidance to specific earlier details hidden by compaction in the
|
|
6
34
|
current conversation, not startup, project discovery, or missing requirements.
|
|
7
35
|
Filesystem restrictions apply only to that recovery workflow, not user-requested
|
|
8
36
|
session audits, debugging, or cross-session analysis. Remove the misleading
|
|
@@ -29,10 +57,11 @@
|
|
|
29
57
|
raw session history; previously saved spans are not rewritten. Managed
|
|
30
58
|
re-orientation messages continue to be regenerated instead.
|
|
31
59
|
- Tool signatures record per-call `ok`, `error`, or `unknown` outcomes from
|
|
32
|
-
matched tool-result metadata
|
|
60
|
+
matched tool-result metadata; the header explains that outputs are removed. Missing or
|
|
33
61
|
ambiguous outcomes are never inferred, including unlabelled older spans.
|
|
34
|
-
- Read-file entries distinguish retained startup reads from removed content; a closing
|
|
35
|
-
|
|
62
|
+
- Read-file entries distinguish retained startup reads from removed content; a closing
|
|
63
|
+
evidence rule directs historical evidence/provenance questions to lookup and
|
|
64
|
+
current-state questions to the source.
|
|
36
65
|
- The instruction envelope now has recovery explanations before all compacted
|
|
37
66
|
spans, one evidence-boundary warning after them, and numbered
|
|
38
67
|
recovery reminders plus brief recovery recap after the retained tail.
|
package/README.md
CHANGED
|
@@ -65,6 +65,21 @@ After another compaction, only the current checklist is presented: older generat
|
|
|
65
65
|
checklists are excluded from compacted spans and the retained tail. This is
|
|
66
66
|
instruction delivery, not a guarantee of model compliance.
|
|
67
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
|
+
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
|
+
|
|
68
83
|
### Automatic startup-read retention
|
|
69
84
|
|
|
70
85
|
Successful text reads between the first and second user prompts are retained when
|
package/docs/DESIGN.md
CHANGED
|
@@ -16,18 +16,66 @@ 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
|
|
23
|
-
results, not a guarantee that tests passed.
|
|
24
|
-
|
|
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.
|
|
25
37
|
|
|
26
38
|
All newly compacted custom messages follow the same stub policy, regardless of
|
|
27
39
|
extension, display setting, or content format. Long type names are abbreviated
|
|
28
40
|
like tool-call arguments. This applies even with the cap disabled. Previously
|
|
29
41
|
saved spans are not rewritten; older custom-message bodies may remain in them.
|
|
30
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
|
+
|
|
31
79
|
### Retained startup reads
|
|
32
80
|
|
|
33
81
|
On the first verbatim compaction, the extension scans successful text-only `read`
|
|
@@ -73,7 +121,10 @@ original branch, not from its summary prose.
|
|
|
73
121
|
Retained startup reads count as fixed budget overhead and are never trimmed.
|
|
74
122
|
Like an inherited base, they can exceed the budget by themselves; in that case
|
|
75
123
|
the extension warns and preserves them. The conversation-line budget still has
|
|
76
|
-
a 500-character minimum.
|
|
124
|
+
a 500-character minimum. Every span changed by the cap carries `trimmed="true"`
|
|
125
|
+
and a recovery note, including partial line removal and shortened user messages.
|
|
126
|
+
An originally empty span is not marked as trimmed. Originals remain recoverable
|
|
127
|
+
from the session.
|
|
77
128
|
|
|
78
129
|
|
|
79
130
|
### Session-backed lookup
|
|
@@ -114,12 +165,27 @@ by provider.
|
|
|
114
165
|
|
|
115
166
|
### Recover historical details
|
|
116
167
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
168
|
+
Compaction hides earlier details from the model's current view; the recorded history,
|
|
169
|
+
including tool outputs and reasoning, remains in the session. Recovery can retrieve
|
|
170
|
+
specific outputs, trace where an earlier finding came from or why a conclusion was
|
|
171
|
+
reached, and check historical evidence when earlier notes conflict with new evidence.
|
|
172
|
+
These triggers are advertised in the tool description and conditionally explained
|
|
173
|
+
in post-compaction reminders, not just in the skill body. Reminders lead with
|
|
174
|
+
restoring task-relevant inputs, current-file reads, and cheap recomputation;
|
|
175
|
+
compaction alone is not a lookup trigger. Advertising and re-orientation use
|
|
176
|
+
separate wording. The skill description also names provenance and contradictions.
|
|
177
|
+
This is guidance, not a guarantee of model compliance.
|
|
178
|
+
|
|
179
|
+
Re-read project files for their current contents. Prefer lookup for what was
|
|
180
|
+
observed earlier or to avoid repeating slow external research or expensive
|
|
181
|
+
computations; cheap local rereads (including downloaded sources) and recomputations
|
|
182
|
+
remain reasonable. Current external facts may require fresh research. Retrieval
|
|
183
|
+
establishes what was recorded, not whether an earlier conclusion was correct.
|
|
184
|
+
|
|
185
|
+
Use recovery for history established by this conversation or its checkpoint, not
|
|
186
|
+
project discovery, requirements never supplied, other sessions, or abandoned branches.
|
|
187
|
+
For unfamiliar project details or missing requirements, inspect project files or
|
|
188
|
+
ask the user instead.
|
|
123
189
|
|
|
124
190
|
For this recovery workflow, use the recovery tools rather than reading raw session
|
|
125
191
|
files through filesystem tools. This restriction does not apply to user-requested
|
|
@@ -176,8 +242,17 @@ The recovery reminders identify retained startup reads and the uncompacted tail
|
|
|
176
242
|
as available evidence. They ask for recovery only when task-relevant inputs are
|
|
177
243
|
missing, not for rediscovery of reading requirements or blanket document rereads.
|
|
178
244
|
They also distinguish restoring inputs from repeating completed writes, call for
|
|
179
|
-
inspecting Git state, and
|
|
180
|
-
|
|
245
|
+
inspecting Git state, and ask the agent to resolve task-relevant uncertainty or
|
|
246
|
+
contradictions using supporting output or current-state verification before treating
|
|
247
|
+
a claim as established. Retained prose can guide continuation without re-verifying
|
|
248
|
+
every fact; unresolved claims should be labelled unverified, and retrieved reasoning
|
|
249
|
+
remains a historical hypothesis. Historical outputs do not establish current file
|
|
250
|
+
or build/test state.
|
|
251
|
+
There is no blanket edit-target reread. Before replacing an existing file with
|
|
252
|
+
`write`, the guidance requires rereading unless current contents are already in
|
|
253
|
+
view, and forbids reconstructing unchanged sections from memory. Small exact-match
|
|
254
|
+
edits and newly created files do not acquire a blanket reread requirement.
|
|
255
|
+
It is a saved
|
|
181
256
|
custom message tagged with the current compaction entry ID, not a temporary nudge:
|
|
182
257
|
subsequent responses and user turns retain it in history before the work that
|
|
183
258
|
followed it. `before_agent_start` adds it on normal starts/resume when missing;
|
package/extensions/index.ts
CHANGED
|
@@ -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
|
// ============================================================================
|
|
@@ -419,22 +421,49 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
|
|
|
419
421
|
// Mechanical summary (what replaces the model summary in the session)
|
|
420
422
|
// ============================================================================
|
|
421
423
|
|
|
422
|
-
|
|
424
|
+
// Display-only shortening: never change raw arguments or resolve symlinks.
|
|
425
|
+
function checkpointPath(value: string, cwd: string): string {
|
|
426
|
+
const prefix = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
|
|
427
|
+
if (value === cwd) return ".";
|
|
428
|
+
return value.startsWith(prefix) ? value.slice(prefix.length) : value;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function checkpointCommand(command: string, cwd: string): string {
|
|
432
|
+
const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
433
|
+
// Match complete path prefixes, not sibling directories or URL fragments.
|
|
434
|
+
return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, "g"), "$1.");
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function argumentSnippet(value: unknown): string {
|
|
438
|
+
let s: string;
|
|
439
|
+
try {
|
|
440
|
+
s = JSON.stringify(value) ?? String(value);
|
|
441
|
+
} catch {
|
|
442
|
+
s = String(value);
|
|
443
|
+
}
|
|
444
|
+
return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
|
|
423
448
|
const parts: string[] = [];
|
|
424
449
|
for (const [k, v] of Object.entries(args ?? {})) {
|
|
425
450
|
let s: string;
|
|
426
|
-
|
|
427
|
-
s = JSON.stringify(v)
|
|
428
|
-
|
|
429
|
-
s =
|
|
430
|
-
|
|
431
|
-
|
|
451
|
+
if (["read", "write", "edit"].includes(name) && k === "path" && typeof v === "string")
|
|
452
|
+
s = JSON.stringify(checkpointPath(v, cwd)); // Keep the whole identifying path.
|
|
453
|
+
else if (name === "write" && k === "content" && typeof v === "string")
|
|
454
|
+
s = `<${v.length} chars>`;
|
|
455
|
+
else if (name === "edit" && k === "edits" && Array.isArray(v))
|
|
456
|
+
s = String(v.length);
|
|
457
|
+
else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
|
|
458
|
+
s = `<${v.length} chars>`;
|
|
459
|
+
else
|
|
460
|
+
s = argumentSnippet(name === "bash" && k === "command" && typeof v === "string" ? checkpointCommand(v, cwd) : v);
|
|
432
461
|
parts.push(`${k}=${s}`);
|
|
433
462
|
}
|
|
434
463
|
return `${name}(${parts.join(", ")})`;
|
|
435
464
|
}
|
|
436
465
|
|
|
437
|
-
function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
466
|
+
function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
|
|
438
467
|
// Pair calls with later results in Pi's selected messages only. Never infer
|
|
439
468
|
// outcomes from result text, assistant claims, or another branch/the kept tail.
|
|
440
469
|
const outcomes = new Map<object, "ok" | "error">();
|
|
@@ -470,7 +499,7 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
|
470
499
|
for (const block of m.content ?? []) {
|
|
471
500
|
if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
|
|
472
501
|
else if (block.type === "toolCall")
|
|
473
|
-
calls.push(`${toolCallSignature(String(block.name), block.arguments)} [${outcomes.get(block) ?? "unknown"}
|
|
502
|
+
calls.push(`${toolCallSignature(String(block.name), block.arguments, cwd)} [${outcomes.get(block) ?? "unknown"}]`);
|
|
474
503
|
// thinking blocks: removed by design (kept in the session)
|
|
475
504
|
}
|
|
476
505
|
if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
|
|
@@ -481,13 +510,13 @@ function summarizeMessages(messages: AgentMessage[]): string[] {
|
|
|
481
510
|
// removed by design (kept in the session)
|
|
482
511
|
break;
|
|
483
512
|
case "bashExecution":
|
|
484
|
-
lines.push(`[BashExecution]: $
|
|
513
|
+
lines.push(`[BashExecution]: ${toolCallSignature("bash", { command: String(m.command ?? "") }, cwd)} [output removed]`);
|
|
485
514
|
break;
|
|
486
515
|
case "custom":
|
|
487
516
|
// Our instruction envelope is regenerated, not conversation prose.
|
|
488
517
|
// Keep originals in raw history, but never carry old checklists into spans.
|
|
489
518
|
if (m.customType !== REORIENT_MESSAGE)
|
|
490
|
-
lines.push(`[Custom message]: ${toolCallSignature("custom", { type: m.customType })} [content removed — use context_lookup]`);
|
|
519
|
+
lines.push(`[Custom message]: ${toolCallSignature("custom", { type: m.customType }, cwd)} [content removed — use context_lookup]`);
|
|
491
520
|
break;
|
|
492
521
|
case "branchSummary":
|
|
493
522
|
case "compactionSummary":
|
|
@@ -611,13 +640,115 @@ function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstK
|
|
|
611
640
|
const retained = state.reads.filter((r) => !tail.has(r.entryId));
|
|
612
641
|
if (retained.length === 0) return "";
|
|
613
642
|
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
|
|
643
|
+
"Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool-call status labels refer to the conversation spans, where outputs are removed, not these retained copies.",
|
|
615
644
|
...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
645
|
${r.text.join("\n")}
|
|
617
646
|
</retained-read>`),
|
|
618
647
|
].join("\n\n");
|
|
619
648
|
}
|
|
620
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
|
+
|
|
621
752
|
const SECTION_HEADER = "### Compacted conversation (oldest first)";
|
|
622
753
|
const SPAN_CLOSE = "</compacted-span>";
|
|
623
754
|
const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
|
|
@@ -721,21 +852,25 @@ function capSpans(spans: string[][], budget: number): string[][] {
|
|
|
721
852
|
return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
|
|
722
853
|
}
|
|
723
854
|
|
|
724
|
-
const
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
855
|
+
const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
|
|
856
|
+
const RECOVERY_TRIGGERS = "Ask `context_lookup` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence.";
|
|
857
|
+
const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
|
|
858
|
+
const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
|
|
859
|
+
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.";
|
|
728
860
|
|
|
729
|
-
const
|
|
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.
|
|
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.**
|
|
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.
|
|
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.`;
|
|
730
865
|
|
|
731
|
-
const
|
|
866
|
+
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}`;
|
|
732
867
|
|
|
733
|
-
const RECOVERY_INSTRUCTIONS = `**Recovering
|
|
868
|
+
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}`;
|
|
734
869
|
|
|
735
|
-
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents;
|
|
870
|
+
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; use `context_lookup` when you need that historical evidence or its provenance, and inspect the source when you need current state.";
|
|
736
871
|
|
|
737
872
|
const REORIENT_MESSAGE = "transparent-compact:reorient";
|
|
738
|
-
const RECOVERY_RECAP = `**Recovery recap.**
|
|
873
|
+
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.`;
|
|
739
874
|
|
|
740
875
|
function latestVerbatimCompaction(entries: SessionEntry[]) {
|
|
741
876
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
@@ -835,10 +970,14 @@ async function buildMechanicalSummary(opts: {
|
|
|
835
970
|
if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
|
|
836
971
|
capped.forEach((lines, i) => {
|
|
837
972
|
const s = allSpans[i];
|
|
973
|
+
const trimmed = lines.length !== s.lines.length || lines.some((line, j) => line !== s.lines[j]);
|
|
838
974
|
const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
|
|
839
|
-
blocks.push(
|
|
840
|
-
|
|
841
|
-
|
|
975
|
+
blocks.push([
|
|
976
|
+
trimmed ? `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>` : open,
|
|
977
|
+
...(trimmed ? [SPAN_TRIMMED_NOTE] : []),
|
|
978
|
+
...lines,
|
|
979
|
+
SPAN_CLOSE,
|
|
980
|
+
].join("\n"));
|
|
842
981
|
});
|
|
843
982
|
|
|
844
983
|
const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
|
|
@@ -850,7 +989,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
850
989
|
opts.notify(MIXED_CONTEXT_WARNING);
|
|
851
990
|
}
|
|
852
991
|
parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
|
|
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 (
|
|
992
|
+
parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming; tool calls are kept as one-line signatures. Paths under the session working directory are shown relative to it (as `.` in shell commands). Write contents and edit payloads are replaced by sizes/counts; other argument snippets keep up to 160 characters followed by an ellipsis when abbreviated. Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
|
|
854
993
|
parts.push("- Tool status: ok = result not flagged as an error; error = result flagged as an error; unknown = no safely matched result/status. Output content is removed in all cases. ok does not prove a command or tests passed. Calls without a status in older spans have unknown outcomes.");
|
|
855
994
|
parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Previously saved spans are unchanged.");
|
|
856
995
|
parts.push(
|
|
@@ -867,13 +1006,24 @@ async function buildMechanicalSummary(opts: {
|
|
|
867
1006
|
// verbatim boundary line. That closing line is the LAST line of the
|
|
868
1007
|
// checkpoint; everything after it is pi's retained verbatim tail.
|
|
869
1008
|
if (retainedReads) parts.push("", retainedReads);
|
|
870
|
-
const retainedPaths = new Set(opts.startupReads.reads.map((r) =>
|
|
1009
|
+
const retainedPaths = new Set(opts.startupReads.reads.map((r) => fileEvidenceKey(r.path, opts.cwd)));
|
|
871
1010
|
const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
|
|
872
|
-
if (hasFileLists)
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
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
|
+
}
|
|
877
1027
|
parts.push("");
|
|
878
1028
|
parts.push(EVIDENCE_BOUNDARY_RULE);
|
|
879
1029
|
parts.push("");
|
|
@@ -1347,7 +1497,7 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
|
|
|
1347
1497
|
}
|
|
1348
1498
|
|
|
1349
1499
|
function registerDirectTools(pi: ExtensionAPI): void {
|
|
1350
|
-
const pre = "Fallback after context_lookup, when its findings are incomplete
|
|
1500
|
+
const pre = "Fallback after context_lookup, when its findings are incomplete; same scope as context_lookup. ";
|
|
1351
1501
|
const run = (ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, f: (t: Transcript[]) => string) => {
|
|
1352
1502
|
try {
|
|
1353
1503
|
const transcript = sessionTranscript(ctx);
|
|
@@ -1371,7 +1521,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1371
1521
|
name: "context_grep",
|
|
1372
1522
|
label: "Context: grep",
|
|
1373
1523
|
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.",
|
|
1374
|
-
promptSnippet: "Fallback: search this conversation's evidence
|
|
1524
|
+
promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
|
|
1375
1525
|
parameters: Type.Object(GREP_FIELDS),
|
|
1376
1526
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1377
1527
|
return run(ctx, (t) => grepTranscript(t, params));
|
|
@@ -1553,7 +1703,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1553
1703
|
const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
|
|
1554
1704
|
const spanFrom = toIso(msgTs(allMessages[0]));
|
|
1555
1705
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
1556
|
-
const spanLines = summarizeMessages(allMessages);
|
|
1706
|
+
const spanLines = summarizeMessages(allMessages, ctx.cwd);
|
|
1557
1707
|
|
|
1558
1708
|
// 3) Freeze startup references after the second user prompt, then carry
|
|
1559
1709
|
// their original outputs forward outside the trimmable conversation spans.
|
|
@@ -1612,11 +1762,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
1612
1762
|
label: "Context lookup",
|
|
1613
1763
|
executionMode: "sequential",
|
|
1614
1764
|
description:
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
promptSnippet: "Recover specific earlier conversation details lost through compaction",
|
|
1765
|
+
`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}`,
|
|
1766
|
+
promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
|
|
1618
1767
|
parameters: Type.Object({
|
|
1619
|
-
question: Type.String({ description: "
|
|
1768
|
+
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." }),
|
|
1620
1769
|
}),
|
|
1621
1770
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1622
1771
|
if (cfg.lookupMaxCalls > 0 && consecutiveLookups(ctx, toolCallId) >= cfg.lookupMaxCalls) {
|
package/package.json
CHANGED
|
@@ -1,22 +1,21 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: context-retrieval
|
|
3
|
-
description: Use context_lookup
|
|
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
8
|
## Applicability
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
requirements or an unfamiliar project do not imply forgotten context: inspect
|
|
15
|
-
project files or ask the user instead.
|
|
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.
|
|
16
14
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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.
|
|
20
19
|
|
|
21
20
|
User-requested session audits, debugging, and cross-session analysis are separate
|
|
22
21
|
tasks, not this recovery workflow. Its filesystem restrictions do not apply to
|
|
@@ -26,7 +25,7 @@ This skill pairs with the `@foliox/transparent-compact-pi` extension, which prov
|
|
|
26
25
|
|
|
27
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.
|
|
28
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.
|
|
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
|
|
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.
|
|
30
29
|
|
|
31
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.
|
|
32
31
|
|
|
@@ -34,8 +33,21 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
|
|
|
34
33
|
|
|
35
34
|
## When to use
|
|
36
35
|
|
|
37
|
-
-
|
|
38
|
-
-
|
|
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.
|
|
39
51
|
|
|
40
52
|
## How to ask
|
|
41
53
|
|
|
@@ -79,11 +91,11 @@ intended context parameters.
|
|
|
79
91
|
|
|
80
92
|
## Rules
|
|
81
93
|
|
|
82
|
-
1. **For recovery of details
|
|
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.
|
|
83
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.
|
|
84
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.
|
|
85
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.
|
|
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
|
|
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.
|
|
87
99
|
6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive.
|
|
88
100
|
|
|
89
101
|
## Independent exports
|