@foliox/transparent-compact-pi 0.11.2 → 0.11.4
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 +28 -0
- package/README.md +40 -7
- package/docs/DESIGN.md +94 -87
- package/extensions/index.ts +162 -266
- package/extensions/lib/read-retention-ui.ts +105 -0
- package/extensions/lib/read-retention.ts +228 -0
- package/extensions/lib/turn-context.ts +5 -1
- package/extensions/lib/turn-filter.ts +20 -4
- package/package.json +2 -2
- package/skills/context-retrieval/SKILL.md +7 -48
package/extensions/index.ts
CHANGED
|
@@ -26,7 +26,6 @@
|
|
|
26
26
|
import * as fs from "node:fs";
|
|
27
27
|
import * as path from "node:path";
|
|
28
28
|
import { homedir } from "node:os";
|
|
29
|
-
import { fileURLToPath } from "node:url";
|
|
30
29
|
import { Type } from "typebox";
|
|
31
30
|
import { contentText, normalizeContext, uuidv7 } from "@earendil-works/pi-ai";
|
|
32
31
|
import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-works/pi-ai";
|
|
@@ -40,7 +39,10 @@ import { Locations } from "./lib/tool-stubs/locations.mjs";
|
|
|
40
39
|
import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
|
|
41
40
|
import { FILTER_EXPLANATION, PREFLAG_ENTRY, AUTO_FILTER_ENTRY, FILTER_REVISION_ENTRY, autoFilterEnabled, preflaggedTurns,
|
|
42
41
|
filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
|
|
43
|
-
import type { FilterTurn, TurnSpan } from "./lib/turn-filter.js";
|
|
42
|
+
import type { FilterTurn, TurnSpan, ReadPosition } from "./lib/turn-filter.js";
|
|
43
|
+
import { readPath as fileEvidenceKey, readCatalog, readRetentionState, selectedReads, renderRetainedReads, retainedReadOutputs, retainReadSpans, READ_RETENTION_ENTRY } from "./lib/read-retention.js";
|
|
44
|
+
import type { ReadOutput, ReadRetention } from "./lib/read-retention.js";
|
|
45
|
+
import { pickRetainedReads } from "./lib/read-retention-ui.js";
|
|
44
46
|
import { FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint,
|
|
45
47
|
messageTokens, previewMessages, checkCheckpointBudget, checkContextBudget, isExpandedCheckpoint, checkpointContextMessages, retainedTailMessages, estimateContext } from "./lib/turn-context.js";
|
|
46
48
|
import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, TurnSlot } from "./lib/turn-context.js";
|
|
@@ -555,9 +557,10 @@ function bashOutputLabel(command: string, result: Record<string, any>): string {
|
|
|
555
557
|
return labels.join("; ");
|
|
556
558
|
}
|
|
557
559
|
|
|
558
|
-
|
|
560
|
+
interface MessageSource { entryId: string; owner: string | null }
|
|
561
|
+
async function summarizeMessages(messages: AgentMessage[], renderer: ToolRenderer, sources?: (MessageSource | null)[]): Promise<TurnSpan> {
|
|
559
562
|
const results = pairedToolResults(messages);
|
|
560
|
-
const lines: string[] = [], turnIds: (string | null)[] = [];
|
|
563
|
+
const lines: string[] = [], turnIds: (string | null)[] = [], readPositions: ReadPosition[] = [];
|
|
561
564
|
const tools: ToolLines = { version: 2, lines: [] };
|
|
562
565
|
for (const [messageIndex, msg] of messages.entries()) {
|
|
563
566
|
const start = lines.length;
|
|
@@ -590,9 +593,13 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
|
|
|
590
593
|
}
|
|
591
594
|
break;
|
|
592
595
|
}
|
|
593
|
-
case "toolResult":
|
|
594
|
-
//
|
|
596
|
+
case "toolResult": {
|
|
597
|
+
// Keep a structural insertion point even when retention is OFF. Outputs
|
|
598
|
+
// are fetched from the session only when rendering a selected read.
|
|
599
|
+
const source = sources?.[messageIndex];
|
|
600
|
+
if (m.toolName === "read" && source) readPositions.push({ entryId: source.entryId, index: lines.length });
|
|
595
601
|
break;
|
|
602
|
+
}
|
|
596
603
|
case "bashExecution": {
|
|
597
604
|
const calls = [await renderer.render("bash", { command: String(m.command ?? "") }, " [output removed]")];
|
|
598
605
|
const prefix = "[BashExecution]: ";
|
|
@@ -613,138 +620,9 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
|
|
|
613
620
|
default:
|
|
614
621
|
break;
|
|
615
622
|
}
|
|
616
|
-
for (let i = start; i < lines.length; i++) turnIds.push(
|
|
623
|
+
for (let i = start; i < lines.length; i++) turnIds.push(sources?.[messageIndex]?.owner ?? null);
|
|
617
624
|
}
|
|
618
|
-
return { lines, ...(
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
// Startup reference retention is a lexical heuristic, not an interpretation of
|
|
622
|
-
// required-reading prose. Snapshot actual text read results; never open files.
|
|
623
|
-
interface StartupRead {
|
|
624
|
-
entryId: string;
|
|
625
|
-
path: string;
|
|
626
|
-
offset?: number;
|
|
627
|
-
limit?: number;
|
|
628
|
-
text: string[];
|
|
629
|
-
}
|
|
630
|
-
interface StartupReads {
|
|
631
|
-
version: 1;
|
|
632
|
-
closed: boolean;
|
|
633
|
-
reads: StartupRead[];
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
function isInstructionFile(file: string): boolean {
|
|
637
|
-
return /^(AGENTS(?:\.override)?|CLAUDE)\.md$/i.test(path.basename(file));
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
function mentionsPath(content: string, name: string): boolean {
|
|
641
|
-
if (!name) return false;
|
|
642
|
-
// A bare name can match, but not as a substring of another path or filename.
|
|
643
|
-
// Permit sentence-final punctuation, Markdown delimiters and link anchors.
|
|
644
|
-
const word = /[\p{L}\p{N}_./\\-]/u;
|
|
645
|
-
for (let at = content.indexOf(name); at >= 0; at = content.indexOf(name, at + 1)) {
|
|
646
|
-
const end = at + name.length;
|
|
647
|
-
const before = content[at - 1];
|
|
648
|
-
const after = content[end];
|
|
649
|
-
if ((!before || !word.test(before)) &&
|
|
650
|
-
(!after || !word.test(after) || (after === "." && (!content[end + 1] || /\s/.test(content[end + 1]))))) return true;
|
|
651
|
-
}
|
|
652
|
-
return false;
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
function startupReads(entries: SessionEntry[], ctx: ExtensionContext): StartupReads {
|
|
656
|
-
const latest = entries.findLast((e) => e.type === "compaction");
|
|
657
|
-
const previous = latest?.type === "compaction" &&
|
|
658
|
-
(latest.details as { kind?: string })?.kind === MECH_KIND
|
|
659
|
-
? (latest.details as { startupReads?: StartupReads }).startupReads : undefined;
|
|
660
|
-
// Once the second user prompt has arrived, the selection and output bytes are
|
|
661
|
-
// frozen. Repeated compaction does not parse or compact an earlier checkpoint.
|
|
662
|
-
if (previous?.version === 1 && previous.closed) return previous;
|
|
663
|
-
|
|
664
|
-
const prompts = entries.filter((e) => e.type === "message" && e.message.role === "user");
|
|
665
|
-
const first = prompts[0] ? entries.indexOf(prompts[0]) : -1;
|
|
666
|
-
const second = prompts[1] ? entries.indexOf(prompts[1]) : entries.length;
|
|
667
|
-
const state: StartupReads = { version: 1, closed: prompts.length >= 2, reads: previous?.reads.slice() ?? [] };
|
|
668
|
-
if (first < 0) return state;
|
|
669
|
-
|
|
670
|
-
const sources = (ctx.getSystemPromptOptions?.().contextFiles ?? [])
|
|
671
|
-
.filter((f) => isInstructionFile(f.path)).map((f) => ({ path: f.path, content: f.content }));
|
|
672
|
-
// Older/custom contexts may expose only the rendered prompt. Restrict fallback
|
|
673
|
-
// extraction to named project-instruction blocks, never arbitrary prompt prose.
|
|
674
|
-
if (sources.length === 0) {
|
|
675
|
-
for (const match of (ctx.getSystemPrompt?.() ?? "").matchAll(/<project_instructions path="([^"]+)">\n?([\s\S]*?)<\/project_instructions>/g)) {
|
|
676
|
-
if (isInstructionFile(match[1])) sources.push({ path: match[1], content: match[2] });
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
// Respect explicit context omissions/replacements when selecting original
|
|
681
|
-
// reads. Raw session text remains recoverable, but is not silently resurrected.
|
|
682
|
-
const edits = new Map(entries.filter((e) => e.type === "context_edit").map((e) => [e.targetId, e.replacement]));
|
|
683
|
-
const pending = new Map<string, { name: string; args: Record<string, any> } | null>();
|
|
684
|
-
const reads: StartupRead[] = [];
|
|
685
|
-
for (const entry of entries.slice(first + 1, second)) {
|
|
686
|
-
if (entry.type !== "message" || edits.get(entry.id) === null) continue;
|
|
687
|
-
const msg = entry.message;
|
|
688
|
-
const content = edits.get(entry.id)?.content ?? (msg as { content?: unknown }).content;
|
|
689
|
-
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
690
|
-
if (!Array.isArray(blocks)) continue;
|
|
691
|
-
if (msg.role === "assistant") {
|
|
692
|
-
for (const b of blocks) {
|
|
693
|
-
if (b.type !== "toolCall" || typeof b.id !== "string") continue;
|
|
694
|
-
pending.set(b.id, pending.has(b.id) ? null : { name: b.name, args: b.arguments ?? {} });
|
|
695
|
-
}
|
|
696
|
-
} else if (msg.role === "toolResult") {
|
|
697
|
-
const call = pending.get(msg.toolCallId);
|
|
698
|
-
if (!call || call.name !== msg.toolName) continue;
|
|
699
|
-
pending.delete(msg.toolCallId);
|
|
700
|
-
if (call.name !== "read" || msg.isError !== false || typeof call.args.path !== "string" ||
|
|
701
|
-
blocks.length === 0 || blocks.some((b) => b.type !== "text" || typeof b.text !== "string")) continue;
|
|
702
|
-
const read: StartupRead = { entryId: entry.id, path: call.args.path,
|
|
703
|
-
...(typeof call.args.offset === "number" ? { offset: call.args.offset } : {}),
|
|
704
|
-
...(typeof call.args.limit === "number" ? { limit: call.args.limit } : {}),
|
|
705
|
-
text: blocks.map((b) => b.text) };
|
|
706
|
-
reads.push(read);
|
|
707
|
-
// Also recognize instruction files explicitly read during startup, e.g.
|
|
708
|
-
// nested AGENTS.md files not automatically loaded into the system prompt.
|
|
709
|
-
if (isInstructionFile(read.path)) sources.push({ path: read.path, content: read.text.join("\n") });
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
const known = new Set(state.reads.map((r) => r.entryId));
|
|
713
|
-
for (const read of reads) {
|
|
714
|
-
const absolute = path.resolve(ctx.cwd, read.path);
|
|
715
|
-
const names = [read.path, absolute, path.relative(ctx.cwd, absolute), path.basename(absolute)];
|
|
716
|
-
if (!known.has(read.entryId) && sources.some((source) =>
|
|
717
|
-
[...names, path.relative(path.dirname(path.resolve(ctx.cwd, source.path)), absolute)]
|
|
718
|
-
.some((name) => mentionsPath(source.content, name)))) {
|
|
719
|
-
state.reads.push(read);
|
|
720
|
-
known.add(read.entryId);
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
return state;
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstKeptEntryId?: string): string {
|
|
727
|
-
const cut = entries.findIndex((e) => e.id === firstKeptEntryId);
|
|
728
|
-
const tail = new Set(cut < 0 ? [] : entries.slice(cut).map((e) => e.id));
|
|
729
|
-
const retained = state.reads.filter((r) => !tail.has(r.entryId));
|
|
730
|
-
if (retained.length === 0) return "";
|
|
731
|
-
return ["### Retained startup reads",
|
|
732
|
-
"Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool-call status labels refer to the conversation spans, not these retained copies.",
|
|
733
|
-
...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}`}>
|
|
734
|
-
${r.text.join("\n")}
|
|
735
|
-
</retained-read>`),
|
|
736
|
-
].join("\n\n");
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
function fileEvidenceKey(file: string, cwd: string): string {
|
|
740
|
-
// Lexical normalization only: no stat/realpath, and no symlink-equivalence claim.
|
|
741
|
-
let normalized = file.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
|
|
742
|
-
if (normalized === "~") normalized = homedir();
|
|
743
|
-
else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) normalized = path.join(homedir(), normalized.slice(2));
|
|
744
|
-
if (normalized.startsWith("file://")) {
|
|
745
|
-
try { normalized = fileURLToPath(normalized); } catch { /* Unknown path syntax: keep it literal. */ }
|
|
746
|
-
}
|
|
747
|
-
return path.resolve(cwd, normalized);
|
|
625
|
+
return { lines, ...(sources ? { turnIds } : {}), ...(readPositions.length ? { readPositions } : {}), ...(tools.lines.length ? { tools } : {}) };
|
|
748
626
|
}
|
|
749
627
|
|
|
750
628
|
const SECTION_HEADER = "### Compacted conversation (oldest first)";
|
|
@@ -813,6 +691,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
|
|
|
813
691
|
lines: sd.lines,
|
|
814
692
|
tools: sd.tools,
|
|
815
693
|
turnIds: sd.turnIds,
|
|
694
|
+
readPositions: sd.readPositions,
|
|
816
695
|
});
|
|
817
696
|
}
|
|
818
697
|
return { base, spans };
|
|
@@ -825,6 +704,7 @@ interface FilterRevision {
|
|
|
825
704
|
keptAsideTurnIds: string[];
|
|
826
705
|
fidelity?: TurnFidelities;
|
|
827
706
|
slots?: TurnSlot[];
|
|
707
|
+
readRetention: ReadRetention;
|
|
828
708
|
}
|
|
829
709
|
|
|
830
710
|
function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
|
|
@@ -871,15 +751,15 @@ function projectCheckpoint(messages: AgentMessage[], entries: SessionEntry[]): A
|
|
|
871
751
|
|
|
872
752
|
// Match Pi's prepared messages to their source entries, including explicit
|
|
873
753
|
// context replacements and generated custom messages. No raw bodies are stored.
|
|
874
|
-
function
|
|
754
|
+
function preparedMessageSources(entries: SessionEntry[], messages: AgentMessage[]): (MessageSource | null)[] {
|
|
875
755
|
const owners = turnOwners(entries);
|
|
876
|
-
const queues = new Map<string,
|
|
756
|
+
const queues = new Map<string, MessageSource[]>();
|
|
877
757
|
for (const projected of buildSessionProjection(entries).entries) {
|
|
878
758
|
if (projected.sourceEntry.type === "compaction") continue;
|
|
879
759
|
for (const message of projected.messages) {
|
|
880
760
|
const key = JSON.stringify(message);
|
|
881
761
|
const queue = queues.get(key) ?? [];
|
|
882
|
-
queue.push(owners.get(projected.sourceEntry.id) ?? null);
|
|
762
|
+
queue.push({ entryId: projected.sourceEntry.id, owner: owners.get(projected.sourceEntry.id) ?? null });
|
|
883
763
|
queues.set(key, queue);
|
|
884
764
|
}
|
|
885
765
|
}
|
|
@@ -887,21 +767,18 @@ function preparedTurnOwners(entries: SessionEntry[], messages: AgentMessage[]):
|
|
|
887
767
|
}
|
|
888
768
|
|
|
889
769
|
function filterChoices(entries: SessionEntry[], spans: TurnSpan[], excluded: Set<string>, firstKeptEntryId: string,
|
|
890
|
-
retained:
|
|
770
|
+
retained: ReadOutput[], selected = excluded, fidelity: TurnFidelities = turnFidelities(entries)): FilterTurn[] {
|
|
891
771
|
const owners = turnOwners(entries), flagged = preflaggedTurns(entries);
|
|
892
772
|
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
893
773
|
const tailOwners = new Set(entries.slice(cut).filter((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary")
|
|
894
774
|
.map((entry) => owners.get(entry.id)));
|
|
895
775
|
const lines = new Map<string, string[]>();
|
|
896
|
-
|
|
776
|
+
const inline = retainReadSpans(spans, retained.filter((read) =>
|
|
777
|
+
entries.findIndex((entry) => entry.id === read.entryId) < cut && !fidelity[read.owner ?? ""]), excluded);
|
|
778
|
+
for (const span of inline.spans) span.lines.forEach((line, index) => {
|
|
897
779
|
const owner = span.turnIds?.[index];
|
|
898
780
|
if (owner) { const group = lines.get(owner) ?? []; group.push(line); lines.set(owner, group); }
|
|
899
781
|
});
|
|
900
|
-
for (const read of retained.reads) {
|
|
901
|
-
const owner = owners.get(read.entryId);
|
|
902
|
-
if (owner && entries.findIndex((entry) => entry.id === read.entryId) < cut)
|
|
903
|
-
lines.get(owner)?.push(`[Retained startup read: ${read.path}]\n${read.text.join("\n")}`);
|
|
904
|
-
}
|
|
905
782
|
return entries.filter((entry) => entry.type === "message" && entry.message.role === "user").map((entry) => {
|
|
906
783
|
const content = lines.get(entry.id) ?? [];
|
|
907
784
|
const deferred = tailOwners.has(entry.id);
|
|
@@ -955,15 +832,11 @@ function excludedFilePaths(entries: SessionEntry[], excluded: Set<string>, first
|
|
|
955
832
|
}
|
|
956
833
|
|
|
957
834
|
function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, cwd: string,
|
|
958
|
-
|
|
959
|
-
if (!excluded.size
|
|
960
|
-
const owners = turnOwners(entries);
|
|
835
|
+
readRetention: ReadRetention, readFiles: string[], modifiedFiles: string[], excluded: Set<string>) {
|
|
836
|
+
if (!excluded.size) return { readRetention, readFiles, modifiedFiles };
|
|
961
837
|
const removedPaths = excludedFilePaths(entries, excluded, firstKeptEntryId, cwd);
|
|
962
838
|
return {
|
|
963
|
-
|
|
964
|
-
const owner = owners.get(read.entryId) ?? "";
|
|
965
|
-
return !excluded.has(owner) && !fidelity[owner];
|
|
966
|
-
}) },
|
|
839
|
+
readRetention,
|
|
967
840
|
readFiles: readFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
968
841
|
modifiedFiles: modifiedFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
969
842
|
};
|
|
@@ -974,20 +847,20 @@ const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current conten
|
|
|
974
847
|
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.";
|
|
975
848
|
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.";
|
|
976
849
|
|
|
977
|
-
const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_NOTE}
|
|
850
|
+
const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_NOTE} Selected retained reads and the uncompacted tail remain available as evidence. Recover only hidden information needed for the current task.
|
|
978
851
|
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.**
|
|
979
852
|
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.
|
|
980
853
|
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.`;
|
|
981
854
|
|
|
982
|
-
const REVISION_NOTE_PREFIX = "-
|
|
855
|
+
const REVISION_NOTE_PREFIX = "- Checkpoint context revised: ";
|
|
983
856
|
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}`;
|
|
984
857
|
|
|
985
|
-
const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Use \`context_lookup\` with a specific historical question: a subagent searches this conversation's full session history and returns relevant findings. Use the recovery tools for history established by this conversation or its checkpoint, not for project discovery or exploration of other sessions
|
|
858
|
+
const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Use \`context_lookup\` with a specific historical question: a subagent searches this conversation's full session history and returns relevant findings. Use the recovery tools for history established by this conversation or its checkpoint, not for project discovery or exploration of other sessions.`;
|
|
986
859
|
|
|
987
860
|
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Use `context_lookup` for omitted observations or provenance; inspect sources for current state.";
|
|
988
861
|
|
|
989
862
|
const REORIENT_MESSAGE = "transparent-compact:reorient";
|
|
990
|
-
const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead.
|
|
863
|
+
const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead. ${RECOVERY_FILESYSTEM_RULE} Keep these evidence/recovery rules in force as work continues.`;
|
|
991
864
|
|
|
992
865
|
function latestVerbatimCompaction(entries: SessionEntry[]) {
|
|
993
866
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
@@ -1069,6 +942,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
1069
942
|
spanTools?: ToolLines; // display records; no raw command/program payloads
|
|
1070
943
|
locations?: LocationEntry[];
|
|
1071
944
|
spanTurnIds?: (string | null)[];
|
|
945
|
+
spanReadPositions?: ReadPosition[];
|
|
1072
946
|
filteredTurnIds?: string[];
|
|
1073
947
|
fidelity?: TurnFidelities;
|
|
1074
948
|
slots?: TurnSlot[]; // generated output placements; no raw payloads
|
|
@@ -1076,7 +950,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
1076
950
|
spanFrom?: string; // ISO timestamp of the first summarised message
|
|
1077
951
|
spanTo?: string; // ISO timestamp of the last summarised message
|
|
1078
952
|
firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
|
|
1079
|
-
|
|
953
|
+
readRetention: ReadRetention;
|
|
1080
954
|
cwd: string;
|
|
1081
955
|
notify: (msg: string) => void;
|
|
1082
956
|
chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
|
|
@@ -1086,10 +960,15 @@ async function buildMechanicalSummary(opts: {
|
|
|
1086
960
|
const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
|
|
1087
961
|
const nativeMessages = [...native.values()].flat();
|
|
1088
962
|
const nativeChars = messageTokens(nativeMessages) * 4;
|
|
1089
|
-
const
|
|
963
|
+
const excluded = new Set(opts.filteredTurnIds);
|
|
964
|
+
const retained = retainedReadOutputs(readCatalog(opts.branchEntries, opts.cwd), opts.readRetention,
|
|
965
|
+
opts.branchEntries, opts.firstKeptEntryId, fidelity);
|
|
966
|
+
const inserted = retainReadSpans(opts.revisedAt ? spans : [...spans, {
|
|
1090
967
|
at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
|
|
1091
|
-
lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
|
|
1092
|
-
}],
|
|
968
|
+
lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds, readPositions: opts.spanReadPositions,
|
|
969
|
+
}], retained, excluded);
|
|
970
|
+
if (inserted.unplaced.length) throw new Error(`Cannot retain read ${inserted.unplaced[0].entryId} (${inserted.unplaced[0].path}): its original position is not in a verbatim span. Choose another read or set it to OFF.`);
|
|
971
|
+
const rendered = fidelitySpans(filterSpans(inserted.spans, excluded), fidelity);
|
|
1093
972
|
const allSpans = rendered.spans;
|
|
1094
973
|
const locations = new Locations(opts.cwd, opts.locations ?? checkpointLocations(opts.branchEntries));
|
|
1095
974
|
const dictionary = (ids: string[]) => locations.render(new Set(ids));
|
|
@@ -1097,12 +976,13 @@ async function buildMechanicalSummary(opts: {
|
|
|
1097
976
|
const allLocationIds = allSpans.flatMap((span) => span.tools?.lines.flatMap((line) => line.calls.flatMap((call) => call.locations ?? [])) ?? []);
|
|
1098
977
|
const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
|
|
1099
978
|
|
|
1100
|
-
//
|
|
1101
|
-
// The base and
|
|
1102
|
-
// exceed the budget by itself; warn rather than silently dropping evidence.
|
|
979
|
+
// Inline reads count in span size exactly once and are structurally protected
|
|
980
|
+
// from capping. The opaque base and native messages remain fixed overhead.
|
|
1103
981
|
const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
|
|
1104
|
-
const
|
|
1105
|
-
|
|
982
|
+
const retainedChars = allSpans.reduce((total, span) => total + (span.protectedLines ?? [])
|
|
983
|
+
.filter((index) => !rendered.markers.has(span.turnIds?.[index] ?? ""))
|
|
984
|
+
.reduce((n, index) => n + span.lines[index].length + 1, 0), 0);
|
|
985
|
+
let overhead = nativeChars + SECTION_HEADER.length + 2;
|
|
1106
986
|
if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
|
|
1107
987
|
overhead += allSpans.reduce(
|
|
1108
988
|
(a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + TIGHTENED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
|
|
@@ -1124,8 +1004,8 @@ async function buildMechanicalSummary(opts: {
|
|
|
1124
1004
|
if (maxChars === null) return undefined;
|
|
1125
1005
|
if (maxChars !== undefined && base && base.summary.length > maxChars)
|
|
1126
1006
|
opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
|
|
1127
|
-
if (maxChars !== undefined &&
|
|
1128
|
-
opts.notify(`transparent-compact: retained
|
|
1007
|
+
if (maxChars !== undefined && retainedChars > maxChars)
|
|
1008
|
+
opts.notify(`transparent-compact: retained reads alone are ${retainedChars.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
|
|
1129
1009
|
if (maxChars !== undefined && nativeChars > maxChars)
|
|
1130
1010
|
opts.notify(`transparent-compact: full-fidelity turns alone are ~${nativeChars.toLocaleString()} estimated chars (budget ${maxChars.toLocaleString()}); they are kept un-capped. Only PROSE can be trimmed.`);
|
|
1131
1011
|
const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost);
|
|
@@ -1171,11 +1051,10 @@ async function buildMechanicalSummary(opts: {
|
|
|
1171
1051
|
parts.push(SECTION_HEADER);
|
|
1172
1052
|
parts.push("");
|
|
1173
1053
|
parts.push(blocks.length > 0 ? blocks.join("\n\n") : "(no user or assistant prose in these spans — use context_lookup)");
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
if (retainedReads) parts.push("", retainedReads);
|
|
1054
|
+
// The location dictionary stays above the LAST checkpoint line; everything
|
|
1055
|
+
// after that line is Pi's verbatim tail.
|
|
1177
1056
|
const locationTable = dictionary(capped.locationIds);
|
|
1178
|
-
if (locationTable) parts.push("", locationTable);
|
|
1057
|
+
if (locationTable) parts.push("", "The following location dictionary resolves `@N` references above; it is not part of the conversation.", locationTable);
|
|
1179
1058
|
parts.push("");
|
|
1180
1059
|
parts.push(EVIDENCE_BOUNDARY_RULE);
|
|
1181
1060
|
parts.push("");
|
|
@@ -1367,8 +1246,7 @@ function showEntry(transcripts: Transcript[], opts: { id: string; includeRelated
|
|
|
1367
1246
|
}) : `No entry with id "${opts.id}" found.`;
|
|
1368
1247
|
}
|
|
1369
1248
|
|
|
1370
|
-
//
|
|
1371
|
-
// subagent accepts a logical transcript name (not a filesystem path).
|
|
1249
|
+
// Subagent paging parameters use logical transcript names, not filesystem paths.
|
|
1372
1250
|
const OFFSET_FIELD = Type.Optional(Type.Integer({ minimum: 0, description: "Character offset (UTF-16 units, default 0). Use the next offset reported by the previous page." }));
|
|
1373
1251
|
const FILE_FIELD = Type.Optional(Type.String({ description: "Logical transcript name. Omit for all." }));
|
|
1374
1252
|
const THROUGH_ENTRY_FIELD = Type.Optional(Type.String({ description: "Last ENTRY id included in this paginated listing/search. Keep the reported throughEntry on subsequent pages to exclude newly appended calls/results; omit to start a fresh search." }));
|
|
@@ -1389,15 +1267,12 @@ const SHOW_FIELDS = {
|
|
|
1389
1267
|
offset: OFFSET_FIELD,
|
|
1390
1268
|
};
|
|
1391
1269
|
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
// Append outside the truncated findings so the next-step guidance survives
|
|
1396
|
-
// even a long write-up. Normal successful answers remain unchanged.
|
|
1270
|
+
// Keep the incomplete-findings marker outside the truncated write-up.
|
|
1271
|
+
// Normal successful answers remain unchanged.
|
|
1397
1272
|
function lookupPartialFindings(text: string, marker: string): string {
|
|
1398
1273
|
const status = truncateHead(marker, 1_000); // Provider error messages can be large too.
|
|
1399
|
-
const budget = cfg.lookupAnswerMaxChars - status.length -
|
|
1400
|
-
return `${truncateHead(text, budget)}\n${status}
|
|
1274
|
+
const budget = cfg.lookupAnswerMaxChars - status.length - 1;
|
|
1275
|
+
return `${truncateHead(text, budget)}\n${status}`;
|
|
1401
1276
|
}
|
|
1402
1277
|
|
|
1403
1278
|
const LOOKUP_WRITEUP_PROMPT =
|
|
@@ -1630,13 +1505,11 @@ function sessionTranscript(ctx: { sessionManager: { getBranch: () => SessionEntr
|
|
|
1630
1505
|
}
|
|
1631
1506
|
|
|
1632
1507
|
// ============================================================================
|
|
1633
|
-
// Main-agent
|
|
1508
|
+
// Main-agent lookup admission
|
|
1634
1509
|
// ============================================================================
|
|
1635
1510
|
|
|
1636
|
-
const FALLBACK_TOOL_NAMES = new Set(["context_list_entries", "context_grep", "context_show_entry"]);
|
|
1637
|
-
|
|
1638
1511
|
/** Count prior lookup attempts since the last user/ordinary-work/bash boundary.
|
|
1639
|
-
*
|
|
1512
|
+
* Text and thinking neither increase nor reset the count. Deduplicate call/result ids, and include
|
|
1640
1513
|
* earlier siblings in the current assistant message even before results exist:
|
|
1641
1514
|
* two parallel lookups cannot both claim the first slot. Later siblings are
|
|
1642
1515
|
* excluded. Raw branch state follows reload, resume, compaction, and forks. */
|
|
@@ -1649,11 +1522,10 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
|
|
|
1649
1522
|
const m = e.message;
|
|
1650
1523
|
if (m.role === "user" || m.role === "bashExecution") break;
|
|
1651
1524
|
if (m.role === "toolResult") {
|
|
1652
|
-
if (FALLBACK_TOOL_NAMES.has(m.toolName)) continue;
|
|
1653
1525
|
if (m.toolName !== "context_lookup") break;
|
|
1654
1526
|
calls.add(m.toolCallId);
|
|
1655
1527
|
} else if (m.role === "assistant") {
|
|
1656
|
-
for (const b of m.content) {
|
|
1528
|
+
for (const b of m.content ?? []) {
|
|
1657
1529
|
if (b.type !== "toolCall") continue;
|
|
1658
1530
|
if (b.id === toolCallId) break;
|
|
1659
1531
|
if (b.name === "context_lookup") calls.add(b.id);
|
|
@@ -1663,49 +1535,6 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
|
|
|
1663
1535
|
return calls.size;
|
|
1664
1536
|
}
|
|
1665
1537
|
|
|
1666
|
-
function registerDirectTools(pi: ExtensionAPI): void {
|
|
1667
|
-
const pre = "Fallback after context_lookup, when its findings are incomplete; same scope as context_lookup. ";
|
|
1668
|
-
const run = (ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, f: (t: Transcript[]) => string) => {
|
|
1669
|
-
try {
|
|
1670
|
-
const transcript = sessionTranscript(ctx);
|
|
1671
|
-
if (transcript.index.length === 0) return { content: [{ type: "text" as const, text: "No entries found on the session branch." }], details: undefined };
|
|
1672
|
-
return { content: [{ type: "text" as const, text: f([transcript]) }], details: undefined };
|
|
1673
|
-
} catch (err) {
|
|
1674
|
-
return { content: [{ type: "text" as const, text: `Tool error: ${errMsg(err)}` }], details: undefined };
|
|
1675
|
-
}
|
|
1676
|
-
};
|
|
1677
|
-
pi.registerTool({
|
|
1678
|
-
name: "context_list_entries",
|
|
1679
|
-
label: "Context: list entries",
|
|
1680
|
-
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).",
|
|
1681
|
-
promptSnippet: "Fallback: list this conversation's entries for post-compaction recovery",
|
|
1682
|
-
parameters: Type.Object(LIST_FIELDS),
|
|
1683
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1684
|
-
return run(ctx, (t) => listEntries(t, params));
|
|
1685
|
-
},
|
|
1686
|
-
});
|
|
1687
|
-
pi.registerTool({
|
|
1688
|
-
name: "context_grep",
|
|
1689
|
-
label: "Context: grep",
|
|
1690
|
-
description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
|
|
1691
|
-
promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
|
|
1692
|
-
parameters: Type.Object(GREP_FIELDS),
|
|
1693
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1694
|
-
return run(ctx, (t) => grepTranscript(t, params));
|
|
1695
|
-
},
|
|
1696
|
-
});
|
|
1697
|
-
pi.registerTool({
|
|
1698
|
-
name: "context_show_entry",
|
|
1699
|
-
label: "Context: show entry",
|
|
1700
|
-
description: "Read a known raw session entry to recover a specific detail hidden by compaction. Use an ENTRY id returned by context_lookup, context_grep, or context_list_entries. Prefer context_lookup when search or interpretation is needed; same scope as context_lookup. Start with a small maxLines. Optional includeRelated=true includes matched tool call/result entries; use it only if the counterpart is needed. Returns up to 24000 payload characters and maxLines lines per page, plus attribution/cursor notes; a page may not contain the entire entry. Continue with the reported offset only if the requested detail is missing, incomplete, or needs more context to resolve ambiguity, keeping includeRelated unchanged. Stop once the question is answered; do not expand surrounding history by default.",
|
|
1701
|
-
promptSnippet: "Recover a specific detail hidden by compaction at a known ENTRY id in this conversation.",
|
|
1702
|
-
parameters: Type.Object(SHOW_FIELDS),
|
|
1703
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1704
|
-
return run(ctx, (t) => showEntry(t, params));
|
|
1705
|
-
},
|
|
1706
|
-
});
|
|
1707
|
-
}
|
|
1708
|
-
|
|
1709
1538
|
// ============================================================================
|
|
1710
1539
|
// Extension
|
|
1711
1540
|
// ============================================================================
|
|
@@ -1857,21 +1686,38 @@ export default function (pi: ExtensionAPI) {
|
|
|
1857
1686
|
|
|
1858
1687
|
const filterTurns = {
|
|
1859
1688
|
description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
|
|
1860
|
-
handler: async (args: string, ctx: ExtensionContext) => {
|
|
1861
|
-
|
|
1689
|
+
handler: async (args: string, ctx: ExtensionContext, reads = false) => {
|
|
1690
|
+
const command = reads ? "/retain-reads" : "/filter-turns";
|
|
1691
|
+
if (args.trim()) { ctx.ui.notify(`Usage: ${command}`, "error"); return; }
|
|
1862
1692
|
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1863
|
-
ctx.ui.notify(
|
|
1693
|
+
ctx.ui.notify(`${command} requires the interactive terminal UI.`, "error"); return;
|
|
1864
1694
|
}
|
|
1865
1695
|
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1866
1696
|
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
1867
1697
|
}
|
|
1868
1698
|
const entries = ctx.sessionManager.getBranch();
|
|
1869
1699
|
const compaction = latestVerbatimCompaction(entries);
|
|
1870
|
-
if (compactionMethod(entries) !== "verbatim"
|
|
1871
|
-
ctx.ui.notify(
|
|
1700
|
+
if (compactionMethod(entries) !== "verbatim") {
|
|
1701
|
+
ctx.ui.notify(`${command} requires verbatim compaction.`, "error"); return;
|
|
1872
1702
|
}
|
|
1873
|
-
const
|
|
1874
|
-
|
|
1703
|
+
const catalog = readCatalog(entries, ctx.cwd);
|
|
1704
|
+
let retention = readRetentionState(entries, ctx, catalog);
|
|
1705
|
+
if (!compaction) {
|
|
1706
|
+
if (!reads) { ctx.ui.notify("/filter-turns requires an existing verbatim checkpoint. Use /compact-filtered to create one.", "error"); return; }
|
|
1707
|
+
const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
|
|
1708
|
+
const result = await pickRetainedReads(ctx, catalog, retention, new Set(), new AbortController().signal);
|
|
1709
|
+
if (!result) return;
|
|
1710
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leafId || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1711
|
+
ctx.ui.notify("Session changed; retention update cancelled.", "warning"); return;
|
|
1712
|
+
}
|
|
1713
|
+
if (JSON.stringify(result) === JSON.stringify(retention)) {
|
|
1714
|
+
ctx.ui.notify("No read-retention changes.", "info"); return;
|
|
1715
|
+
}
|
|
1716
|
+
pi.appendEntry(READ_RETENTION_ENTRY, result);
|
|
1717
|
+
ctx.ui.notify("Read retention saved for future verbatim compactions.", "info"); return;
|
|
1718
|
+
}
|
|
1719
|
+
const canonical = compaction.details as { span: StoredSpan; readRetention: ReadRetention; readFiles: string[]; modifiedFiles: string[] };
|
|
1720
|
+
if (!canonical.span) {
|
|
1875
1721
|
ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
|
|
1876
1722
|
}
|
|
1877
1723
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
@@ -1882,9 +1728,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1882
1728
|
const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
|
|
1883
1729
|
const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
|
|
1884
1730
|
const preflags = preflaggedTurns(entries);
|
|
1731
|
+
const anchor = latestFilterRevision(entries) ?? compaction;
|
|
1732
|
+
const savedRetention = anchor.type === "custom" ? anchor.data.readRetention : canonical.readRetention;
|
|
1733
|
+
const savedEntries = entries.slice(0, entries.indexOf(anchor) + 1);
|
|
1734
|
+
const previousRetained = renderRetainedReads(readCatalog(savedEntries, ctx.cwd), savedRetention,
|
|
1735
|
+
savedEntries, compaction.firstKeptEntryId, excluded, fidelity);
|
|
1736
|
+
// LATEST can move (or an output can be context-edited) without a mode
|
|
1737
|
+
// toggle. Compare generated read copies against their original branch
|
|
1738
|
+
// inputs, never by parsing quoted text out of the saved checkpoint.
|
|
1739
|
+
const sameRetention = () => JSON.stringify(retention) === JSON.stringify(savedRetention) &&
|
|
1740
|
+
renderRetainedReads(catalog, retention, entries, compaction.firstKeptEntryId,
|
|
1741
|
+
new Set(previousExcluded), previousFidelity) === previousRetained;
|
|
1885
1742
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
1886
1743
|
const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
|
|
1887
|
-
compaction.firstKeptEntryId,
|
|
1744
|
+
compaction.firstKeptEntryId, selectedReads(catalog, retention), proposed);
|
|
1888
1745
|
const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
|
|
1889
1746
|
pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
|
|
1890
1747
|
kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
|
|
@@ -1895,7 +1752,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1895
1752
|
now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
|
|
1896
1753
|
firstKeptEntryId: compaction.firstKeptEntryId,
|
|
1897
1754
|
...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
|
|
1898
|
-
|
|
1755
|
+
retention, canonical.readFiles, canonical.modifiedFiles, pruned),
|
|
1899
1756
|
cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
|
|
1900
1757
|
chooseCap: preview ? async () => {
|
|
1901
1758
|
if (cap.mode === "off") return undefined;
|
|
@@ -1924,7 +1781,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1924
1781
|
const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
|
|
1925
1782
|
applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
|
|
1926
1783
|
const original = await baseline;
|
|
1927
|
-
if (unchanged(pruned, kept, modes)) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
|
|
1784
|
+
if (unchanged(pruned, kept, modes) && sameRetention()) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
|
|
1928
1785
|
const presentation = { shortened: false };
|
|
1929
1786
|
const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
|
|
1930
1787
|
if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
|
|
@@ -1937,26 +1794,32 @@ export default function (pi: ExtensionAPI) {
|
|
|
1937
1794
|
fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
|
|
1938
1795
|
} : undefined };
|
|
1939
1796
|
};
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1797
|
+
if (reads) {
|
|
1798
|
+
const result = await pickRetainedReads(ctx, catalog, retention, excluded, signal);
|
|
1799
|
+
if (!result) return;
|
|
1800
|
+
retention = result;
|
|
1801
|
+
} else {
|
|
1802
|
+
const result = await pickFilteredTurns(ctx, choices, signal, estimateSelection);
|
|
1803
|
+
if (result === undefined) return;
|
|
1804
|
+
applyTurnSelection(choices, result, preflags, excluded, keptAsides, fidelity);
|
|
1805
|
+
}
|
|
1806
|
+
if (unchanged(excluded, keptAsides, fidelity) && sameRetention()) {
|
|
1807
|
+
ctx.ui.notify("No checkpoint context changes.", "info"); return;
|
|
1945
1808
|
}
|
|
1946
1809
|
const summary = await renderCheckpoint(excluded, fidelity, slots, false);
|
|
1947
1810
|
if (summary === undefined) return;
|
|
1948
1811
|
checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
|
|
1949
1812
|
const current = ctx.sessionManager.getBranch();
|
|
1950
1813
|
if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
|
|
1951
|
-
latestFilterRevision(current)?.id !== revisionId) {
|
|
1814
|
+
latestFilterRevision(current)?.id !== revisionId || ctx.sessionManager.getLeafId() !== entries.at(-1)?.id || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1952
1815
|
ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
|
|
1953
1816
|
}
|
|
1954
|
-
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
|
|
1817
|
+
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary, readRetention: retention,
|
|
1955
1818
|
filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
|
|
1956
1819
|
...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
|
|
1957
|
-
ctx.ui.notify("Checkpoint
|
|
1820
|
+
ctx.ui.notify("Checkpoint context updated. No additional history compacted; recent messages and boundary unchanged.", "info");
|
|
1958
1821
|
} catch (error) {
|
|
1959
|
-
ctx.ui.notify(`Checkpoint
|
|
1822
|
+
ctx.ui.notify(`Checkpoint context update cancelled: ${errMsg(error)}`, "error");
|
|
1960
1823
|
}
|
|
1961
1824
|
},
|
|
1962
1825
|
};
|
|
@@ -2001,6 +1864,36 @@ export default function (pi: ExtensionAPI) {
|
|
|
2001
1864
|
},
|
|
2002
1865
|
});
|
|
2003
1866
|
pi.registerCommand("filter-turns", filterTurns);
|
|
1867
|
+
pi.registerCommand("retain-reads", {
|
|
1868
|
+
description: "Choose retained file reads: off, first or latest; preview full outputs",
|
|
1869
|
+
handler: (args, ctx) => filterTurns.handler(args, ctx, true),
|
|
1870
|
+
});
|
|
1871
|
+
pi.registerCommand("export-checkpoint", {
|
|
1872
|
+
description: "Export the saved checkpoint text, including manual revisions: [path]",
|
|
1873
|
+
handler: async (args, ctx) => {
|
|
1874
|
+
const argument = args.trim();
|
|
1875
|
+
const match = argument.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))$/);
|
|
1876
|
+
if (argument && !match) {
|
|
1877
|
+
ctx.ui.notify("Usage: /export-checkpoint [path] (quote paths containing spaces)", "error"); return;
|
|
1878
|
+
}
|
|
1879
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1880
|
+
const compaction = entries.findLast((entry) => entry.type === "compaction");
|
|
1881
|
+
if (!compaction) {
|
|
1882
|
+
ctx.ui.notify("No checkpoint in this branch. Use /compact first.", "info"); return;
|
|
1883
|
+
}
|
|
1884
|
+
const filename = match?.[1] ?? match?.[2] ?? match?.[3] ?? `pi-checkpoint-${ctx.sessionManager.getSessionId()}.txt`;
|
|
1885
|
+
const outputPath = path.resolve(ctx.cwd, filename.replace(/^~(?=$|[/\\])/, () => homedir()));
|
|
1886
|
+
// Export the frozen text, not a reconstruction from newer reads or spans.
|
|
1887
|
+
// Native turn expansions are separate context messages, not summary text.
|
|
1888
|
+
const summary = latestFilterRevision(entries)?.data.summary ?? compaction.summary;
|
|
1889
|
+
try {
|
|
1890
|
+
fs.writeFileSync(outputPath, summary, { encoding: "utf8", mode: 0o600 });
|
|
1891
|
+
ctx.ui.notify(`Checkpoint exported to: ${outputPath}`, "info");
|
|
1892
|
+
} catch (error) {
|
|
1893
|
+
ctx.ui.notify(`Failed to export checkpoint: ${errMsg(error)}`, "error");
|
|
1894
|
+
}
|
|
1895
|
+
},
|
|
1896
|
+
});
|
|
2004
1897
|
|
|
2005
1898
|
pi.on("session_start", (_event, ctx) => {
|
|
2006
1899
|
clearAsideSubmission();
|
|
@@ -2051,10 +1944,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2051
1944
|
preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
|
|
2052
1945
|
.map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
|
|
2053
1946
|
const canonical = latestVerbatimCompaction(branchEntries)!.details as {
|
|
2054
|
-
|
|
1947
|
+
readRetention: ReadRetention; readFiles: string[]; modifiedFiles: string[];
|
|
2055
1948
|
};
|
|
2056
1949
|
const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2057
|
-
|
|
1950
|
+
readRetentionState(branchEntries, ctx), canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
|
|
2058
1951
|
const ops = preparation.fileOps;
|
|
2059
1952
|
ops.read = new Set(visible.readFiles);
|
|
2060
1953
|
ops.edited = new Set(visible.modifiedFiles);
|
|
@@ -2078,6 +1971,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2078
1971
|
|
|
2079
1972
|
// 1) Cumulative file lists: pi only carries lists from pi-generated
|
|
2080
1973
|
// compactions (fromHook=false), so we carry our own forward.
|
|
1974
|
+
let retainingReads = false;
|
|
2081
1975
|
try {
|
|
2082
1976
|
const fileOps = preparation.fileOps as { read: Set<string>; written: Set<string>; edited: Set<string> } | undefined;
|
|
2083
1977
|
if (fileOps) {
|
|
@@ -2117,12 +2011,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2117
2011
|
const spanFrom = toIso(msgTs(allMessages[0]));
|
|
2118
2012
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
2119
2013
|
const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
|
|
2120
|
-
const span = await summarizeMessages(allMessages, renderer,
|
|
2014
|
+
const span = await summarizeMessages(allMessages, renderer, preparedMessageSources(branchEntries, allMessages));
|
|
2121
2015
|
const spanLines = span.lines;
|
|
2122
2016
|
|
|
2123
|
-
// 3)
|
|
2124
|
-
|
|
2125
|
-
const canonicalRetained =
|
|
2017
|
+
// 3) Explicit read choices apply independently after whole-turn filtering.
|
|
2018
|
+
const catalog = readCatalog(branchEntries, ctx.cwd);
|
|
2019
|
+
const canonicalRetained = readRetentionState(branchEntries, ctx, catalog);
|
|
2020
|
+
retainingReads = selectedReads(catalog, canonicalRetained).length > 0;
|
|
2126
2021
|
const excluded = new Set(filteredTurns(branchEntries));
|
|
2127
2022
|
const keptAsides = new Set(keptAsideTurns(branchEntries));
|
|
2128
2023
|
const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
|
|
@@ -2130,13 +2025,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2130
2025
|
const preflags = preflaggedTurns(branchEntries);
|
|
2131
2026
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2132
2027
|
const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
|
|
2133
|
-
excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
|
|
2028
|
+
excluded, preparation.firstKeptEntryId, selectedReads(catalog, canonicalRetained), proposed);
|
|
2134
2029
|
for (const turn of choices)
|
|
2135
2030
|
if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
|
|
2136
2031
|
}
|
|
2137
2032
|
const filteredTurnIds = [...excluded];
|
|
2138
2033
|
const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2139
|
-
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded
|
|
2034
|
+
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded);
|
|
2140
2035
|
const summary = await buildMechanicalSummary({
|
|
2141
2036
|
reason, // pi's raw reason, passed through unchanged
|
|
2142
2037
|
tokensBefore: preparation.tokensBefore,
|
|
@@ -2146,6 +2041,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2146
2041
|
spanTools: span.tools,
|
|
2147
2042
|
locations: renderer.locations.entries,
|
|
2148
2043
|
spanTurnIds: span.turnIds,
|
|
2044
|
+
spanReadPositions: span.readPositions,
|
|
2149
2045
|
filteredTurnIds, fidelity, slots,
|
|
2150
2046
|
spanFrom,
|
|
2151
2047
|
spanTo,
|
|
@@ -2171,10 +2067,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2171
2067
|
details: {
|
|
2172
2068
|
kind: MECH_KIND,
|
|
2173
2069
|
// Canonical metadata stays reversible; only the rendered checkpoint
|
|
2174
|
-
// masks file paths
|
|
2070
|
+
// masks file paths owned by excluded turns. Retained reads are independent.
|
|
2175
2071
|
readFiles: canonicalReadFiles,
|
|
2176
2072
|
modifiedFiles: canonicalModifiedFiles,
|
|
2177
|
-
|
|
2073
|
+
readRetention: canonicalRetained,
|
|
2178
2074
|
locations: renderer.locations.entries,
|
|
2179
2075
|
...(filteredTurnIds.length ? { filteredTurnIds } : {}),
|
|
2180
2076
|
...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
|
|
@@ -2182,13 +2078,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
2182
2078
|
// Only this compaction's own span (un-capped lines). Earlier spans
|
|
2183
2079
|
// are re-rendered from the earlier entries' details — no nesting.
|
|
2184
2080
|
span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
|
|
2185
|
-
lines: spanLines, turnIds: span.turnIds, ...(span.
|
|
2081
|
+
lines: spanLines, turnIds: span.turnIds, ...(span.readPositions ? { readPositions: span.readPositions } : {}),
|
|
2082
|
+
...(span.tools ? { tools: span.tools } : {}) },
|
|
2186
2083
|
},
|
|
2187
2084
|
},
|
|
2188
2085
|
};
|
|
2189
2086
|
} catch (err) {
|
|
2190
|
-
//
|
|
2191
|
-
const preserveFiltering = automaticFiltering || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2087
|
+
// Fail closed rather than discard explicit filtering/fidelity/retention.
|
|
2088
|
+
const preserveFiltering = automaticFiltering || retainingReads || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2192
2089
|
ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
|
|
2193
2090
|
return preserveFiltering ? { cancel: true } : undefined;
|
|
2194
2091
|
}
|
|
@@ -2197,13 +2094,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
2197
2094
|
// --------------------------------------------------------------------------
|
|
2198
2095
|
// context_lookup tool: subagent research over the raw session branch
|
|
2199
2096
|
// --------------------------------------------------------------------------
|
|
2200
|
-
registerDirectTools(pi);
|
|
2201
2097
|
pi.registerTool({
|
|
2202
2098
|
name: "context_lookup",
|
|
2203
2099
|
label: "Context lookup",
|
|
2204
2100
|
executionMode: "sequential",
|
|
2205
2101
|
description:
|
|
2206
|
-
`Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. Ask \`context_lookup\` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence. A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE}
|
|
2102
|
+
`Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. Ask \`context_lookup\` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence. A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} ${RECOVERY_FILESYSTEM_RULE}`,
|
|
2207
2103
|
promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
|
|
2208
2104
|
parameters: Type.Object({
|
|
2209
2105
|
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." }),
|
|
@@ -2211,7 +2107,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2211
2107
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
2212
2108
|
if (cfg.lookupMaxCalls > 0 && consecutiveLookups(ctx, toolCallId) >= cfg.lookupMaxCalls) {
|
|
2213
2109
|
return {
|
|
2214
|
-
content: [{ type: "text", text: `context_lookup consecutive-call limit reached (${cfg.lookupMaxCalls})
|
|
2110
|
+
content: [{ type: "text", text: `context_lookup consecutive-call limit reached (${cfg.lookupMaxCalls}).` }],
|
|
2215
2111
|
details: undefined,
|
|
2216
2112
|
};
|
|
2217
2113
|
}
|