@foliox/transparent-compact-pi 0.11.2 → 0.11.3
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 +72 -49
- package/extensions/index.ts +150 -203
- 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 +2 -2
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,12 +847,12 @@ 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
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. If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`.`;
|
|
@@ -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("");
|
|
@@ -1857,21 +1736,38 @@ export default function (pi: ExtensionAPI) {
|
|
|
1857
1736
|
|
|
1858
1737
|
const filterTurns = {
|
|
1859
1738
|
description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
|
|
1860
|
-
handler: async (args: string, ctx: ExtensionContext) => {
|
|
1861
|
-
|
|
1739
|
+
handler: async (args: string, ctx: ExtensionContext, reads = false) => {
|
|
1740
|
+
const command = reads ? "/retain-reads" : "/filter-turns";
|
|
1741
|
+
if (args.trim()) { ctx.ui.notify(`Usage: ${command}`, "error"); return; }
|
|
1862
1742
|
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1863
|
-
ctx.ui.notify(
|
|
1743
|
+
ctx.ui.notify(`${command} requires the interactive terminal UI.`, "error"); return;
|
|
1864
1744
|
}
|
|
1865
1745
|
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1866
1746
|
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
1867
1747
|
}
|
|
1868
1748
|
const entries = ctx.sessionManager.getBranch();
|
|
1869
1749
|
const compaction = latestVerbatimCompaction(entries);
|
|
1870
|
-
if (compactionMethod(entries) !== "verbatim"
|
|
1871
|
-
ctx.ui.notify(
|
|
1750
|
+
if (compactionMethod(entries) !== "verbatim") {
|
|
1751
|
+
ctx.ui.notify(`${command} requires verbatim compaction.`, "error"); return;
|
|
1872
1752
|
}
|
|
1873
|
-
const
|
|
1874
|
-
|
|
1753
|
+
const catalog = readCatalog(entries, ctx.cwd);
|
|
1754
|
+
let retention = readRetentionState(entries, ctx, catalog);
|
|
1755
|
+
if (!compaction) {
|
|
1756
|
+
if (!reads) { ctx.ui.notify("/filter-turns requires an existing verbatim checkpoint. Use /compact-filtered to create one.", "error"); return; }
|
|
1757
|
+
const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
|
|
1758
|
+
const result = await pickRetainedReads(ctx, catalog, retention, new Set(), new AbortController().signal);
|
|
1759
|
+
if (!result) return;
|
|
1760
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leafId || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1761
|
+
ctx.ui.notify("Session changed; retention update cancelled.", "warning"); return;
|
|
1762
|
+
}
|
|
1763
|
+
if (JSON.stringify(result) === JSON.stringify(retention)) {
|
|
1764
|
+
ctx.ui.notify("No read-retention changes.", "info"); return;
|
|
1765
|
+
}
|
|
1766
|
+
pi.appendEntry(READ_RETENTION_ENTRY, result);
|
|
1767
|
+
ctx.ui.notify("Read retention saved for future verbatim compactions.", "info"); return;
|
|
1768
|
+
}
|
|
1769
|
+
const canonical = compaction.details as { span: StoredSpan; readRetention: ReadRetention; readFiles: string[]; modifiedFiles: string[] };
|
|
1770
|
+
if (!canonical.span) {
|
|
1875
1771
|
ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
|
|
1876
1772
|
}
|
|
1877
1773
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
@@ -1882,9 +1778,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1882
1778
|
const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
|
|
1883
1779
|
const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
|
|
1884
1780
|
const preflags = preflaggedTurns(entries);
|
|
1781
|
+
const anchor = latestFilterRevision(entries) ?? compaction;
|
|
1782
|
+
const savedRetention = anchor.type === "custom" ? anchor.data.readRetention : canonical.readRetention;
|
|
1783
|
+
const savedEntries = entries.slice(0, entries.indexOf(anchor) + 1);
|
|
1784
|
+
const previousRetained = renderRetainedReads(readCatalog(savedEntries, ctx.cwd), savedRetention,
|
|
1785
|
+
savedEntries, compaction.firstKeptEntryId, excluded, fidelity);
|
|
1786
|
+
// LATEST can move (or an output can be context-edited) without a mode
|
|
1787
|
+
// toggle. Compare generated read copies against their original branch
|
|
1788
|
+
// inputs, never by parsing quoted text out of the saved checkpoint.
|
|
1789
|
+
const sameRetention = () => JSON.stringify(retention) === JSON.stringify(savedRetention) &&
|
|
1790
|
+
renderRetainedReads(catalog, retention, entries, compaction.firstKeptEntryId,
|
|
1791
|
+
new Set(previousExcluded), previousFidelity) === previousRetained;
|
|
1885
1792
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
1886
1793
|
const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
|
|
1887
|
-
compaction.firstKeptEntryId,
|
|
1794
|
+
compaction.firstKeptEntryId, selectedReads(catalog, retention), proposed);
|
|
1888
1795
|
const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
|
|
1889
1796
|
pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
|
|
1890
1797
|
kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
|
|
@@ -1895,7 +1802,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1895
1802
|
now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
|
|
1896
1803
|
firstKeptEntryId: compaction.firstKeptEntryId,
|
|
1897
1804
|
...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
|
|
1898
|
-
|
|
1805
|
+
retention, canonical.readFiles, canonical.modifiedFiles, pruned),
|
|
1899
1806
|
cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
|
|
1900
1807
|
chooseCap: preview ? async () => {
|
|
1901
1808
|
if (cap.mode === "off") return undefined;
|
|
@@ -1924,7 +1831,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1924
1831
|
const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
|
|
1925
1832
|
applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
|
|
1926
1833
|
const original = await baseline;
|
|
1927
|
-
if (unchanged(pruned, kept, modes)) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
|
|
1834
|
+
if (unchanged(pruned, kept, modes) && sameRetention()) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
|
|
1928
1835
|
const presentation = { shortened: false };
|
|
1929
1836
|
const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
|
|
1930
1837
|
if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
|
|
@@ -1937,26 +1844,32 @@ export default function (pi: ExtensionAPI) {
|
|
|
1937
1844
|
fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
|
|
1938
1845
|
} : undefined };
|
|
1939
1846
|
};
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1847
|
+
if (reads) {
|
|
1848
|
+
const result = await pickRetainedReads(ctx, catalog, retention, excluded, signal);
|
|
1849
|
+
if (!result) return;
|
|
1850
|
+
retention = result;
|
|
1851
|
+
} else {
|
|
1852
|
+
const result = await pickFilteredTurns(ctx, choices, signal, estimateSelection);
|
|
1853
|
+
if (result === undefined) return;
|
|
1854
|
+
applyTurnSelection(choices, result, preflags, excluded, keptAsides, fidelity);
|
|
1855
|
+
}
|
|
1856
|
+
if (unchanged(excluded, keptAsides, fidelity) && sameRetention()) {
|
|
1857
|
+
ctx.ui.notify("No checkpoint context changes.", "info"); return;
|
|
1945
1858
|
}
|
|
1946
1859
|
const summary = await renderCheckpoint(excluded, fidelity, slots, false);
|
|
1947
1860
|
if (summary === undefined) return;
|
|
1948
1861
|
checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
|
|
1949
1862
|
const current = ctx.sessionManager.getBranch();
|
|
1950
1863
|
if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
|
|
1951
|
-
latestFilterRevision(current)?.id !== revisionId) {
|
|
1864
|
+
latestFilterRevision(current)?.id !== revisionId || ctx.sessionManager.getLeafId() !== entries.at(-1)?.id || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1952
1865
|
ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
|
|
1953
1866
|
}
|
|
1954
|
-
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
|
|
1867
|
+
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary, readRetention: retention,
|
|
1955
1868
|
filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
|
|
1956
1869
|
...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
|
|
1957
|
-
ctx.ui.notify("Checkpoint
|
|
1870
|
+
ctx.ui.notify("Checkpoint context updated. No additional history compacted; recent messages and boundary unchanged.", "info");
|
|
1958
1871
|
} catch (error) {
|
|
1959
|
-
ctx.ui.notify(`Checkpoint
|
|
1872
|
+
ctx.ui.notify(`Checkpoint context update cancelled: ${errMsg(error)}`, "error");
|
|
1960
1873
|
}
|
|
1961
1874
|
},
|
|
1962
1875
|
};
|
|
@@ -2001,6 +1914,36 @@ export default function (pi: ExtensionAPI) {
|
|
|
2001
1914
|
},
|
|
2002
1915
|
});
|
|
2003
1916
|
pi.registerCommand("filter-turns", filterTurns);
|
|
1917
|
+
pi.registerCommand("retain-reads", {
|
|
1918
|
+
description: "Choose retained file reads: off, first or latest; preview full outputs",
|
|
1919
|
+
handler: (args, ctx) => filterTurns.handler(args, ctx, true),
|
|
1920
|
+
});
|
|
1921
|
+
pi.registerCommand("export-checkpoint", {
|
|
1922
|
+
description: "Export the saved checkpoint text, including manual revisions: [path]",
|
|
1923
|
+
handler: async (args, ctx) => {
|
|
1924
|
+
const argument = args.trim();
|
|
1925
|
+
const match = argument.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))$/);
|
|
1926
|
+
if (argument && !match) {
|
|
1927
|
+
ctx.ui.notify("Usage: /export-checkpoint [path] (quote paths containing spaces)", "error"); return;
|
|
1928
|
+
}
|
|
1929
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1930
|
+
const compaction = entries.findLast((entry) => entry.type === "compaction");
|
|
1931
|
+
if (!compaction) {
|
|
1932
|
+
ctx.ui.notify("No checkpoint in this branch. Use /compact first.", "info"); return;
|
|
1933
|
+
}
|
|
1934
|
+
const filename = match?.[1] ?? match?.[2] ?? match?.[3] ?? `pi-checkpoint-${ctx.sessionManager.getSessionId()}.txt`;
|
|
1935
|
+
const outputPath = path.resolve(ctx.cwd, filename.replace(/^~(?=$|[/\\])/, () => homedir()));
|
|
1936
|
+
// Export the frozen text, not a reconstruction from newer reads or spans.
|
|
1937
|
+
// Native turn expansions are separate context messages, not summary text.
|
|
1938
|
+
const summary = latestFilterRevision(entries)?.data.summary ?? compaction.summary;
|
|
1939
|
+
try {
|
|
1940
|
+
fs.writeFileSync(outputPath, summary, { encoding: "utf8", mode: 0o600 });
|
|
1941
|
+
ctx.ui.notify(`Checkpoint exported to: ${outputPath}`, "info");
|
|
1942
|
+
} catch (error) {
|
|
1943
|
+
ctx.ui.notify(`Failed to export checkpoint: ${errMsg(error)}`, "error");
|
|
1944
|
+
}
|
|
1945
|
+
},
|
|
1946
|
+
});
|
|
2004
1947
|
|
|
2005
1948
|
pi.on("session_start", (_event, ctx) => {
|
|
2006
1949
|
clearAsideSubmission();
|
|
@@ -2051,10 +1994,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2051
1994
|
preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
|
|
2052
1995
|
.map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
|
|
2053
1996
|
const canonical = latestVerbatimCompaction(branchEntries)!.details as {
|
|
2054
|
-
|
|
1997
|
+
readRetention: ReadRetention; readFiles: string[]; modifiedFiles: string[];
|
|
2055
1998
|
};
|
|
2056
1999
|
const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2057
|
-
|
|
2000
|
+
readRetentionState(branchEntries, ctx), canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
|
|
2058
2001
|
const ops = preparation.fileOps;
|
|
2059
2002
|
ops.read = new Set(visible.readFiles);
|
|
2060
2003
|
ops.edited = new Set(visible.modifiedFiles);
|
|
@@ -2078,6 +2021,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2078
2021
|
|
|
2079
2022
|
// 1) Cumulative file lists: pi only carries lists from pi-generated
|
|
2080
2023
|
// compactions (fromHook=false), so we carry our own forward.
|
|
2024
|
+
let retainingReads = false;
|
|
2081
2025
|
try {
|
|
2082
2026
|
const fileOps = preparation.fileOps as { read: Set<string>; written: Set<string>; edited: Set<string> } | undefined;
|
|
2083
2027
|
if (fileOps) {
|
|
@@ -2117,12 +2061,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2117
2061
|
const spanFrom = toIso(msgTs(allMessages[0]));
|
|
2118
2062
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
2119
2063
|
const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
|
|
2120
|
-
const span = await summarizeMessages(allMessages, renderer,
|
|
2064
|
+
const span = await summarizeMessages(allMessages, renderer, preparedMessageSources(branchEntries, allMessages));
|
|
2121
2065
|
const spanLines = span.lines;
|
|
2122
2066
|
|
|
2123
|
-
// 3)
|
|
2124
|
-
|
|
2125
|
-
const canonicalRetained =
|
|
2067
|
+
// 3) Explicit read choices apply independently after whole-turn filtering.
|
|
2068
|
+
const catalog = readCatalog(branchEntries, ctx.cwd);
|
|
2069
|
+
const canonicalRetained = readRetentionState(branchEntries, ctx, catalog);
|
|
2070
|
+
retainingReads = selectedReads(catalog, canonicalRetained).length > 0;
|
|
2126
2071
|
const excluded = new Set(filteredTurns(branchEntries));
|
|
2127
2072
|
const keptAsides = new Set(keptAsideTurns(branchEntries));
|
|
2128
2073
|
const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
|
|
@@ -2130,13 +2075,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2130
2075
|
const preflags = preflaggedTurns(branchEntries);
|
|
2131
2076
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2132
2077
|
const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
|
|
2133
|
-
excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
|
|
2078
|
+
excluded, preparation.firstKeptEntryId, selectedReads(catalog, canonicalRetained), proposed);
|
|
2134
2079
|
for (const turn of choices)
|
|
2135
2080
|
if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
|
|
2136
2081
|
}
|
|
2137
2082
|
const filteredTurnIds = [...excluded];
|
|
2138
2083
|
const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2139
|
-
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded
|
|
2084
|
+
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded);
|
|
2140
2085
|
const summary = await buildMechanicalSummary({
|
|
2141
2086
|
reason, // pi's raw reason, passed through unchanged
|
|
2142
2087
|
tokensBefore: preparation.tokensBefore,
|
|
@@ -2146,6 +2091,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2146
2091
|
spanTools: span.tools,
|
|
2147
2092
|
locations: renderer.locations.entries,
|
|
2148
2093
|
spanTurnIds: span.turnIds,
|
|
2094
|
+
spanReadPositions: span.readPositions,
|
|
2149
2095
|
filteredTurnIds, fidelity, slots,
|
|
2150
2096
|
spanFrom,
|
|
2151
2097
|
spanTo,
|
|
@@ -2171,10 +2117,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2171
2117
|
details: {
|
|
2172
2118
|
kind: MECH_KIND,
|
|
2173
2119
|
// Canonical metadata stays reversible; only the rendered checkpoint
|
|
2174
|
-
// masks file paths
|
|
2120
|
+
// masks file paths owned by excluded turns. Retained reads are independent.
|
|
2175
2121
|
readFiles: canonicalReadFiles,
|
|
2176
2122
|
modifiedFiles: canonicalModifiedFiles,
|
|
2177
|
-
|
|
2123
|
+
readRetention: canonicalRetained,
|
|
2178
2124
|
locations: renderer.locations.entries,
|
|
2179
2125
|
...(filteredTurnIds.length ? { filteredTurnIds } : {}),
|
|
2180
2126
|
...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
|
|
@@ -2182,13 +2128,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
2182
2128
|
// Only this compaction's own span (un-capped lines). Earlier spans
|
|
2183
2129
|
// are re-rendered from the earlier entries' details — no nesting.
|
|
2184
2130
|
span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
|
|
2185
|
-
lines: spanLines, turnIds: span.turnIds, ...(span.
|
|
2131
|
+
lines: spanLines, turnIds: span.turnIds, ...(span.readPositions ? { readPositions: span.readPositions } : {}),
|
|
2132
|
+
...(span.tools ? { tools: span.tools } : {}) },
|
|
2186
2133
|
},
|
|
2187
2134
|
},
|
|
2188
2135
|
};
|
|
2189
2136
|
} catch (err) {
|
|
2190
|
-
//
|
|
2191
|
-
const preserveFiltering = automaticFiltering || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2137
|
+
// Fail closed rather than discard explicit filtering/fidelity/retention.
|
|
2138
|
+
const preserveFiltering = automaticFiltering || retainingReads || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2192
2139
|
ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
|
|
2193
2140
|
return preserveFiltering ? { cancel: true } : undefined;
|
|
2194
2141
|
}
|