@foliox/transparent-compact-pi 0.11.1 → 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 +78 -93
- package/extensions/index.ts +152 -327
- 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 +4 -4
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,231 +620,11 @@ 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(
|
|
617
|
-
}
|
|
618
|
-
return { lines, ...(owners ? { turnIds } : {}), ...(tools.lines.length ? { tools } : {}) };
|
|
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
|
-
// File annotations describe evidence, not a guarantee of filesystem freshness.
|
|
740
|
-
// Use Pi's projection for visibility, but recorded mutations can invalidate a
|
|
741
|
-
// snapshot even when the mutation's message was subsequently omitted.
|
|
742
|
-
interface FileEvidence {
|
|
743
|
-
kind: "read" | "write";
|
|
744
|
-
completeness?: "full" | "partial" | "unknown";
|
|
745
|
-
changed?: "edit" | "write";
|
|
746
|
-
orderUncertain?: boolean;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
function fileEvidenceKey(file: string, cwd: string): string {
|
|
750
|
-
// Lexical normalization only: no stat/realpath, and no symlink-equivalence claim.
|
|
751
|
-
let normalized = file.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
|
|
752
|
-
if (normalized === "~") normalized = homedir();
|
|
753
|
-
else if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) normalized = path.join(homedir(), normalized.slice(2));
|
|
754
|
-
if (normalized.startsWith("file://")) {
|
|
755
|
-
try { normalized = fileURLToPath(normalized); } catch { /* Unknown path syntax: keep it literal. */ }
|
|
756
|
-
}
|
|
757
|
-
return path.resolve(cwd, normalized);
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
function readCompleteness(args: Record<string, any>, message: Record<string, any>, replaced: boolean): "full" | "partial" | "unknown" {
|
|
761
|
-
const blocks = message.content;
|
|
762
|
-
if (replaced || !Array.isArray(blocks) || blocks.length !== 1 || blocks[0].type !== "text" || typeof blocks[0].text !== "string") return "unknown";
|
|
763
|
-
const text = blocks[0].text;
|
|
764
|
-
if (/^Read image file \[/.test(text)) return "unknown";
|
|
765
|
-
const truncation = message.details?.truncation;
|
|
766
|
-
if (truncation?.firstLineExceedsLimit) return "unknown"; // Only a warning, not file contents.
|
|
767
|
-
// Pi's read tool supplies these notices for both default and explicit limits.
|
|
768
|
-
if (truncation?.truncated === true || /\[(?:Showing lines [^\n]*Use offset=\d+ to continue\.|\d+ more lines in file\. Use offset=\d+ to continue\.)\]\s*$/.test(text)) return "partial";
|
|
769
|
-
const offset = args.offset ?? 1;
|
|
770
|
-
if (!Number.isInteger(offset) || offset < 1 || (args.limit != null && (!Number.isInteger(args.limit) || args.limit < 1))) return "unknown";
|
|
771
|
-
if (offset > 1) return "partial";
|
|
772
|
-
// A limit is not proof of partialness: without a continuation notice Pi reached EOF.
|
|
773
|
-
// Unknown argument schemas are not assumed to have Pi's read semantics.
|
|
774
|
-
return Object.keys(args).every((key) => ["path", "offset", "limit"].includes(key)) ? "full" : "unknown";
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
function retainedFileEvidence(entries: SessionEntry[], firstKeptEntryId: string | undefined, cwd: string): Map<string, FileEvidence> {
|
|
778
|
-
const evidence = new Map<string, FileEvidence>();
|
|
779
|
-
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
780
|
-
if (cut < 0) return evidence;
|
|
781
|
-
const visible = new Map(buildSessionProjection(entries).entries.map((entry) => [entry.sourceEntry.id, entry.messages]));
|
|
782
|
-
const pending = new Map<string, { name: string; args: Record<string, any>; visible: boolean; orderUncertain: boolean } | null>();
|
|
783
|
-
const changed = (name: "edit" | "write", args: Record<string, any>) => {
|
|
784
|
-
if (typeof args.path !== "string") return;
|
|
785
|
-
const previous = evidence.get(fileEvidenceKey(args.path, cwd));
|
|
786
|
-
if (previous) previous.changed = name;
|
|
787
|
-
};
|
|
788
|
-
for (const entry of entries.slice(cut)) {
|
|
789
|
-
if (entry.type !== "message") continue;
|
|
790
|
-
const raw = entry.message as unknown as Record<string, any>;
|
|
791
|
-
const projected = visible.get(entry.id)?.find((message) => message.role === raw.role) as Record<string, any> | undefined;
|
|
792
|
-
if (raw.role === "assistant") {
|
|
793
|
-
const blocks = Array.isArray(raw.content) ? raw.content : [];
|
|
794
|
-
for (const block of blocks) {
|
|
795
|
-
if (block.type !== "toolCall" || typeof block.id !== "string") continue;
|
|
796
|
-
// Sibling calls may execute concurrently; result order is not read/write order.
|
|
797
|
-
const orderUncertain = typeof block.arguments?.path === "string" && blocks.some((other: any) =>
|
|
798
|
-
other !== block && other.type === "toolCall" && ["write", "edit"].includes(other.name) &&
|
|
799
|
-
typeof other.arguments?.path === "string" &&
|
|
800
|
-
fileEvidenceKey(other.arguments.path, cwd) === fileEvidenceKey(block.arguments.path, cwd));
|
|
801
|
-
const shown = projected?.content?.filter?.((b: any) => b.type === "toolCall" && b.id === block.id);
|
|
802
|
-
const sameCall = shown?.length === 1 && shown[0].name === block.name &&
|
|
803
|
-
JSON.stringify(shown[0].arguments) === JSON.stringify(block.arguments);
|
|
804
|
-
pending.set(block.id, pending.has(block.id) ? null : { name: block.name, args: block.arguments ?? {}, visible: sameCall, orderUncertain });
|
|
805
|
-
}
|
|
806
|
-
} else if (raw.role === "toolResult") {
|
|
807
|
-
const call = pending.get(raw.toolCallId);
|
|
808
|
-
pending.delete(raw.toolCallId);
|
|
809
|
-
if (call && call.name === raw.toolName && typeof call.args.path === "string" && raw.isError === false) {
|
|
810
|
-
const key = fileEvidenceKey(call.args.path, cwd);
|
|
811
|
-
if (call.name === "write" || call.name === "edit") changed(call.name, call.args);
|
|
812
|
-
if (call.visible && projected && call.name === "read") {
|
|
813
|
-
const completeness = readCompleteness(call.args, projected, projected.content !== raw.content);
|
|
814
|
-
const previous = evidence.get(key);
|
|
815
|
-
// A later partial read does not hide an earlier complete snapshot.
|
|
816
|
-
if (!previous || previous.changed || previous.orderUncertain || (previous.kind === "read" && previous.completeness !== "full"))
|
|
817
|
-
evidence.set(key, { kind: "read", completeness, orderUncertain: call.orderUncertain });
|
|
818
|
-
} else if (call.visible && call.name === "write" && typeof call.args.content === "string") {
|
|
819
|
-
evidence.set(key, { kind: "write", orderUncertain: call.orderUncertain });
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
// Nested calls have metadata but no model-visible read outputs or write payloads.
|
|
823
|
-
for (const nested of raw.nestedCalls?.calls ?? []) {
|
|
824
|
-
if (nested.status === "ok" && (nested.name === "edit" || nested.name === "write")) changed(nested.name, nested.arguments ?? {});
|
|
825
|
-
}
|
|
826
|
-
}
|
|
623
|
+
for (let i = start; i < lines.length; i++) turnIds.push(sources?.[messageIndex]?.owner ?? null);
|
|
827
624
|
}
|
|
828
|
-
return
|
|
625
|
+
return { lines, ...(sources ? { turnIds } : {}), ...(readPositions.length ? { readPositions } : {}), ...(tools.lines.length ? { tools } : {}) };
|
|
829
626
|
}
|
|
830
627
|
|
|
831
|
-
function fileEvidenceLabel(evidence: FileEvidence | undefined): string | undefined {
|
|
832
|
-
if (!evidence) return;
|
|
833
|
-
if (evidence.orderUncertain) return `${evidence.kind} in tail; order uncertain`;
|
|
834
|
-
if (evidence.changed) return `${evidence.kind} in tail, then ${evidence.changed === "edit" ? "edited" : "written"}`;
|
|
835
|
-
if (evidence.kind === "write") return "write content in tail";
|
|
836
|
-
return evidence.completeness === "unknown" ? "read output in tail" : `${evidence.completeness} read in tail`;
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
const FILE_LIST_EXPLANATION = "File lists record earlier operations. Read/write annotations describe retained evidence as of this checkpoint, not live filesystem state; unannotated paths do not establish content visibility.";
|
|
840
|
-
|
|
841
628
|
const SECTION_HEADER = "### Compacted conversation (oldest first)";
|
|
842
629
|
const SPAN_CLOSE = "</compacted-span>";
|
|
843
630
|
const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
|
|
@@ -904,6 +691,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
|
|
|
904
691
|
lines: sd.lines,
|
|
905
692
|
tools: sd.tools,
|
|
906
693
|
turnIds: sd.turnIds,
|
|
694
|
+
readPositions: sd.readPositions,
|
|
907
695
|
});
|
|
908
696
|
}
|
|
909
697
|
return { base, spans };
|
|
@@ -916,6 +704,7 @@ interface FilterRevision {
|
|
|
916
704
|
keptAsideTurnIds: string[];
|
|
917
705
|
fidelity?: TurnFidelities;
|
|
918
706
|
slots?: TurnSlot[];
|
|
707
|
+
readRetention: ReadRetention;
|
|
919
708
|
}
|
|
920
709
|
|
|
921
710
|
function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
|
|
@@ -962,15 +751,15 @@ function projectCheckpoint(messages: AgentMessage[], entries: SessionEntry[]): A
|
|
|
962
751
|
|
|
963
752
|
// Match Pi's prepared messages to their source entries, including explicit
|
|
964
753
|
// context replacements and generated custom messages. No raw bodies are stored.
|
|
965
|
-
function
|
|
754
|
+
function preparedMessageSources(entries: SessionEntry[], messages: AgentMessage[]): (MessageSource | null)[] {
|
|
966
755
|
const owners = turnOwners(entries);
|
|
967
|
-
const queues = new Map<string,
|
|
756
|
+
const queues = new Map<string, MessageSource[]>();
|
|
968
757
|
for (const projected of buildSessionProjection(entries).entries) {
|
|
969
758
|
if (projected.sourceEntry.type === "compaction") continue;
|
|
970
759
|
for (const message of projected.messages) {
|
|
971
760
|
const key = JSON.stringify(message);
|
|
972
761
|
const queue = queues.get(key) ?? [];
|
|
973
|
-
queue.push(owners.get(projected.sourceEntry.id) ?? null);
|
|
762
|
+
queue.push({ entryId: projected.sourceEntry.id, owner: owners.get(projected.sourceEntry.id) ?? null });
|
|
974
763
|
queues.set(key, queue);
|
|
975
764
|
}
|
|
976
765
|
}
|
|
@@ -978,21 +767,18 @@ function preparedTurnOwners(entries: SessionEntry[], messages: AgentMessage[]):
|
|
|
978
767
|
}
|
|
979
768
|
|
|
980
769
|
function filterChoices(entries: SessionEntry[], spans: TurnSpan[], excluded: Set<string>, firstKeptEntryId: string,
|
|
981
|
-
retained:
|
|
770
|
+
retained: ReadOutput[], selected = excluded, fidelity: TurnFidelities = turnFidelities(entries)): FilterTurn[] {
|
|
982
771
|
const owners = turnOwners(entries), flagged = preflaggedTurns(entries);
|
|
983
772
|
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
984
773
|
const tailOwners = new Set(entries.slice(cut).filter((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary")
|
|
985
774
|
.map((entry) => owners.get(entry.id)));
|
|
986
775
|
const lines = new Map<string, string[]>();
|
|
987
|
-
|
|
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) => {
|
|
988
779
|
const owner = span.turnIds?.[index];
|
|
989
780
|
if (owner) { const group = lines.get(owner) ?? []; group.push(line); lines.set(owner, group); }
|
|
990
781
|
});
|
|
991
|
-
for (const read of retained.reads) {
|
|
992
|
-
const owner = owners.get(read.entryId);
|
|
993
|
-
if (owner && entries.findIndex((entry) => entry.id === read.entryId) < cut)
|
|
994
|
-
lines.get(owner)?.push(`[Retained startup read: ${read.path}]\n${read.text.join("\n")}`);
|
|
995
|
-
}
|
|
996
782
|
return entries.filter((entry) => entry.type === "message" && entry.message.role === "user").map((entry) => {
|
|
997
783
|
const content = lines.get(entry.id) ?? [];
|
|
998
784
|
const deferred = tailOwners.has(entry.id);
|
|
@@ -1046,15 +832,11 @@ function excludedFilePaths(entries: SessionEntry[], excluded: Set<string>, first
|
|
|
1046
832
|
}
|
|
1047
833
|
|
|
1048
834
|
function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, cwd: string,
|
|
1049
|
-
|
|
1050
|
-
if (!excluded.size
|
|
1051
|
-
const owners = turnOwners(entries);
|
|
835
|
+
readRetention: ReadRetention, readFiles: string[], modifiedFiles: string[], excluded: Set<string>) {
|
|
836
|
+
if (!excluded.size) return { readRetention, readFiles, modifiedFiles };
|
|
1052
837
|
const removedPaths = excludedFilePaths(entries, excluded, firstKeptEntryId, cwd);
|
|
1053
838
|
return {
|
|
1054
|
-
|
|
1055
|
-
const owner = owners.get(read.entryId) ?? "";
|
|
1056
|
-
return !excluded.has(owner) && !fidelity[owner];
|
|
1057
|
-
}) },
|
|
839
|
+
readRetention,
|
|
1058
840
|
readFiles: readFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
1059
841
|
modifiedFiles: modifiedFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
1060
842
|
};
|
|
@@ -1065,17 +847,17 @@ const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current conten
|
|
|
1065
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.";
|
|
1066
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.";
|
|
1067
849
|
|
|
1068
|
-
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.
|
|
1069
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.**
|
|
1070
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.
|
|
1071
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.`;
|
|
1072
854
|
|
|
1073
|
-
const REVISION_NOTE_PREFIX = "-
|
|
855
|
+
const REVISION_NOTE_PREFIX = "- Checkpoint context revised: ";
|
|
1074
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}`;
|
|
1075
857
|
|
|
1076
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\`.`;
|
|
1077
859
|
|
|
1078
|
-
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs
|
|
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.";
|
|
1079
861
|
|
|
1080
862
|
const REORIENT_MESSAGE = "transparent-compact:reorient";
|
|
1081
863
|
const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead. If lookup findings are incomplete, use \`context_list_entries\`, \`context_grep\`, or \`context_show_entry\`, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE} Keep these evidence/recovery rules in force as work continues.`;
|
|
@@ -1160,6 +942,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
1160
942
|
spanTools?: ToolLines; // display records; no raw command/program payloads
|
|
1161
943
|
locations?: LocationEntry[];
|
|
1162
944
|
spanTurnIds?: (string | null)[];
|
|
945
|
+
spanReadPositions?: ReadPosition[];
|
|
1163
946
|
filteredTurnIds?: string[];
|
|
1164
947
|
fidelity?: TurnFidelities;
|
|
1165
948
|
slots?: TurnSlot[]; // generated output placements; no raw payloads
|
|
@@ -1167,9 +950,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
1167
950
|
spanFrom?: string; // ISO timestamp of the first summarised message
|
|
1168
951
|
spanTo?: string; // ISO timestamp of the last summarised message
|
|
1169
952
|
firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
|
|
1170
|
-
|
|
1171
|
-
modifiedFiles: string[];
|
|
1172
|
-
startupReads: StartupReads;
|
|
953
|
+
readRetention: ReadRetention;
|
|
1173
954
|
cwd: string;
|
|
1174
955
|
notify: (msg: string) => void;
|
|
1175
956
|
chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
|
|
@@ -1179,29 +960,29 @@ async function buildMechanicalSummary(opts: {
|
|
|
1179
960
|
const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
|
|
1180
961
|
const nativeMessages = [...native.values()].flat();
|
|
1181
962
|
const nativeChars = messageTokens(nativeMessages) * 4;
|
|
1182
|
-
const
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
}
|
|
1187
|
-
const rendered = fidelitySpans(filterSpans(opts.revisedAt ? spans : [...spans, {
|
|
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, {
|
|
1188
967
|
at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
|
|
1189
|
-
lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
|
|
1190
|
-
}],
|
|
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);
|
|
1191
972
|
const allSpans = rendered.spans;
|
|
1192
973
|
const locations = new Locations(opts.cwd, opts.locations ?? checkpointLocations(opts.branchEntries));
|
|
1193
|
-
const
|
|
1194
|
-
const dictionary = (ids: string[]) => locations.render(new Set([...fileIds, ...ids]));
|
|
974
|
+
const dictionary = (ids: string[]) => locations.render(new Set(ids));
|
|
1195
975
|
const dictionaryCost = (ids: string[]) => { const text = dictionary(ids); return text ? text.length + 2 : 0; };
|
|
1196
976
|
const allLocationIds = allSpans.flatMap((span) => span.tools?.lines.flatMap((line) => line.calls.flatMap((call) => call.locations ?? [])) ?? []);
|
|
1197
977
|
const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
|
|
1198
978
|
|
|
1199
|
-
//
|
|
1200
|
-
// The base and
|
|
1201
|
-
// 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.
|
|
1202
981
|
const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
|
|
1203
|
-
const
|
|
1204
|
-
|
|
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;
|
|
1205
986
|
if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
|
|
1206
987
|
overhead += allSpans.reduce(
|
|
1207
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,
|
|
@@ -1223,10 +1004,8 @@ async function buildMechanicalSummary(opts: {
|
|
|
1223
1004
|
if (maxChars === null) return undefined;
|
|
1224
1005
|
if (maxChars !== undefined && base && base.summary.length > maxChars)
|
|
1225
1006
|
opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
|
|
1226
|
-
if (maxChars !== undefined &&
|
|
1227
|
-
opts.notify(`transparent-compact: retained
|
|
1228
|
-
if (maxChars !== undefined && dictionaryCost([]) > maxChars)
|
|
1229
|
-
opts.notify(`transparent-compact: location definitions required by file lists exceed the budget; they are kept to avoid dangling references`);
|
|
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`);
|
|
1230
1009
|
if (maxChars !== undefined && nativeChars > maxChars)
|
|
1231
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.`);
|
|
1232
1011
|
const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost);
|
|
@@ -1272,31 +1051,10 @@ async function buildMechanicalSummary(opts: {
|
|
|
1272
1051
|
parts.push(SECTION_HEADER);
|
|
1273
1052
|
parts.push("");
|
|
1274
1053
|
parts.push(blocks.length > 0 ? blocks.join("\n\n") : "(no user or assistant prose in these spans — use context_lookup)");
|
|
1275
|
-
// The
|
|
1276
|
-
//
|
|
1277
|
-
// checkpoint; everything after it is pi's retained verbatim tail.
|
|
1278
|
-
if (retainedReads) parts.push("", retainedReads);
|
|
1279
|
-
const retainedPaths = new Set(opts.startupReads.reads.map((r) => fileEvidenceKey(r.path, opts.cwd)));
|
|
1280
|
-
const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
|
|
1281
|
-
if (hasFileLists) {
|
|
1282
|
-
const evidence = retainedFileEvidence(opts.branchEntries, opts.firstKeptEntryId, opts.cwd);
|
|
1283
|
-
const knownTail = opts.branchEntries.some((entry) => entry.id === opts.firstKeptEntryId);
|
|
1284
|
-
const fileLine = (file: string, modified: boolean): string => {
|
|
1285
|
-
const key = fileEvidenceKey(file, opts.cwd);
|
|
1286
|
-
const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
|
|
1287
|
-
? "startup read output retained in checkpoint or tail; may be partial"
|
|
1288
|
-
: nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
|
|
1289
|
-
: modified && knownTail ? "no read-tool output in tail" : undefined);
|
|
1290
|
-
return `${locations.ref(file, opts.cwd, 'path', true).id}${label ? ` (${label})` : ""}`;
|
|
1291
|
-
};
|
|
1292
|
-
parts.push("", FILE_LIST_EXPLANATION);
|
|
1293
|
-
if (opts.readFiles.length > 0)
|
|
1294
|
-
parts.push(`<read-files note="reads in compacted history; unless annotated, no retained read-tool output identified">\n${opts.readFiles.map((file) => fileLine(file, false)).join("\n")}\n</read-files>`);
|
|
1295
|
-
if (opts.modifiedFiles.length > 0)
|
|
1296
|
-
parts.push(`<modified-files note="modified in compacted history">\n${opts.modifiedFiles.map((file) => fileLine(file, true)).join("\n")}\n</modified-files>`);
|
|
1297
|
-
}
|
|
1054
|
+
// The location dictionary stays above the LAST checkpoint line; everything
|
|
1055
|
+
// after that line is Pi's verbatim tail.
|
|
1298
1056
|
const locationTable = dictionary(capped.locationIds);
|
|
1299
|
-
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);
|
|
1300
1058
|
parts.push("");
|
|
1301
1059
|
parts.push(EVIDENCE_BOUNDARY_RULE);
|
|
1302
1060
|
parts.push("");
|
|
@@ -1978,21 +1736,38 @@ export default function (pi: ExtensionAPI) {
|
|
|
1978
1736
|
|
|
1979
1737
|
const filterTurns = {
|
|
1980
1738
|
description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
|
|
1981
|
-
handler: async (args: string, ctx: ExtensionContext) => {
|
|
1982
|
-
|
|
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; }
|
|
1983
1742
|
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1984
|
-
ctx.ui.notify(
|
|
1743
|
+
ctx.ui.notify(`${command} requires the interactive terminal UI.`, "error"); return;
|
|
1985
1744
|
}
|
|
1986
1745
|
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1987
1746
|
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
1988
1747
|
}
|
|
1989
1748
|
const entries = ctx.sessionManager.getBranch();
|
|
1990
1749
|
const compaction = latestVerbatimCompaction(entries);
|
|
1991
|
-
if (compactionMethod(entries) !== "verbatim"
|
|
1992
|
-
ctx.ui.notify(
|
|
1750
|
+
if (compactionMethod(entries) !== "verbatim") {
|
|
1751
|
+
ctx.ui.notify(`${command} requires verbatim compaction.`, "error"); return;
|
|
1993
1752
|
}
|
|
1994
|
-
const
|
|
1995
|
-
|
|
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) {
|
|
1996
1771
|
ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
|
|
1997
1772
|
}
|
|
1998
1773
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
@@ -2003,9 +1778,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
2003
1778
|
const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
|
|
2004
1779
|
const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
|
|
2005
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;
|
|
2006
1792
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2007
1793
|
const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
|
|
2008
|
-
compaction.firstKeptEntryId,
|
|
1794
|
+
compaction.firstKeptEntryId, selectedReads(catalog, retention), proposed);
|
|
2009
1795
|
const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
|
|
2010
1796
|
pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
|
|
2011
1797
|
kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
|
|
@@ -2016,7 +1802,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2016
1802
|
now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
|
|
2017
1803
|
firstKeptEntryId: compaction.firstKeptEntryId,
|
|
2018
1804
|
...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
|
|
2019
|
-
|
|
1805
|
+
retention, canonical.readFiles, canonical.modifiedFiles, pruned),
|
|
2020
1806
|
cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
|
|
2021
1807
|
chooseCap: preview ? async () => {
|
|
2022
1808
|
if (cap.mode === "off") return undefined;
|
|
@@ -2045,7 +1831,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2045
1831
|
const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
|
|
2046
1832
|
applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
|
|
2047
1833
|
const original = await baseline;
|
|
2048
|
-
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 };
|
|
2049
1835
|
const presentation = { shortened: false };
|
|
2050
1836
|
const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
|
|
2051
1837
|
if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
|
|
@@ -2058,26 +1844,32 @@ export default function (pi: ExtensionAPI) {
|
|
|
2058
1844
|
fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
|
|
2059
1845
|
} : undefined };
|
|
2060
1846
|
};
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
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;
|
|
2066
1858
|
}
|
|
2067
1859
|
const summary = await renderCheckpoint(excluded, fidelity, slots, false);
|
|
2068
1860
|
if (summary === undefined) return;
|
|
2069
1861
|
checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
|
|
2070
1862
|
const current = ctx.sessionManager.getBranch();
|
|
2071
1863
|
if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
|
|
2072
|
-
latestFilterRevision(current)?.id !== revisionId) {
|
|
1864
|
+
latestFilterRevision(current)?.id !== revisionId || ctx.sessionManager.getLeafId() !== entries.at(-1)?.id || !ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
2073
1865
|
ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
|
|
2074
1866
|
}
|
|
2075
|
-
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
|
|
1867
|
+
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary, readRetention: retention,
|
|
2076
1868
|
filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
|
|
2077
1869
|
...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
|
|
2078
|
-
ctx.ui.notify("Checkpoint
|
|
1870
|
+
ctx.ui.notify("Checkpoint context updated. No additional history compacted; recent messages and boundary unchanged.", "info");
|
|
2079
1871
|
} catch (error) {
|
|
2080
|
-
ctx.ui.notify(`Checkpoint
|
|
1872
|
+
ctx.ui.notify(`Checkpoint context update cancelled: ${errMsg(error)}`, "error");
|
|
2081
1873
|
}
|
|
2082
1874
|
},
|
|
2083
1875
|
};
|
|
@@ -2122,6 +1914,36 @@ export default function (pi: ExtensionAPI) {
|
|
|
2122
1914
|
},
|
|
2123
1915
|
});
|
|
2124
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
|
+
});
|
|
2125
1947
|
|
|
2126
1948
|
pi.on("session_start", (_event, ctx) => {
|
|
2127
1949
|
clearAsideSubmission();
|
|
@@ -2172,10 +1994,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2172
1994
|
preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
|
|
2173
1995
|
.map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
|
|
2174
1996
|
const canonical = latestVerbatimCompaction(branchEntries)!.details as {
|
|
2175
|
-
|
|
1997
|
+
readRetention: ReadRetention; readFiles: string[]; modifiedFiles: string[];
|
|
2176
1998
|
};
|
|
2177
1999
|
const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2178
|
-
|
|
2000
|
+
readRetentionState(branchEntries, ctx), canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
|
|
2179
2001
|
const ops = preparation.fileOps;
|
|
2180
2002
|
ops.read = new Set(visible.readFiles);
|
|
2181
2003
|
ops.edited = new Set(visible.modifiedFiles);
|
|
@@ -2199,6 +2021,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2199
2021
|
|
|
2200
2022
|
// 1) Cumulative file lists: pi only carries lists from pi-generated
|
|
2201
2023
|
// compactions (fromHook=false), so we carry our own forward.
|
|
2024
|
+
let retainingReads = false;
|
|
2202
2025
|
try {
|
|
2203
2026
|
const fileOps = preparation.fileOps as { read: Set<string>; written: Set<string>; edited: Set<string> } | undefined;
|
|
2204
2027
|
if (fileOps) {
|
|
@@ -2238,13 +2061,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2238
2061
|
const spanFrom = toIso(msgTs(allMessages[0]));
|
|
2239
2062
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
2240
2063
|
const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
|
|
2241
|
-
|
|
2242
|
-
const span = await summarizeMessages(allMessages, renderer, preparedTurnOwners(branchEntries, allMessages));
|
|
2064
|
+
const span = await summarizeMessages(allMessages, renderer, preparedMessageSources(branchEntries, allMessages));
|
|
2243
2065
|
const spanLines = span.lines;
|
|
2244
2066
|
|
|
2245
|
-
// 3)
|
|
2246
|
-
|
|
2247
|
-
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;
|
|
2248
2071
|
const excluded = new Set(filteredTurns(branchEntries));
|
|
2249
2072
|
const keptAsides = new Set(keptAsideTurns(branchEntries));
|
|
2250
2073
|
const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
|
|
@@ -2252,13 +2075,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
2252
2075
|
const preflags = preflaggedTurns(branchEntries);
|
|
2253
2076
|
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2254
2077
|
const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
|
|
2255
|
-
excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
|
|
2078
|
+
excluded, preparation.firstKeptEntryId, selectedReads(catalog, canonicalRetained), proposed);
|
|
2256
2079
|
for (const turn of choices)
|
|
2257
2080
|
if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
|
|
2258
2081
|
}
|
|
2259
2082
|
const filteredTurnIds = [...excluded];
|
|
2260
2083
|
const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2261
|
-
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded
|
|
2084
|
+
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded);
|
|
2262
2085
|
const summary = await buildMechanicalSummary({
|
|
2263
2086
|
reason, // pi's raw reason, passed through unchanged
|
|
2264
2087
|
tokensBefore: preparation.tokensBefore,
|
|
@@ -2268,6 +2091,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
2268
2091
|
spanTools: span.tools,
|
|
2269
2092
|
locations: renderer.locations.entries,
|
|
2270
2093
|
spanTurnIds: span.turnIds,
|
|
2094
|
+
spanReadPositions: span.readPositions,
|
|
2271
2095
|
filteredTurnIds, fidelity, slots,
|
|
2272
2096
|
spanFrom,
|
|
2273
2097
|
spanTo,
|
|
@@ -2293,10 +2117,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
2293
2117
|
details: {
|
|
2294
2118
|
kind: MECH_KIND,
|
|
2295
2119
|
// Canonical metadata stays reversible; only the rendered checkpoint
|
|
2296
|
-
// masks file paths
|
|
2120
|
+
// masks file paths owned by excluded turns. Retained reads are independent.
|
|
2297
2121
|
readFiles: canonicalReadFiles,
|
|
2298
2122
|
modifiedFiles: canonicalModifiedFiles,
|
|
2299
|
-
|
|
2123
|
+
readRetention: canonicalRetained,
|
|
2300
2124
|
locations: renderer.locations.entries,
|
|
2301
2125
|
...(filteredTurnIds.length ? { filteredTurnIds } : {}),
|
|
2302
2126
|
...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
|
|
@@ -2304,13 +2128,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
2304
2128
|
// Only this compaction's own span (un-capped lines). Earlier spans
|
|
2305
2129
|
// are re-rendered from the earlier entries' details — no nesting.
|
|
2306
2130
|
span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
|
|
2307
|
-
lines: spanLines, turnIds: span.turnIds, ...(span.
|
|
2131
|
+
lines: spanLines, turnIds: span.turnIds, ...(span.readPositions ? { readPositions: span.readPositions } : {}),
|
|
2132
|
+
...(span.tools ? { tools: span.tools } : {}) },
|
|
2308
2133
|
},
|
|
2309
2134
|
},
|
|
2310
2135
|
};
|
|
2311
2136
|
} catch (err) {
|
|
2312
|
-
//
|
|
2313
|
-
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;
|
|
2314
2139
|
ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
|
|
2315
2140
|
return preserveFiltering ? { cancel: true } : undefined;
|
|
2316
2141
|
}
|