@foliox/transparent-compact-pi 0.8.9 → 0.10.0

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.
@@ -15,7 +15,7 @@
15
15
  * Valid continuation-only turns are exempt;
16
16
  * total search-phase calls capped at 3x this,
17
17
  * plus one final write-up on exhaustion
18
- * MECH_COMPACT_LOOKUP_MAX_CALLS consecutive lookup limit (default 1;
18
+ * MECH_COMPACT_LOOKUP_MAX_CALLS consecutive lookup limit (default 3;
19
19
  * 0 = unlimited). Non-recovery tool results,
20
20
  * bash executions, or user messages reset it.
21
21
  * Fallback tools neither count nor reset it.
@@ -33,6 +33,14 @@ import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-work
33
33
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
34
34
  import { buildSessionProjection, SessionManager } from "@earendil-works/pi-coding-agent";
35
35
  import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
36
+ import { capSpans, commandPreview, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
37
+ import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
38
+ import { FILTER_EXPLANATION, PREFLAG_ENTRY, AUTO_FILTER_ENTRY, FILTER_REVISION_ENTRY, autoFilterEnabled, preflaggedTurns,
39
+ filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
40
+ import type { FilterTurn, TurnSpan } from "./lib/turn-filter.js";
41
+ import { FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint,
42
+ messageTokens, previewMessages, checkCheckpointBudget, checkContextBudget, isExpandedCheckpoint, checkpointContextMessages, retainedTailMessages, estimateContext } from "./lib/turn-context.js";
43
+ import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, TurnSlot } from "./lib/turn-context.js";
36
44
 
37
45
  // ============================================================================
38
46
  // Configuration
@@ -72,7 +80,7 @@ function percentFromEnv(name: string, fallback: number): number {
72
80
  function lookupMaxCallsFromEnv(): number {
73
81
  const raw = process.env.MECH_COMPACT_LOOKUP_MAX_CALLS?.trim();
74
82
  const n = raw && /^\d+$/.test(raw) ? Number(raw) : NaN;
75
- return Number.isSafeInteger(n) && n >= 0 ? n : 1;
83
+ return Number.isSafeInteger(n) && n >= 0 ? n : 3;
76
84
  }
77
85
 
78
86
  const cfg = {
@@ -82,7 +90,7 @@ const cfg = {
82
90
  lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 25),
83
91
  lookupMaxCalls: lookupMaxCallsFromEnv(),
84
92
  lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
85
- argSnippetChars: 160,
93
+ argSnippetChars: NORMAL_PREVIEW_CHARS,
86
94
  listMaxChars: 12_000,
87
95
  grepMaxChars: 12_000,
88
96
  showEntryMaxChars: 24_000,
@@ -147,7 +155,7 @@ function persistCap(pi: ExtensionAPI, previous: CapSettings, next: CapSettings):
147
155
 
148
156
  // undefined means uncapped; null means cancel (never fall through to summary).
149
157
  async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal: AbortSignal | undefined,
150
- reason: string, size: { overhead: number; lineChars: number }): Promise<number | undefined | null> {
158
+ reason: string, size: { overhead: number; lineChars: number }, operation = "compaction"): Promise<number | undefined | null> {
151
159
  try {
152
160
  let state = capSettings(ctx.sessionManager.getBranch());
153
161
  for (;;) {
@@ -161,7 +169,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
161
169
  // Exactly the existing cap's test, including its minimum 500-char line budget.
162
170
  const needsTrim = size.lineChars > Math.max(500, limit - size.overhead);
163
171
  if (state.mode !== "warn" || !needsTrim) return limit;
164
- const warning = `Verbatim compaction would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
172
+ const warning = `Verbatim ${operation} would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
165
173
  if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
166
174
  ctx.ui.notify(`${warning} Applying the cap because no interactive UI is available.`, "warning");
167
175
  return limit;
@@ -170,7 +178,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
170
178
  ? "Overflow recovery: disabling the cap may leave too much context for the retry."
171
179
  : "Disabling the cap may leave too much context for the model.";
172
180
  const choice = await ctx.ui.select(`${warning}\n${risk}`, [
173
- "Apply trimming", "Disable cap for this session", "Change budget", "Cancel compaction",
181
+ "Apply trimming", "Disable cap for this session", "Change budget", `Cancel ${operation}`,
174
182
  ], { signal });
175
183
  if (signal?.aborted) return null;
176
184
  if (choice === "Apply trimming") return limit;
@@ -198,7 +206,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
198
206
  }
199
207
  }
200
208
  } catch (err) {
201
- if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); compaction cancelled`, "error");
209
+ if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); ${operation} cancelled`, "error");
202
210
  return null;
203
211
  }
204
212
  }
@@ -294,6 +302,28 @@ interface TranscriptIndexSection {
294
302
  startLine: number;
295
303
  }
296
304
 
305
+ // Pair only selected messages, by call id AND tool name. Ambiguous concurrent
306
+ // ids stay unknown; sequential reuse is allowed after consuming a result.
307
+ function pairedToolResults(messages: AgentMessage[]): Map<object, Record<string, any>> {
308
+ const results = new Map<object, Record<string, any>>();
309
+ const pending = new Map<string, { block: object; name: string } | null>();
310
+ for (const message of messages) {
311
+ const m = message as unknown as Record<string, any>;
312
+ if (m.role === "assistant") {
313
+ for (const block of m.content ?? []) {
314
+ if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
315
+ pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
316
+ }
317
+ } else if (m.role === "toolResult") {
318
+ const call = pending.get(m.toolCallId);
319
+ if (!call || call.name !== m.toolName) continue;
320
+ results.set(call.block, m);
321
+ pending.delete(m.toolCallId);
322
+ }
323
+ }
324
+ return results;
325
+ }
326
+
297
327
  interface TranscriptIndexEntry {
298
328
  id: string;
299
329
  type: string;
@@ -303,6 +333,8 @@ interface TranscriptIndexEntry {
303
333
  /** 1-based line number of the last line of the block (inclusive) */
304
334
  endLine: number;
305
335
  sections?: TranscriptIndexSection[];
336
+ /** Raw, unambiguously matched call/result entries; never parsed from text. */
337
+ relatedIds?: string[];
306
338
  }
307
339
 
308
340
  function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index: TranscriptIndexEntry[] } {
@@ -414,6 +446,25 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
414
446
  if (b.sections && b.sections.length > 0) e.sections = b.sections.map((s) => ({ kind: s.kind, startLine: b.hrIdx + s.rel + 3 }));
415
447
  return e;
416
448
  });
449
+ const byMessage = new Map<object, string>();
450
+ const byCall = new Map<object, string>();
451
+ const messages: AgentMessage[] = [];
452
+ for (const entry of entries) {
453
+ if (entry.type !== "message") continue;
454
+ messages.push(entry.message);
455
+ byMessage.set(entry.message, entry.id);
456
+ if (entry.message.role === "assistant")
457
+ for (const block of entry.message.content ?? [])
458
+ if (block.type === "toolCall") byCall.set(block, entry.id);
459
+ }
460
+ const byId = new Map(index.map((entry) => [entry.id, entry]));
461
+ for (const [call, result] of pairedToolResults(messages)) {
462
+ const callId = byCall.get(call), resultId = byMessage.get(result);
463
+ if (!callId || !resultId) continue;
464
+ const callEntry = byId.get(callId)!, resultEntry = byId.get(resultId)!;
465
+ (callEntry.relatedIds ??= []).push(resultId);
466
+ resultEntry.relatedIds = [callId];
467
+ }
417
468
  return { lines, index };
418
469
  }
419
470
 
@@ -444,48 +495,130 @@ function argumentSnippet(value: unknown): string {
444
495
  return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
445
496
  }
446
497
 
447
- function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
498
+ function toolSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): ToolStub {
499
+ const a = args ?? {};
500
+ if (!["read", "write", "edit", "bash"].includes(name))
501
+ return { prefix: `${name}(${Object.entries(a).map(([k, v]) => `${k}=${argumentSnippet(v)}`).join(", ")})`, suffix: "" };
448
502
  const parts: string[] = [];
449
- for (const [k, v] of Object.entries(args ?? {})) {
450
- let s: string;
451
- if (["read", "write", "edit"].includes(name) && k === "path" && typeof v === "string")
452
- s = JSON.stringify(checkpointPath(v, cwd)); // Keep the whole identifying path.
503
+ let command: ToolStub["command"];
504
+ const fileTool = ["read", "write", "edit"].includes(name) && typeof a.path === "string";
505
+ let base = fileTool ? `${name} ${JSON.stringify(checkpointPath(a.path as string, cwd))}` : name;
506
+ const range = name === "read" && fileTool &&
507
+ (a.offset === undefined || (Number.isSafeInteger(a.offset) && (a.offset as number) > 0)) &&
508
+ (a.limit === undefined || (Number.isSafeInteger(a.limit) && (a.limit as number) > 0));
509
+ if (range && (a.offset !== undefined || a.limit !== undefined)) {
510
+ const start = (a.offset as number | undefined) ?? 1;
511
+ const end = a.limit === undefined ? "" : start + (a.limit as number) - 1;
512
+ base += `:${start}-${end}`; // Requested range, not a claim about returned lines.
513
+ }
514
+ for (const [k, v] of Object.entries(a)) {
515
+ if (fileTool && k === "path") continue;
516
+ if (range && (k === "offset" || k === "limit")) continue;
517
+ if (name === "bash" && k === "timeout") continue;
518
+ if (name === "bash" && k === "command" && typeof v === "string")
519
+ command = commandPreview(JSON.stringify(checkpointCommand(v, cwd)));
453
520
  else if (name === "write" && k === "content" && typeof v === "string")
454
- s = `<${v.length} chars>`;
521
+ parts.push(`(${v.length} chars)`);
455
522
  else if (name === "edit" && k === "edits" && Array.isArray(v))
456
- s = String(v.length);
523
+ parts.push(`×${v.length}`);
457
524
  else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
458
- s = `<${v.length} chars>`;
459
- else
460
- s = argumentSnippet(name === "bash" && k === "command" && typeof v === "string" ? checkpointCommand(v, cwd) : v);
461
- parts.push(`${k}=${s}`);
525
+ parts.push(`${k}=<${v.length} chars>`);
526
+ else parts.push(`${k}=${argumentSnippet(v)}`);
462
527
  }
463
- return `${name}(${parts.join(", ")})`;
528
+ return command ? { prefix: `${base} `, command, suffix: parts.length ? ` ${parts.join(" ")}` : "" }
529
+ : { prefix: [base, ...parts].join(" "), suffix: "" };
464
530
  }
465
531
 
466
- function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
467
- // Pair calls with later results in Pi's selected messages only. Never infer
468
- // outcomes from result text, assistant claims, or another branch/the kept tail.
469
- const outcomes = new Map<object, "ok" | "error">();
470
- const pending = new Map<string, { block: object; name: string } | null>();
471
- for (const msg of messages) {
472
- const m = msg as unknown as Record<string, any>;
473
- if (m.role === "assistant") {
474
- for (const block of m.content ?? []) {
475
- if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
476
- // Concurrent duplicate IDs cannot be attributed safely. Sequential
477
- // reuse is fine once the preceding call's result has been consumed.
478
- pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
479
- }
480
- } else if (m.role === "toolResult") {
481
- const call = pending.get(m.toolCallId);
482
- if (!call || call.name !== m.toolName) continue;
483
- if (typeof m.isError === "boolean") outcomes.set(call.block, m.isError ? "error" : "ok");
484
- pending.delete(m.toolCallId);
485
- }
532
+ function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
533
+ return renderToolStub(toolSignature(name, args, cwd));
534
+ }
535
+
536
+ // Conservative lexical categories for selected output observations. These do
537
+ // not parse shell syntax or establish whether a command succeeded.
538
+ function commandHints(command: string): { tests: boolean; network: boolean; historical: boolean } {
539
+ const core = command.replace(/^\s*cd\s+(?:"[^"\n]*"|'[^'\n]*'|[^\s;&|]+)\s*&&\s*/, "").trimStart();
540
+ const tests = /^(?:(?:uv run |(?:\S*\/)?python[\d.]* -m )?pytest\b|(?:\S*\/)?pytest\b|(?:npm|pnpm|yarn) (?:run )?(?:test|build)\b|node --test\b|(?:\.\/)?gradlew\b|cargo (?:test|build)\b|go (?:test|build)\b|dotnet (?:test|build)\b|mvn (?:test|verify|package)\b)/.test(core);
541
+ const network = /^(?:curl|wget)\b/.test(core);
542
+ const readOnly = /^(?:cat|sed|awk|rg|grep|head|tail|find|ls|man|git)\b/.test(core);
543
+ const historical = !readOnly && (network || /^(?:timeout\s+\S+\s+)?tmux\b/.test(core) ||
544
+ /^(?:\S*\/)?(?:python[\d.]*|node|ruby|perl)\b[^\n]*(?:\s-[ce]\b|\s-\s*<<)/.test(core) ||
545
+ /^(?:uv run )?(?:\S*\/)?(?:python[\d.]*|node)\b/.test(core) ||
546
+ /^(?:time|hyperfine)\b|\b(?:bench(?:mark)?|timeit)\b/.test(core));
547
+ return { tests, network, historical };
548
+ }
549
+
550
+ function observationQuote(text: string): string {
551
+ if (JSON.stringify(text).length <= cfg.argSnippetChars) return JSON.stringify(text);
552
+ // Unlike a generic argument prefix, keep output quotations closed and escaped
553
+ // even when the source contains control characters or ends at a surrogate.
554
+ let end = Math.min(text.length, cfg.argSnippetChars);
555
+ while (JSON.stringify(text.slice(0, end) + "…").length > cfg.argSnippetChars) end--;
556
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
557
+ return JSON.stringify(text.slice(0, end) + "…");
558
+ }
559
+
560
+ function bashOutputLabel(command: string, result: Record<string, any>): string {
561
+ const content = result.content;
562
+ // Do not treat an image, structured-only result, or truncation notice as a
563
+ // tiny complete text observation. Summaries below quote selected text only.
564
+ const textOnly = typeof content === "string" || (Array.isArray(content) && content.length > 0 && content.every((b) => b?.type === "text" && typeof b.text === "string"));
565
+ if (!textOnly) return "";
566
+ const raw = textOf(content).text;
567
+ const structuredExit = result.structuredContent?.exit_code;
568
+ const hasStructuredExit = Number.isSafeInteger(structuredExit);
569
+ const suffix = /(?:^|\n)Command exited with code (-?\d+)\s*$/.exec(raw);
570
+ // Successful reads can print a fixture containing the wrapper's exact text.
571
+ // Prefer explicit metadata; trust a legacy nonzero footer only on tool error.
572
+ const exit = suffix && (hasStructuredExit ? Number(suffix[1]) === structuredExit : result.isError === true) ? suffix : undefined;
573
+ const bodyText = exit ? raw.slice(0, exit.index) : raw;
574
+ const body = bodyText.trim();
575
+ const partial = result.details?.truncation?.truncated === true || /\[(?:Output truncated|Showing last |Showing lines )/i.test(body);
576
+ const labels: string[] = [];
577
+ const reportedExit = hasStructuredExit ? structuredExit : exit ? Number(exit[1]) : undefined;
578
+ const exitCode = Number.isSafeInteger(reportedExit) ? reportedExit : undefined;
579
+ if (exitCode !== undefined && exitCode !== 0) labels.push(`exit ${exitCode}`); // Reported shell status, NOT pipeline/test status.
580
+ if (!partial && (bodyText === "" || body === "(no output)")) return [...labels, "no output"].join("; ");
581
+ const hints = commandHints(command);
582
+ const lines = body.replace(/\x1b\[[0-9;]*m/g, "").split("\n");
583
+ let observed: string[] = [];
584
+ if (hints.tests) {
585
+ observed = lines.filter((line) =>
586
+ /^=+ .*\b\d+ (?:passed|failed|errors?|skipped|xfailed)\b.*=+$/.test(line.trim()) ||
587
+ /^(?:\d+ (?:passed|failed|errors?|skipped|xfailed|deselected|warnings?)(?:, )?)+ in [\d.]+s$/.test(line.trim()) ||
588
+ /^(?:ℹ|#) (?:pass|fail) \d+$/.test(line.trim()) ||
589
+ /^BUILD (?:SUCCESSFUL|FAILED)\b/.test(line.trim()) ||
590
+ /^(?:PASS|FAIL): \d+\/\d+$/.test(line.trim())).slice(-3);
486
591
  }
487
- const lines: string[] = [];
488
- for (const msg of messages) {
592
+ if (hints.network) {
593
+ const codes = [...body.matchAll(/(?:^|\n)(?:HTTP\/[\d.]+\s+([1-5]\d\d)\b|http(?:_code)?[=: ]\s*([1-5]\d\d)\b)/gi)].map((m) => m[1] ?? m[2]);
594
+ if (codes.length) labels.push(`output: http ${codes.slice(0, 4).join(",")}${codes.length > 4 ? ",…" : ""}`);
595
+ }
596
+ // Only recognized execution commands get error-text scanning. In particular,
597
+ // never extract test/error labels from file reads, searches, or git views.
598
+ if (!observed.length && (hints.tests || hints.historical)) {
599
+ const errors = lines.filter((line) => line.trim()).slice(-6).filter((line) =>
600
+ /^(?:\s*\w*(?:Error|Exception):|Traceback \(most recent call last\):|error(?:\[\w+\])?:|fatal:)|command not found/.test(line));
601
+ observed = errors.slice(-1);
602
+ }
603
+ if (observed.length) labels.push(`output: ${observed.map((line) => observationQuote(line.trim())).join(" / ")}`);
604
+ else if (!labels.some((label) => label.startsWith("output:")) && hints.historical && !partial &&
605
+ bodyText.length <= 100 && JSON.stringify(bodyText).length <= cfg.argSnippetChars)
606
+ labels.push(`output: ${JSON.stringify(bodyText)}`);
607
+ // A commit hash is useful provenance, but only extract the git-generated
608
+ // bracketed form, not arbitrary lines that merely start with hex digits.
609
+ if (/^(?:git\b|.*&&\s*git\b)/.test(command) && /\bgit commit\b/.test(command)) {
610
+ const hash = /^\[[^\]\n]+ ([0-9a-f]{7,40})\]/m.exec(body)?.[1];
611
+ if (hash) labels.push(`commit ${hash}`);
612
+ }
613
+ return labels.join("; ");
614
+ }
615
+
616
+ function summarizeMessages(messages: AgentMessage[], cwd: string, owners?: (string | null)[]): TurnSpan {
617
+ const results = pairedToolResults(messages);
618
+ const lines: string[] = [], turnIds: (string | null)[] = [];
619
+ const tools: ToolLines = { version: 2, lines: [] };
620
+ for (const [messageIndex, msg] of messages.entries()) {
621
+ const start = lines.length;
489
622
  const m = msg as unknown as Record<string, any>;
490
623
  switch (msg.role) {
491
624
  case "user": {
@@ -495,15 +628,26 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
495
628
  }
496
629
  case "assistant": {
497
630
  let prose = "";
498
- const calls: string[] = [];
631
+ const calls: ToolStub[] = [];
499
632
  for (const block of m.content ?? []) {
500
633
  if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
501
- else if (block.type === "toolCall")
502
- calls.push(`${toolCallSignature(String(block.name), block.arguments, cwd)} [${outcomes.get(block) ?? "unknown"}]`);
634
+ else if (block.type === "toolCall") {
635
+ const name = String(block.name), args = block.arguments ?? {};
636
+ const result = results.get(block);
637
+ const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
638
+ const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
639
+ const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
640
+ const stub = toolSignature(name, args, cwd);
641
+ stub.suffix += status + (label ? ` → ${label}` : "");
642
+ calls.push(stub);
643
+ }
503
644
  // thinking blocks: removed by design (kept in the session)
504
645
  }
505
646
  if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
506
- if (calls.length > 0) lines.push(`[Assistant tool calls]: ${calls.join("; ")}`);
647
+ if (calls.length > 0) {
648
+ tools.lines.push({ index: lines.length, calls, mergeable: !prose.trim() });
649
+ lines.push(renderToolLine(calls));
650
+ }
507
651
  break;
508
652
  }
509
653
  case "toolResult":
@@ -525,8 +669,9 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
525
669
  default:
526
670
  break;
527
671
  }
672
+ for (let i = start; i < lines.length; i++) turnIds.push(owners?.[messageIndex] ?? null);
528
673
  }
529
- return lines;
674
+ return { lines, ...(owners ? { turnIds } : {}), ...(tools.lines.length ? { tools } : {}) };
530
675
  }
531
676
 
532
677
  // Startup reference retention is a lexical heuristic, not an interpretation of
@@ -640,7 +785,7 @@ function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstK
640
785
  const retained = state.reads.filter((r) => !tail.has(r.entryId));
641
786
  if (retained.length === 0) return "";
642
787
  return ["### Retained startup reads",
643
- "Original read outputs, preserved verbatim. Offsets and truncation notices are part of the original reads. These are not new filesystem reads. Tool-call status labels refer to the conversation spans, where outputs are removed, not these retained copies.",
788
+ "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.",
644
789
  ...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}`}>
645
790
  ${r.text.join("\n")}
646
791
  </retained-read>`),
@@ -770,15 +915,17 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
770
915
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
771
916
  * (the base is opaque; the session holds the raw history).
772
917
  */
918
+ type StoredSpan = TurnSpan & { at: string; reason: string; from?: string; to?: string };
919
+
773
920
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
774
921
  base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
775
- spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[];
922
+ spans: StoredSpan[];
776
923
  } {
777
924
  const spanDetails = (e: SessionEntry) => {
778
925
  if (e.type !== "compaction") return undefined;
779
926
  const d = (e as { details?: Record<string, any> }).details;
780
927
  if (!d || d.kind !== MECH_KIND || !Array.isArray(d.span?.lines)) return undefined;
781
- return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[] };
928
+ return d.span as TurnSpan & { at?: unknown; reason?: unknown; from?: unknown; to?: unknown };
782
929
  };
783
930
  let baseIdx = -1;
784
931
  for (let i = branchEntries.length - 1; i >= 0; i--) {
@@ -798,7 +945,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
798
945
  summary: (baseEntry as { summary?: string }).summary ?? "",
799
946
  }
800
947
  : null;
801
- const spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[] = [];
948
+ const spans: StoredSpan[] = [];
802
949
  for (let i = Math.max(baseIdx + 1, 0); i < branchEntries.length; i++) {
803
950
  const sd = spanDetails(branchEntries[i]);
804
951
  if (sd)
@@ -810,50 +957,161 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
810
957
  from: typeof sd.from === "string" && sd.from !== "" ? sd.from : undefined,
811
958
  to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
812
959
  lines: sd.lines,
960
+ tools: sd.tools,
961
+ turnIds: sd.turnIds,
813
962
  });
814
963
  }
815
964
  return { base, spans };
816
965
  }
817
966
 
818
- /**
819
- * Size guard across ordered spans (oldest first): if the total line budget is
820
- * exceeded, (1) drop the oldest non-user lines, (2) stub each oversized user
821
- * line at most once in a single forward pass (never re-stub → no loops),
822
- * (3) drop the oldest remaining lines until under budget. Everything dropped
823
- * remains in the session.
824
- */
825
- function capSpans(spans: string[][], budget: number): string[][] {
826
- const items: { span: number; line: string }[] = spans.flatMap((lines, span) => lines.map((line) => ({ span, line })));
827
- let size = items.reduce((a, it) => a + it.line.length + 1, 0);
828
- const over = () => size > budget;
829
- const remove = (i: number) => {
830
- size -= items[i].line.length + 1;
831
- items.splice(i, 1);
832
- };
967
+ interface FilterRevision {
968
+ compactionId: string;
969
+ summary: string;
970
+ filteredTurnIds: string[];
971
+ keptAsideTurnIds: string[];
972
+ fidelity?: TurnFidelities;
973
+ slots?: TurnSlot[];
974
+ }
975
+
976
+ function latestFilterRevision(entries: SessionEntry[]) {
977
+ const compaction = latestVerbatimCompaction(entries);
978
+ if (!compaction) return;
979
+ const entry = entries.slice(entries.indexOf(compaction) + 1).findLast((entry) =>
980
+ entry.type === "custom" && entry.customType === FILTER_REVISION_ENTRY &&
981
+ (entry.data as FilterRevision)?.compactionId === compaction.id);
982
+ return entry?.type === "custom" ? entry as typeof entry & { data: FilterRevision } : undefined;
983
+ }
984
+
985
+ function filteredTurns(entries: SessionEntry[]): string[] {
986
+ return latestFilterRevision(entries)?.data.filteredTurnIds ??
987
+ (latestVerbatimCompaction(entries)?.details as { filteredTurnIds?: string[] } | undefined)?.filteredTurnIds ?? [];
988
+ }
989
+
990
+ function keptAsideTurns(entries: SessionEntry[]): string[] {
991
+ return latestFilterRevision(entries)?.data.keptAsideTurnIds ??
992
+ (latestVerbatimCompaction(entries)?.details as { keptAsideTurnIds?: string[] } | undefined)?.keptAsideTurnIds ?? [];
993
+ }
994
+
995
+ function turnFidelities(entries: SessionEntry[]): TurnFidelities {
996
+ const revision = latestFilterRevision(entries);
997
+ return revision ? revision.data.fidelity ?? {} :
998
+ (latestVerbatimCompaction(entries)?.details as { fidelity?: TurnFidelities } | undefined)?.fidelity ?? {};
999
+ }
1000
+
1001
+ function projectCheckpoint(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
1002
+ const compaction = latestVerbatimCompaction(entries), revision = latestFilterRevision(entries);
1003
+ const fidelity = turnFidelities(entries);
1004
+ if (!compaction || (!revision && !Object.keys(fidelity).length)) return messages;
1005
+ const saved = revision?.data ?? compaction.details as { slots?: TurnSlot[] };
1006
+ if (messages.some((message) => isExpandedCheckpoint(message, revision?.data.summary ?? compaction.summary))) return messages;
1007
+ // Expand only the active checkpoint using generated offsets, not historical
1008
+ // text patterns. Original records and the retained tail remain untouched.
1009
+ return messages.flatMap((message) => message.role === "compactionSummary"
1010
+ ? expandCheckpoint(message, revision?.data.summary ?? message.summary, saved.slots ?? [], fidelity, entries, compaction.firstKeptEntryId)
1011
+ : [message]);
1012
+ }
1013
+
1014
+ // Match Pi's prepared messages to their source entries, including explicit
1015
+ // context replacements and generated custom messages. No raw bodies are stored.
1016
+ function preparedTurnOwners(entries: SessionEntry[], messages: AgentMessage[]): (string | null)[] {
1017
+ const owners = turnOwners(entries);
1018
+ const queues = new Map<string, (string | null)[]>();
1019
+ for (const projected of buildSessionProjection(entries).entries) {
1020
+ if (projected.sourceEntry.type === "compaction") continue;
1021
+ for (const message of projected.messages) {
1022
+ const key = JSON.stringify(message);
1023
+ const queue = queues.get(key) ?? [];
1024
+ queue.push(owners.get(projected.sourceEntry.id) ?? null);
1025
+ queues.set(key, queue);
1026
+ }
1027
+ }
1028
+ return messages.map((message) => queues.get(JSON.stringify(message))?.shift() ?? null);
1029
+ }
1030
+
1031
+ function filterChoices(entries: SessionEntry[], spans: TurnSpan[], excluded: Set<string>, firstKeptEntryId: string,
1032
+ retained: StartupReads, selected = excluded, fidelity: TurnFidelities = turnFidelities(entries)): FilterTurn[] {
1033
+ const owners = turnOwners(entries), flagged = preflaggedTurns(entries);
1034
+ const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
1035
+ const tailOwners = new Set(entries.slice(cut).filter((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary")
1036
+ .map((entry) => owners.get(entry.id)));
1037
+ const lines = new Map<string, string[]>();
1038
+ for (const span of spans) span.lines.forEach((line, index) => {
1039
+ const owner = span.turnIds?.[index];
1040
+ if (owner) { const group = lines.get(owner) ?? []; group.push(line); lines.set(owner, group); }
1041
+ });
1042
+ for (const read of retained.reads) {
1043
+ const owner = owners.get(read.entryId);
1044
+ if (owner && entries.findIndex((entry) => entry.id === read.entryId) < cut)
1045
+ lines.get(owner)?.push(`[Retained startup read: ${read.path}]\n${read.text.join("\n")}`);
1046
+ }
1047
+ return entries.filter((entry) => entry.type === "message" && entry.message.role === "user").map((entry) => {
1048
+ const content = lines.get(entry.id) ?? [];
1049
+ const deferred = tailOwners.has(entry.id);
1050
+ const unavailable = deferred ? (flagged.has(entry.id) ? undefined : "in retained recent tail")
1051
+ : content.length === 0 ? "not individually represented in checkpoint" : undefined;
1052
+ const cache = new Map<string, { tokens: number; lines: string[] }>();
1053
+ return { id: entry.id, fidelity: fidelity[entry.id], fidelityInfo: (mode) => {
1054
+ if (!cache.has(mode)) {
1055
+ const messages = fidelityMessages(entries, { [entry.id]: mode }, firstKeptEntryId).get(entry.id)!;
1056
+ cache.set(mode, { tokens: messageTokens(messages), lines: previewMessages(messages) });
1057
+ }
1058
+ return cache.get(mode)!;
1059
+ }, label: content[0] ?? `[User]: ${entry.type === "message" ? textOf((entry.message as any).content).text : ""}`,
1060
+ lines: content, selected: excluded.has(entry.id) || (!unavailable && selected.has(entry.id)),
1061
+ filtered: excluded.has(entry.id), deferred, unavailable };
1062
+ });
1063
+ }
833
1064
 
834
- // 1) drop oldest non-user lines (flat order = span order = oldest first;
835
- // terminates: each pass removes a line or advances i)
836
- for (let i = 0; i < items.length && over(); ) {
837
- if (items[i].line.startsWith("[User]:")) i++;
838
- else remove(i);
1065
+ function applyTurnSelection(choices: FilterTurn[], result: TurnSelection, preflags: Set<string>,
1066
+ excluded: Set<string>, keptAsides: Set<string>, fidelity: TurnFidelities): void {
1067
+ const selected = new Set(result.pruned);
1068
+ for (const turn of choices) {
1069
+ if (turn.unavailable) continue;
1070
+ if (!turn.deferred) {
1071
+ if (selected.has(turn.id)) excluded.add(turn.id); else excluded.delete(turn.id);
1072
+ if (!selected.has(turn.id) && result.fidelity[turn.id]) fidelity[turn.id] = result.fidelity[turn.id];
1073
+ else delete fidelity[turn.id];
1074
+ }
1075
+ if (preflags.has(turn.id)) {
1076
+ if (selected.has(turn.id)) keptAsides.delete(turn.id); else keptAsides.add(turn.id);
1077
+ }
839
1078
  }
840
- // 2) stub user lines, oldest first, each at most once (terminates: single forward pass)
841
- for (let i = 0; i < items.length && over(); i++) {
842
- const line = items[i].line;
843
- if (!line.startsWith("[User]:") || line.length <= 120) continue;
844
- const stub = `${line.slice(0, 120)}…[truncated +${line.length - 120} chars — use context_lookup]`;
845
- if (stub.length >= line.length) continue; // stubbing would not shrink it; step 3 drops it
846
- size += stub.length - line.length;
847
- items[i] = { ...items[i], line: stub };
1079
+ }
1080
+
1081
+ // Remove file-list traces belonging only to excluded turns. A path also used
1082
+ // by a kept turn stays listed; filtering is not a claim that mutations were undone.
1083
+ function excludedFilePaths(entries: SessionEntry[], excluded: Set<string>, firstKeptEntryId: string, cwd: string): Set<string> {
1084
+ const owners = turnOwners(entries), removed = new Set<string>(), kept = new Set<string>();
1085
+ const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
1086
+ for (const entry of entries.slice(0, cut)) {
1087
+ if (entry.type !== "message") continue;
1088
+ const m = entry.message as any;
1089
+ const calls = m.role === "assistant" ? (m.content ?? []).filter((b: any) => b.type === "toolCall")
1090
+ : m.role === "toolResult" ? m.nestedCalls?.calls ?? [] : [];
1091
+ for (const call of calls) {
1092
+ if (!["read", "write", "edit"].includes(call.name) || typeof call.arguments?.path !== "string") continue;
1093
+ (excluded.has(owners.get(entry.id) ?? "") ? removed : kept).add(fileEvidenceKey(call.arguments.path, cwd));
1094
+ }
848
1095
  }
849
- // 3) drop oldest remaining lines until under budget (terminates: removes one per iteration)
850
- while (over() && items.length > 0) remove(0);
1096
+ return new Set([...removed].filter((file) => !kept.has(file)));
1097
+ }
851
1098
 
852
- return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
1099
+ function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, cwd: string,
1100
+ startup: StartupReads, readFiles: string[], modifiedFiles: string[], excluded: Set<string>, fidelity: TurnFidelities = {}) {
1101
+ if (!excluded.size && !Object.keys(fidelity).length) return { startupReads: startup, readFiles, modifiedFiles };
1102
+ const owners = turnOwners(entries);
1103
+ const removedPaths = excludedFilePaths(entries, excluded, firstKeptEntryId, cwd);
1104
+ return {
1105
+ startupReads: { ...startup, reads: startup.reads.filter((read) => {
1106
+ const owner = owners.get(read.entryId) ?? "";
1107
+ return !excluded.has(owner) && !fidelity[owner];
1108
+ }) },
1109
+ readFiles: readFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
1110
+ modifiedFiles: modifiedFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
1111
+ };
853
1112
  }
854
1113
 
855
1114
  const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
856
- const RECOVERY_TRIGGERS = "Ask `context_lookup` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence.";
857
1115
  const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
858
1116
  const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
859
1117
  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.";
@@ -863,11 +1121,12 @@ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_N
863
1121
  2. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
864
1122
  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.`;
865
1123
 
1124
+ const REVISION_NOTE_PREFIX = "- Turn context revised: ";
866
1125
  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}`;
867
1126
 
868
- const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Prefer \`context_lookup\` with a specific historical question: a subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SCOPE_RULE} If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`; follow their pagination instructions for more detail. ${RECOVERY_FILESYSTEM_RULE}`;
1127
+ 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\`.`;
869
1128
 
870
- const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; use `context_lookup` when you need that historical evidence or its provenance, and inspect the source when you need current state.";
1129
+ const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs and file lists 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.";
871
1130
 
872
1131
  const REORIENT_MESSAGE = "transparent-compact:reorient";
873
1132
  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.`;
@@ -880,18 +1139,19 @@ function latestVerbatimCompaction(entries: SessionEntry[]) {
880
1139
  }
881
1140
  }
882
1141
 
883
- function reorientationMessage(compactionId: string) {
884
- return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}\n\n${RECOVERY_RECAP}`,
885
- display: false, details: { compactionId } };
1142
+ function reorientationMessage(compactionId: string, filtered = false, revisionId = compactionId, fidelity = false) {
1143
+ return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}${filtered ? `\n\n${FILTER_EXPLANATION}` : ""}${fidelity ? `\n\n${FIDELITY_EXPLANATION}` : ""}\n\n${RECOVERY_RECAP}`,
1144
+ display: false, details: { compactionId, ...(revisionId !== compactionId ? { revisionId } : {}) } };
886
1145
  }
887
1146
 
888
1147
  function isReorientation(msg: AgentMessage): boolean {
889
1148
  return msg.role === "custom" && msg.customType === REORIENT_MESSAGE;
890
1149
  }
891
1150
 
892
- function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
893
- return msg.role === "custom" && msg.customType === REORIENT_MESSAGE &&
894
- (msg.details as { compactionId?: string } | undefined)?.compactionId === compactionId;
1151
+ function reorientationFor(msg: AgentMessage, compactionId: string, revisionId: string): boolean {
1152
+ const details = msg.role === "custom" ? msg.details as { compactionId?: string; revisionId?: string } | undefined : undefined;
1153
+ return isReorientation(msg) && details?.compactionId === compactionId &&
1154
+ (details.revisionId ?? details.compactionId) === revisionId;
895
1155
  }
896
1156
 
897
1157
  /** Keep one current, persisted checklist. Obsolete managed messages can still be
@@ -900,12 +1160,13 @@ function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
900
1160
  * Later requests keep it in history before the work that followed it. */
901
1161
  function projectReorientation(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
902
1162
  const compaction = latestVerbatimCompaction(entries);
1163
+ const anchor = latestFilterRevision(entries) ?? compaction;
903
1164
  let selected = -1;
904
1165
  for (let i = 0; i < messages.length; i++)
905
- if (compaction && reorientationFor(messages[i], compaction.id)) selected = i;
1166
+ if (compaction && reorientationFor(messages[i], compaction.id, anchor!.id)) selected = i;
906
1167
  const result = messages.filter((m, i) => !isReorientation(m) || i === selected);
907
1168
  if (selected < 0 || !compaction) return result;
908
- const answered = entries.slice(entries.indexOf(compaction) + 1).some((e) =>
1169
+ const answered = entries.slice(entries.indexOf(anchor!) + 1).some((e) =>
909
1170
  e.type === "message" && e.message.role === "assistant" &&
910
1171
  e.message.stopReason !== "aborted" && e.message.stopReason !== "error");
911
1172
  if (!answered) {
@@ -915,12 +1176,44 @@ function projectReorientation(messages: AgentMessage[], entries: SessionEntry[])
915
1176
  return result;
916
1177
  }
917
1178
 
1179
+ /** Attribute generated notice costs without touching quoted historical text.
1180
+ * Notices occur only in the generated prefix, before SECTION_HEADER. Using the
1181
+ * real estimator on counterfactual messages keeps counts tied to current text.
1182
+ */
1183
+ function contextNoticeTokens(messages: AgentMessage[], reminder: AgentMessage): NoticeTokens {
1184
+ const first = messages.find((message) => message.role === "compactionSummary");
1185
+ if (!first || first.role !== "compactionSummary" || reminder.role !== "custom" || typeof reminder.content !== "string")
1186
+ throw new Error("Cannot identify generated context notices.");
1187
+ const end = first.summary.indexOf(SECTION_HEADER);
1188
+ if (end < 0) throw new Error("Cannot identify the checkpoint introduction.");
1189
+ let header = first.summary.slice(0, end), content = reminder.content;
1190
+ const body = first.summary.slice(end);
1191
+ const revision = header.split("\n").find((line) => line.startsWith(REVISION_NOTE_PREFIX)) ?? "";
1192
+ const notes: NoticeTokens = { pruning: 0, revision: 0, fidelity: 0 };
1193
+ const parts: [keyof NoticeTokens, string][] = [["pruning", FILTER_EXPLANATION], ["revision", revision], ["fidelity", FIDELITY_EXPLANATION]];
1194
+ for (const [kind, text] of parts) {
1195
+ if (!text) continue;
1196
+ const before = messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
1197
+ header = header.replace(`${text}\n`, "");
1198
+ if (kind !== "revision") content = content.replace(`\n\n${text}`, "");
1199
+ notes[kind] = before - messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
1200
+ }
1201
+ return notes;
1202
+ }
1203
+
918
1204
  async function buildMechanicalSummary(opts: {
919
1205
  reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
920
1206
  tokensBefore: number;
921
1207
  branchEntries: SessionEntry[];
922
1208
  now: string;
923
1209
  spanLines: string[]; // this compaction's own span, un-capped
1210
+ revisedAt?: string; // rebuild existing spans only; no new compaction or boundary
1211
+ spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
1212
+ spanTurnIds?: (string | null)[];
1213
+ filteredTurnIds?: string[];
1214
+ fidelity?: TurnFidelities;
1215
+ slots?: TurnSlot[]; // generated output placements; no raw payloads
1216
+ presentation?: { shortened: boolean }; // optional presentation-accounting output
924
1217
  spanFrom?: string; // ISO timestamp of the first summarised message
925
1218
  spanTo?: string; // ISO timestamp of the last summarised message
926
1219
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
@@ -932,7 +1225,20 @@ async function buildMechanicalSummary(opts: {
932
1225
  chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
933
1226
  }): Promise<string | undefined> {
934
1227
  const { base, spans } = collectBaseAndSpans(opts.branchEntries);
935
- const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo, lines: opts.spanLines }];
1228
+ const fidelity = opts.fidelity ?? {};
1229
+ const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
1230
+ const nativeMessages = [...native.values()].flat();
1231
+ const nativeChars = messageTokens(nativeMessages) * 4;
1232
+ const nativeResults = pairedToolResults(nativeMessages), nativeReadPaths = new Set<string>();
1233
+ for (const message of nativeMessages) if (message.role === "assistant") for (const block of message.content) {
1234
+ if (block.type === "toolCall" && block.name === "read" && typeof block.arguments?.path === "string" && nativeResults.get(block)?.isError === false)
1235
+ nativeReadPaths.add(fileEvidenceKey(block.arguments.path, opts.cwd));
1236
+ }
1237
+ const rendered = fidelitySpans(filterSpans(opts.revisedAt ? spans : [...spans, {
1238
+ at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1239
+ lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
1240
+ }], new Set(opts.filteredTurnIds)), fidelity);
1241
+ const allSpans = rendered.spans;
936
1242
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
937
1243
 
938
1244
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -940,10 +1246,10 @@ async function buildMechanicalSummary(opts: {
940
1246
  // exceed the budget by itself; warn rather than silently dropping evidence.
941
1247
  const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
942
1248
  const retainedReads = renderStartupReads(opts.startupReads, opts.branchEntries, opts.firstKeptEntryId);
943
- let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
1249
+ let overhead = nativeChars + SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
944
1250
  if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
945
1251
  overhead += allSpans.reduce(
946
- (a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
1252
+ (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,
947
1253
  0,
948
1254
  );
949
1255
  // Closing line: where the verbatim (uncompacted) tail begins. Spans end at
@@ -964,34 +1270,41 @@ async function buildMechanicalSummary(opts: {
964
1270
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
965
1271
  if (maxChars !== undefined && retainedReads.length > maxChars)
966
1272
  opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
967
- const capped = maxChars === undefined ? lines : capSpans(lines, Math.max(500, maxChars - overhead));
1273
+ if (maxChars !== undefined && nativeChars > maxChars)
1274
+ 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.`);
1275
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
1276
+ if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
968
1277
 
969
1278
  const blocks: string[] = [];
970
1279
  if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
971
- capped.forEach((lines, i) => {
1280
+ capped.lines.forEach((lines, i) => {
972
1281
  const s = allSpans[i];
973
- const trimmed = lines.length !== s.lines.length || lines.some((line, j) => line !== s.lines[j]);
1282
+ const trimmed = capped.trimmed[i];
974
1283
  const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
1284
+ const attributes = (capped.tightened[i] ? TIGHTENED_ATTR : "") + (trimmed ? SPAN_TRIMMED_ATTR : "");
975
1285
  blocks.push([
976
- trimmed ? `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>` : open,
1286
+ attributes ? `${open.slice(0, -1)}${attributes}>` : open,
977
1287
  ...(trimmed ? [SPAN_TRIMMED_NOTE] : []),
978
1288
  ...lines,
979
1289
  SPAN_CLOSE,
980
1290
  ].join("\n"));
981
1291
  });
982
1292
 
983
- const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
1293
+ const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + (opts.revisedAt ? 0 : 1);
984
1294
  const parts: string[] = [];
985
1295
  parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
986
1296
  parts.push(CHECKPOINT_EXPLANATION);
1297
+ if (opts.filteredTurnIds?.length) parts.push(FILTER_EXPLANATION);
1298
+ if (native.size) parts.push(FIDELITY_EXPLANATION);
987
1299
  if (base?.kind === "model-summary") {
988
1300
  parts.push(MIXED_CONTEXT_WARNING);
989
1301
  opts.notify(MIXED_CONTEXT_WARNING);
990
1302
  }
991
1303
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
992
- parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming; tool calls are kept as one-line signatures. Paths under the session working directory are shown relative to it (as `.` in shell commands). Write contents and edit payloads are replaced by sizes/counts; other argument snippets keep up to 160 characters followed by an ellipsis when abbreviated. Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
993
- parts.push("- Tool status: ok = result not flagged as an error; error = result flagged as an error; unknown = no safely matched result/status. Output content is removed in all cases. ok does not prove a command or tests passed. Calls without a status in older spans have unknown outcomes.");
994
- parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Previously saved spans are unchanged.");
1304
+ if (opts.revisedAt) parts.push(`${REVISION_NOTE_PREFIX}${opts.revisedAt}. No additional history was compacted; the verbatim boundary is unchanged.`);
1305
+ parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming. Retained prose is a record of what was said, not verification of its claims. Tool signatures are display notation, not replayable shell commands: paths under the working directory become relative (`.` in commands); read ranges are requested lines; write/edit payloads become sizes/counts. New bash previews keep the first 160 encoded characters, followed by … when truncated, with escaped newlines. Thinking and most output are removed; selected output observations remain after →.");
1306
+ parts.push("- [tool error] means the result was flagged as an error; [unknown] means no safely matched result/status. Unlabelled does NOT establish exit 0 or passing tests. → exit N is a reported shell status; output: quotes/extracts selected output, not an inferred verdict. Everything shown is historical. Legacy [ok] only means not flagged as a tool error; legacy calls without status are unknown.");
1307
+ parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Stored canonical spans are unchanged; their presentation may tighten under the cap.");
995
1308
  parts.push(
996
1309
  "- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that. The retained verbatim conversation begins after the explicit boundary marker at the end of this checkpoint.",
997
1310
  );
@@ -1015,6 +1328,7 @@ async function buildMechanicalSummary(opts: {
1015
1328
  const key = fileEvidenceKey(file, opts.cwd);
1016
1329
  const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
1017
1330
  ? "startup read output retained in checkpoint or tail; may be partial"
1331
+ : nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
1018
1332
  : modified && knownTail ? "no read-tool output in tail" : undefined);
1019
1333
  return `${checkpointPath(file, opts.cwd)}${label ? ` (${label})` : ""}`;
1020
1334
  };
@@ -1029,7 +1343,10 @@ async function buildMechanicalSummary(opts: {
1029
1343
  parts.push("");
1030
1344
  parts.push(closingLine);
1031
1345
 
1032
- return parts.join("\n");
1346
+ const summary = parts.join("\n");
1347
+ if (native.size && !opts.slots) throw new Error("Missing full-fidelity placement output.");
1348
+ opts.slots?.push(...locateSlots(summary, rendered.markers, fidelity));
1349
+ return summary;
1033
1350
  }
1034
1351
 
1035
1352
  // ============================================================================
@@ -1189,16 +1506,22 @@ function grepTranscript(transcripts: Transcript[], opts: GrepOptions, onContinua
1189
1506
  return out.join("\n\n") + notice;
1190
1507
  }
1191
1508
 
1192
- function showEntry(transcripts: Transcript[], opts: { id: string; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1509
+ function showEntry(transcripts: Transcript[], opts: { id: string; includeRelated?: boolean; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1193
1510
  const targets = opts.file ? transcripts.filter((d) => d.name === opts.file) : transcripts;
1194
1511
  const out: string[] = [];
1195
1512
  const headers: string[] = [];
1196
1513
  for (const d of targets) {
1197
1514
  const e = d.index.find((x) => x.id === opts.id);
1198
1515
  if (!e) continue;
1199
- const block = d.lines.slice(e.startLine - 2, e.endLine); // includes the rule before the header
1200
- out.push(`### ${d.name}\n${block.join("\n")}`);
1201
- headers.push(`${d.name}: ${d.lines[e.startLine - 1]}`);
1516
+ const ids = new Set([e.id, ...(opts.includeRelated === true ? e.relatedIds ?? [] : [])]);
1517
+ // Chronological, one-hop expansion: a result includes its originating
1518
+ // assistant, not all sibling outputs. An assistant includes its results.
1519
+ for (const entry of d.index) {
1520
+ if (!ids.has(entry.id)) continue;
1521
+ const block = d.lines.slice(entry.startLine - 2, entry.endLine);
1522
+ out.push(`### ${d.name}\n${block.join("\n")}`);
1523
+ headers.push(`${d.name}: ${d.lines[entry.startLine - 1]}`);
1524
+ }
1202
1525
  }
1203
1526
  return out.length ? pageText(out.join("\n\n"), {
1204
1527
  offset: opts.offset, maxChars: cfg.showEntryMaxChars,
@@ -1222,7 +1545,8 @@ const GREP_FIELDS = {
1222
1545
  throughEntry: THROUGH_ENTRY_FIELD,
1223
1546
  };
1224
1547
  const SHOW_FIELDS = {
1225
- id: Type.String({ description: "Entry id" }),
1548
+ id: Type.String({ description: "ENTRY id" }),
1549
+ includeRelated: Type.Optional(Type.Boolean({ description: "Include unambiguously matched tool call/result entries (default false). Keep unchanged when paging." })),
1226
1550
  maxLines: Type.Optional(Type.Integer({ minimum: 1, description: "Max lines per page (default 400); character limit also applies" })),
1227
1551
  offset: OFFSET_FIELD,
1228
1552
  };
@@ -1248,7 +1572,7 @@ const LOOKUP_SYSTEM_PROMPT = `You are a context-lookup subagent for a coding age
1248
1572
  You have three tools:
1249
1573
  - list_entries: paginated overview of entries (id, role, timestamp, preview)
1250
1574
  - grep: paginated transcript search; matches come with surrounding lines and authoritative ENTRY attribution
1251
- - show_entry: retrieve an entry by id in bounded pages
1575
+ - show_entry: retrieve an entry by id in bounded pages; includeRelated=true also shows its matched tool call/result
1252
1576
 
1253
1577
  Search tools bound each response, not the underlying history. A partial page is not the entire evidence, but you do NOT need to exhaust every page. Follow continuation parameters only when omitted content is needed to answer the question, keeping all other search/context parameters unchanged. Narrow an overly broad search rather than paging through irrelevant matches. Stop paging once you have sufficient relevant evidence.
1254
1578
 
@@ -1289,6 +1613,7 @@ function lookupPageKey(name: string, args: Record<string, any>): string | undefi
1289
1613
  break;
1290
1614
  case "show_entry":
1291
1615
  fields = [typeof args.id === "string" ? args.id : undefined, string("file"),
1616
+ typeof (args.includeRelated ?? false) === "boolean" ? (args.includeRelated ?? false) : undefined,
1292
1617
  number("maxLines", 400, 1), number("offset", 0)];
1293
1618
  break;
1294
1619
  default:
@@ -1319,7 +1644,7 @@ async function runLookupSubagent(opts: {
1319
1644
  },
1320
1645
  {
1321
1646
  name: "show_entry",
1322
- description: "Retrieve an indexed entry by ENTRY id in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset only if omitted content is needed; a page may not contain the entire entry.",
1647
+ description: "Retrieve an indexed entry by ENTRY id, optionally with matched tool call/result entries (includeRelated=true), in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset only if omitted content is needed; keep includeRelated unchanged when paging.",
1323
1648
  parameters: Type.Object({ ...SHOW_FIELDS, file: FILE_FIELD }),
1324
1649
  },
1325
1650
  ];
@@ -1524,7 +1849,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1524
1849
  pi.registerTool({
1525
1850
  name: "context_grep",
1526
1851
  label: "Context: grep",
1527
- description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and authoritative entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1852
+ description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1528
1853
  promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
1529
1854
  parameters: Type.Object(GREP_FIELDS),
1530
1855
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
@@ -1534,8 +1859,8 @@ function registerDirectTools(pi: ExtensionAPI): void {
1534
1859
  pi.registerTool({
1535
1860
  name: "context_show_entry",
1536
1861
  label: "Context: show entry",
1537
- description: pre + "Retrieve an indexed session entry by ENTRY id (from context_list_entries or context_grep) in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset for the rest; a page may not contain the entire entry.",
1538
- promptSnippet: "Fallback: retrieve this conversation's entries for post-compaction recovery",
1862
+ description: "Read a known raw session entry to recover a specific detail hidden by compaction. Use an ENTRY id returned by context_lookup, context_grep, or context_list_entries. Prefer context_lookup when search or interpretation is needed; same scope as context_lookup. Start with a small maxLines. Optional includeRelated=true includes matched tool call/result entries; use it only if the counterpart is needed. Returns up to 24000 payload characters and maxLines lines per page, plus attribution/cursor notes; a page may not contain the entire entry. Continue with the reported offset only if the requested detail is missing, incomplete, or needs more context to resolve ambiguity, keeping includeRelated unchanged. Stop once the question is answered; do not expand surrounding history by default.",
1863
+ promptSnippet: "Recover a specific detail hidden by compaction at a known ENTRY id in this conversation.",
1539
1864
  parameters: Type.Object(SHOW_FIELDS),
1540
1865
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1541
1866
  return run(ctx, (t) => showEntry(t, params));
@@ -1548,15 +1873,39 @@ function registerDirectTools(pi: ExtensionAPI): void {
1548
1873
  // ============================================================================
1549
1874
 
1550
1875
  export default function (pi: ExtensionAPI) {
1876
+ // Only bridge a specific /filter-later (or /fl) submission to its actual persisted user
1877
+ // message. The next input clears a failed/handled submission, so it cannot
1878
+ // accidentally flag a later ordinary prompt. Durable state uses raw entries.
1879
+ let requestedAside: { sessionId: string; text: string } | undefined;
1880
+ let asideInputSession: string | undefined;
1881
+ const clearAsideSubmission = () => { requestedAside = undefined; asideInputSession = undefined; };
1882
+ pi.on("input", (event, ctx) => {
1883
+ asideInputSession = event.source === "extension" && requestedAside?.sessionId === ctx.sessionManager.getSessionId() &&
1884
+ requestedAside.text === event.text ? requestedAside.sessionId : undefined;
1885
+ requestedAside = undefined;
1886
+ });
1887
+ pi.on("message_end", (event, ctx) => {
1888
+ if (event.message.role !== "user" || asideInputSession !== ctx.sessionManager.getSessionId()) return;
1889
+ asideInputSession = undefined;
1890
+ // Pi persists this user message immediately after message_end handlers.
1891
+ pi.appendEntry(PREFLAG_ENTRY, { timestamp: event.message.timestamp });
1892
+ });
1893
+ pi.on("session_shutdown", clearAsideSubmission);
1894
+ pi.on("session_tree", clearAsideSubmission);
1895
+
1551
1896
  // Starting/resuming a run persists the checklist AFTER the starting user
1552
1897
  // message. Existing branch history, not an in-memory flag, prevents repeats.
1553
1898
  pi.on("before_agent_start", (_event, ctx) => {
1554
1899
  const entries = ctx.sessionManager.getBranch();
1555
1900
  const compaction = latestVerbatimCompaction(entries);
1556
1901
  if (!compaction) return;
1557
- const found = entries.some((e) => e.type === "custom_message" && e.customType === REORIENT_MESSAGE &&
1558
- (e.details as { compactionId?: string } | undefined)?.compactionId === compaction.id);
1559
- if (!found) return { message: reorientationMessage(compaction.id) };
1902
+ const revisionId = latestFilterRevision(entries)?.id ?? compaction.id;
1903
+ const found = entries.some((e) => {
1904
+ if (e.type !== "custom_message" || e.customType !== REORIENT_MESSAGE) return false;
1905
+ const details = e.details as { compactionId?: string; revisionId?: string } | undefined;
1906
+ return details?.compactionId === compaction.id && (details.revisionId ?? details.compactionId) === revisionId;
1907
+ });
1908
+ if (!found) return { message: reorientationMessage(compaction.id, filteredTurns(entries).length > 0, revisionId, Object.keys(turnFidelities(entries)).length > 0) };
1560
1909
  });
1561
1910
 
1562
1911
  // Between-turn compaction and overflow continuation do not necessarily pass
@@ -1566,16 +1915,25 @@ export default function (pi: ExtensionAPI) {
1566
1915
  pi.on("session_compact", (event, ctx) => {
1567
1916
  if ((event.compactionEntry.details as { kind?: string } | undefined)?.kind !== MECH_KIND) return;
1568
1917
  if (event.willRetry || ctx.signal)
1569
- pi.sendMessage(reorientationMessage(event.compactionEntry.id), { deliverAs: "steer" });
1918
+ pi.sendMessage(reorientationMessage(event.compactionEntry.id,
1919
+ ((event.compactionEntry.details as { filteredTurnIds?: string[] }).filteredTurnIds?.length ?? 0) > 0, event.compactionEntry.id,
1920
+ Object.keys((event.compactionEntry.details as { fidelity?: TurnFidelities }).fidelity ?? {}).length > 0), { deliverAs: "steer" });
1570
1921
  });
1571
1922
 
1572
1923
  // Run after ordinary transforms and system/tool restoration. Preserve all
1573
1924
  // non-managed messages, remove old checklists even if they survive in the tail,
1574
1925
  // and keep the current one active on subsequent requests (not just the first).
1575
1926
  pi.on("context_with_system", (event, ctx) => {
1576
- const messages = projectReorientation(event.messages, ctx.sessionManager.getBranch());
1577
- if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i]))
1578
- return { messages };
1927
+ const entries = ctx.sessionManager.getBranch();
1928
+ try {
1929
+ const messages = projectReorientation(projectCheckpoint(event.messages, entries), entries);
1930
+ if (Object.keys(turnFidelities(entries)).length) checkContextBudget(messages, ctx);
1931
+ if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i])) return { messages };
1932
+ } catch (error) {
1933
+ ctx.ui.notify(`Full-fidelity context blocked: ${errMsg(error)}`, "error");
1934
+ ctx.abort(); // Hook errors alone do not cancel Pi requests. Abort explicitly.
1935
+ throw error;
1936
+ }
1579
1937
  });
1580
1938
 
1581
1939
  // Method selection never changes Pi's auto-compaction enabled setting.
@@ -1624,7 +1982,190 @@ export default function (pi: ExtensionAPI) {
1624
1982
  },
1625
1983
  });
1626
1984
 
1985
+ for (const name of ["filter-later", "fl"]) pi.registerCommand(name, {
1986
+ description: "Submit a normal user turn pre-flagged for future checkpoint filtering",
1987
+ handler: async (args, ctx) => {
1988
+ if (!args.trim()) { ctx.ui.notify(`Usage: /${name} <message>`, "error"); return; }
1989
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
1990
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before submitting an aside.", "warning"); return;
1991
+ }
1992
+ if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
1993
+ ctx.ui.notify(`/${name} requires verbatim compaction. Use /compaction-method verbatim first.`, "error"); return;
1994
+ }
1995
+ clearAsideSubmission();
1996
+ requestedAside = { sessionId: ctx.sessionManager.getSessionId(), text: args };
1997
+ try {
1998
+ pi.sendUserMessage(args);
1999
+ } catch (error) {
2000
+ clearAsideSubmission();
2001
+ throw error;
2002
+ }
2003
+ },
2004
+ });
2005
+
2006
+ pi.registerCommand("filter-auto", {
2007
+ description: "Show or set automatic application of pre-flagged asides: on|off (default off)",
2008
+ getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix))
2009
+ .map((value) => ({ value, label: value })),
2010
+ handler: async (args, ctx) => {
2011
+ const value = args.trim();
2012
+ if (value && value !== "on" && value !== "off") { ctx.ui.notify("Usage: /filter-auto [on|off]", "error"); return; }
2013
+ const previous = autoFilterEnabled(ctx.sessionManager.getBranch());
2014
+ const enabled = value ? value === "on" : previous;
2015
+ if (enabled !== previous) pi.appendEntry(AUTO_FILTER_ENTRY, { enabled });
2016
+ ctx.ui.notify(`Automatic aside filtering: ${enabled ? "on" : "off"}. Applies user pre-flags during verbatim threshold/overflow compaction; no picker or automatic relevance judgments.`, "info");
2017
+ },
2018
+ });
2019
+
2020
+ const filterTurns = {
2021
+ description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
2022
+ handler: async (args: string, ctx: ExtensionContext) => {
2023
+ if (args.trim()) { ctx.ui.notify("Usage: /filter-turns", "error"); return; }
2024
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
2025
+ ctx.ui.notify("/filter-turns requires the interactive terminal UI.", "error"); return;
2026
+ }
2027
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
2028
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
2029
+ }
2030
+ const entries = ctx.sessionManager.getBranch();
2031
+ const compaction = latestVerbatimCompaction(entries);
2032
+ if (compactionMethod(entries) !== "verbatim" || !compaction) {
2033
+ ctx.ui.notify("/filter-turns requires an existing verbatim checkpoint. Use /compact-filtered to create one.", "error"); return;
2034
+ }
2035
+ const canonical = compaction.details as { span: StoredSpan; startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[] };
2036
+ if (!canonical.span || !canonical.startupReads) {
2037
+ ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
2038
+ }
2039
+ const sessionId = ctx.sessionManager.getSessionId();
2040
+ const revisionId = latestFilterRevision(entries)?.id;
2041
+ const signal = new AbortController().signal;
2042
+ try {
2043
+ const previousExcluded = filteredTurns(entries), previousKept = keptAsideTurns(entries);
2044
+ const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
2045
+ const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
2046
+ const preflags = preflaggedTurns(entries);
2047
+ const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
2048
+ const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
2049
+ compaction.firstKeptEntryId, canonical.startupReads, proposed);
2050
+ const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
2051
+ pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
2052
+ kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
2053
+ JSON.stringify(Object.entries(modes).sort()) === JSON.stringify(Object.entries(previousFidelity).sort());
2054
+ const cap = capSettings(entries);
2055
+ const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }) => buildMechanicalSummary({
2056
+ reason: canonical.span.reason, tokensBefore: compaction.tokensBefore, branchEntries: entries,
2057
+ now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
2058
+ firstKeptEntryId: compaction.firstKeptEntryId,
2059
+ ...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
2060
+ canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, pruned, modes),
2061
+ cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
2062
+ chooseCap: preview ? async () => {
2063
+ if (cap.mode === "off") return undefined;
2064
+ const limit = capBudgetChars(cap.budget, ctx.model?.contextWindow);
2065
+ if (limit === undefined) throw new Error("Cannot preview a percentage cap without the model's context window.");
2066
+ return limit; // Warn-mode previews assume applying the current cap; never open a dialog or persist policy here.
2067
+ } : (size) => chooseCapBudget(pi, ctx, signal, "manual", size, "checkpoint update"),
2068
+ });
2069
+ const activeTools = new Set(pi.getActiveTools());
2070
+ const system: AgentMessage = { role: "system", content: ctx.getSystemPrompt(), timestamp: 0,
2071
+ toolsAdded: pi.getAllTools().filter((tool) => activeTools.has(tool.name))
2072
+ .map(({ name, description, parameters }) => ({ name, description, parameters })) };
2073
+ const tailTokens = messageTokens(retainedTailMessages(entries, compaction.firstKeptEntryId));
2074
+ const measure = (summary: string, placements: TurnSlot[], modes: TurnFidelities, pruned: Set<string>, shortening?: ContextEstimate["shortening"]): ContextEstimate => {
2075
+ const reminder: AgentMessage = { ...reorientationMessage(compaction.id, pruned.size > 0,
2076
+ revisionId ?? compaction.id, Object.keys(modes).length > 0), role: "custom", timestamp: 0 };
2077
+ const messages = checkpointContextMessages(summary, placements, modes, entries, compaction.firstKeptEntryId);
2078
+ return { ...estimateContext([system, ...messages, reminder], ctx), tailTokens,
2079
+ noticeTokens: contextNoticeTokens(messages, reminder), shortening };
2080
+ };
2081
+ const saved = latestFilterRevision(entries)?.data ?? { summary: compaction.summary,
2082
+ slots: (compaction.details as { slots?: TurnSlot[] }).slots };
2083
+ let baseline: Promise<ContextEstimate | undefined> | undefined;
2084
+ const estimateSelection = async (selection: TurnSelection): Promise<ContextEstimate> => {
2085
+ baseline ??= Promise.resolve().then(() => measure(saved.summary, saved.slots ?? [], previousFidelity, new Set(previousExcluded))).catch(() => undefined);
2086
+ const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
2087
+ applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
2088
+ const original = await baseline;
2089
+ if (unchanged(pruned, kept, modes)) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
2090
+ const presentation = { shortened: false };
2091
+ const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
2092
+ if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
2093
+ const estimated = measure(summary, placements, modes, pruned,
2094
+ presentation.shortened ? cap.mode === "warn" ? "confirmation" : "automatic" : undefined);
2095
+ return { ...estimated, delta: original ? estimated.tokens - original.tokens : undefined,
2096
+ noticeDelta: original?.noticeTokens && estimated.noticeTokens ? {
2097
+ pruning: (previousExcluded.length > 0) === (pruned.size > 0) ? 0 : estimated.noticeTokens.pruning - original.noticeTokens.pruning,
2098
+ revision: revisionId ? 0 : estimated.noticeTokens.revision - original.noticeTokens.revision,
2099
+ fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
2100
+ } : undefined };
2101
+ };
2102
+ const result = await pickFilteredTurns(ctx, choices, signal, estimateSelection);
2103
+ if (result === undefined) return;
2104
+ applyTurnSelection(choices, result, preflags, excluded, keptAsides, fidelity);
2105
+ if (unchanged(excluded, keptAsides, fidelity)) {
2106
+ ctx.ui.notify("No checkpoint turn-mode changes.", "info"); return;
2107
+ }
2108
+ const summary = await renderCheckpoint(excluded, fidelity, slots, false);
2109
+ if (summary === undefined) return;
2110
+ checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
2111
+ const current = ctx.sessionManager.getBranch();
2112
+ if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
2113
+ latestFilterRevision(current)?.id !== revisionId) {
2114
+ ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
2115
+ }
2116
+ pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
2117
+ filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
2118
+ ...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
2119
+ ctx.ui.notify("Checkpoint turn modes updated. No additional history compacted; recent messages and boundary unchanged.", "info");
2120
+ } catch (error) {
2121
+ ctx.ui.notify(`Checkpoint turn update cancelled: ${errMsg(error)}`, "error");
2122
+ }
2123
+ },
2124
+ };
2125
+
2126
+ pi.registerCommand("compact-filtered", {
2127
+ description: "Run ordinary compaction, then open checkpoint turn controls",
2128
+ handler: async (args, ctx) => {
2129
+ if (args.trim()) { ctx.ui.notify("Usage: /compact-filtered", "error"); return; }
2130
+ if (ctx.mode !== "tui" || !ctx.hasUI) {
2131
+ ctx.ui.notify("/compact-filtered requires the interactive terminal UI.", "error"); return;
2132
+ }
2133
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) {
2134
+ ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
2135
+ }
2136
+ if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
2137
+ ctx.ui.notify("/compact-filtered requires verbatim compaction. Use /compaction-method verbatim first.", "error"); return;
2138
+ }
2139
+ const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
2140
+ try {
2141
+ // compact() is callback-based. Wait for completion, not merely dispatch,
2142
+ // so the editor sees the saved checkpoint and the host is idle again.
2143
+ const result = await new Promise<{ summary: string; firstKeptEntryId: string }>((resolve, reject) => {
2144
+ ctx.compact({ onComplete: resolve, onError: reject });
2145
+ });
2146
+ const entries = ctx.sessionManager.getBranch(), current = latestVerbatimCompaction(entries);
2147
+ if (ctx.sessionManager.getSessionId() !== sessionId || !current || current.summary !== result.summary ||
2148
+ current.firstKeptEntryId !== result.firstKeptEntryId || (leafId && !entries.some((entry) => entry.id === leafId))) {
2149
+ ctx.ui.notify("Session/checkpoint changed; turn controls not opened.", "warning"); return;
2150
+ }
2151
+ } catch (error) {
2152
+ // These are Pi's current no-op outcomes, not general compaction failures.
2153
+ // Only an unchanged session with an existing checkpoint can be edited.
2154
+ const noOp = error instanceof Error && (error.message === "Already compacted" || error.message === "Nothing to compact (session too small)");
2155
+ if (!noOp || ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leafId ||
2156
+ !latestVerbatimCompaction(ctx.sessionManager.getBranch())) {
2157
+ ctx.ui.notify(`Compaction before turn editing failed: ${errMsg(error)}`, "error"); return;
2158
+ }
2159
+ }
2160
+ // The common editor rechecks idle/UI/method state. Escape here leaves the
2161
+ // already completed compaction intact; only the proposed revision is lost.
2162
+ await filterTurns.handler("", ctx);
2163
+ },
2164
+ });
2165
+ pi.registerCommand("filter-turns", filterTurns);
2166
+
1627
2167
  pi.on("session_start", (_event, ctx) => {
2168
+ clearAsideSubmission();
1628
2169
  const entries = ctx.sessionManager.getBranch();
1629
2170
  if (compactionMethod(entries) === "verbatim" && collectBaseAndSpans(entries).base?.kind === "model-summary") {
1630
2171
  ctx.ui.notify(MIXED_CONTEXT_WARNING, "warning");
@@ -1658,10 +2199,40 @@ export default function (pi: ExtensionAPI) {
1658
2199
  // --------------------------------------------------------------------------
1659
2200
  pi.on("session_before_compact", async (event, ctx) => {
1660
2201
  const { preparation, branchEntries, reason, signal } = event;
2202
+ const automaticFiltering = reason !== "manual" && autoFilterEnabled(branchEntries);
1661
2203
  if (!preparation) return;
1662
2204
  if (signal?.aborted) return;
1663
2205
  if (preparation.messagesToSummarize.length === 0 && preparation.turnPrefixMessages.length === 0) return;
1664
2206
  if (compactionMethod(ctx.sessionManager.getBranch()) === "summary") {
2207
+ const revision = latestFilterRevision(branchEntries);
2208
+ if (revision || Object.keys(turnFidelities(branchEntries)).length) {
2209
+ // Pi prepares from the saved compaction, not our request projection.
2210
+ // Summary mode must consume the revised checkpoint too, rather than
2211
+ // resurrecting filtered text or dropping standalone restorations.
2212
+ const active = latestVerbatimCompaction(branchEntries)!;
2213
+ preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
2214
+ .map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
2215
+ const canonical = latestVerbatimCompaction(branchEntries)!.details as {
2216
+ startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[];
2217
+ };
2218
+ const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
2219
+ canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
2220
+ const ops = preparation.fileOps;
2221
+ ops.read = new Set(visible.readFiles);
2222
+ ops.edited = new Set(visible.modifiedFiles);
2223
+ ops.written = new Set();
2224
+ for (const message of [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages]) {
2225
+ const calls = message.role === "assistant" ? message.content.filter((block) => block.type === "toolCall")
2226
+ : message.role === "toolResult" ? message.nestedCalls?.calls ?? [] : [];
2227
+ for (const call of calls) {
2228
+ const file = (call.arguments as { path?: unknown } | undefined)?.path;
2229
+ if (typeof file !== "string" || !file) continue;
2230
+ if (call.name === "read") ops.read.add(file);
2231
+ else if (call.name === "write") ops.written.add(file);
2232
+ else if (call.name === "edit") ops.edited.add(file);
2233
+ }
2234
+ }
2235
+ }
1665
2236
  return; // No override: Pi runs its normal model-generated compaction.
1666
2237
  }
1667
2238
 
@@ -1686,8 +2257,8 @@ export default function (pi: ExtensionAPI) {
1686
2257
  }
1687
2258
 
1688
2259
  const modified = new Set([...(fileOps?.edited ?? []), ...(fileOps?.written ?? [])]);
1689
- const modifiedFiles = [...modified].sort();
1690
- const readFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
2260
+ const canonicalModifiedFiles = [...modified].sort();
2261
+ const canonicalReadFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
1691
2262
 
1692
2263
  // 2) The new span. Pi's preparation span is [previous cut, current cut)
1693
2264
  // — it includes the previous compaction's retained tail (verified
@@ -1707,28 +2278,45 @@ export default function (pi: ExtensionAPI) {
1707
2278
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1708
2279
  const spanFrom = toIso(msgTs(allMessages[0]));
1709
2280
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1710
- const spanLines = summarizeMessages(allMessages, ctx.cwd);
2281
+ const span = summarizeMessages(allMessages, ctx.cwd, preparedTurnOwners(branchEntries, allMessages));
2282
+ const spanLines = span.lines;
1711
2283
 
1712
2284
  // 3) Freeze startup references after the second user prompt, then carry
1713
2285
  // their original outputs forward outside the trimmable conversation spans.
1714
- const retained = startupReads(branchEntries, ctx);
2286
+ const canonicalRetained = startupReads(branchEntries, ctx);
2287
+ const excluded = new Set(filteredTurns(branchEntries));
2288
+ const keptAsides = new Set(keptAsideTurns(branchEntries));
2289
+ const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
2290
+ if (automaticFiltering) {
2291
+ const preflags = preflaggedTurns(branchEntries);
2292
+ const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
2293
+ const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
2294
+ excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
2295
+ for (const turn of choices)
2296
+ if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
2297
+ }
2298
+ const filteredTurnIds = [...excluded];
2299
+ const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
2300
+ canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded, fidelity);
1715
2301
  const summary = await buildMechanicalSummary({
1716
2302
  reason, // pi's raw reason, passed through unchanged
1717
2303
  tokensBefore: preparation.tokensBefore,
1718
2304
  branchEntries,
1719
2305
  now: nowIso,
1720
2306
  spanLines,
2307
+ spanTools: span.tools,
2308
+ spanTurnIds: span.turnIds,
2309
+ filteredTurnIds, fidelity, slots,
1721
2310
  spanFrom,
1722
2311
  spanTo,
1723
2312
  firstKeptEntryId: preparation.firstKeptEntryId,
1724
- readFiles,
1725
- modifiedFiles,
1726
- startupReads: retained,
2313
+ ...evidence,
1727
2314
  cwd: ctx.cwd,
1728
2315
  notify: (m) => ctx.ui?.notify?.(m, "warning"),
1729
2316
  chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
1730
2317
  });
1731
2318
  if (summary === undefined || signal?.aborted) return { cancel: true };
2319
+ checkCheckpointBudget(summary, slots, fidelity, branchEntries, preparation.firstKeptEntryId, ctx);
1732
2320
 
1733
2321
  ctx.ui?.notify?.(
1734
2322
  `transparent-compact: ~${preparation.tokensBefore.toLocaleString()} tokens -> verbatim checkpoint; full transcript kept in the session`,
@@ -1742,18 +2330,26 @@ export default function (pi: ExtensionAPI) {
1742
2330
  tokensBefore: preparation.tokensBefore,
1743
2331
  details: {
1744
2332
  kind: MECH_KIND,
1745
- readFiles,
1746
- modifiedFiles,
1747
- startupReads: retained,
2333
+ // Canonical metadata stays reversible; only the rendered checkpoint
2334
+ // masks file paths/startup reads owned by excluded turns.
2335
+ readFiles: canonicalReadFiles,
2336
+ modifiedFiles: canonicalModifiedFiles,
2337
+ startupReads: canonicalRetained,
2338
+ ...(filteredTurnIds.length ? { filteredTurnIds } : {}),
2339
+ ...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
2340
+ ...(Object.keys(fidelity).length ? { fidelity, slots } : {}),
1748
2341
  // Only this compaction's own span (un-capped lines). Earlier spans
1749
2342
  // are re-rendered from the earlier entries' details — no nesting.
1750
- span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
2343
+ span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
2344
+ lines: spanLines, turnIds: span.turnIds, ...(span.tools ? { tools: span.tools } : {}) },
1751
2345
  },
1752
2346
  },
1753
2347
  };
1754
2348
  } catch (err) {
1755
- ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); falling back to Pi's summary compaction`, "error");
1756
- return;
2349
+ // Never replace a filtered checkpoint with an unfiltered model summary.
2350
+ const preserveFiltering = automaticFiltering || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
2351
+ ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
2352
+ return preserveFiltering ? { cancel: true } : undefined;
1757
2353
  }
1758
2354
  });
1759
2355
 
@@ -1766,7 +2362,7 @@ export default function (pi: ExtensionAPI) {
1766
2362
  label: "Context lookup",
1767
2363
  executionMode: "sequential",
1768
2364
  description:
1769
- `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. ${RECOVERY_TRIGGERS} A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} If findings are incomplete, use context_list_entries, context_grep, or context_show_entry, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE}`,
2365
+ `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. Ask \`context_lookup\` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence. A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} If findings are incomplete, use context_list_entries, context_grep, or context_show_entry, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE}`,
1770
2366
  promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
1771
2367
  parameters: Type.Object({
1772
2368
  question: Type.String({ description: "A specific question about earlier in this conversation: an output, source of a finding, reason for a decision, or evidence behind notes that conflict with new observations." }),