@foliox/transparent-compact-pi 0.8.8 → 0.9.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.
@@ -11,11 +11,11 @@
11
11
  * MECH_COMPACT_MAX_SUMMARY_CHARS initial character budget override (takes precedence over percent)
12
12
  * MECH_COMPACT_MAX_SUMMARY_PERCENT initial percentage of model context (default 25; >0, <=100)
13
13
  * MECH_COMPACT_LOOKUP_MODEL "provider/modelId" for the lookup subagent
14
- * MECH_COMPACT_LOOKUP_TURNS max substantive search turns (default 10).
14
+ * MECH_COMPACT_LOOKUP_TURNS max substantive search turns (default 25).
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,8 @@ 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 { SpanContent, ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
36
38
 
37
39
  // ============================================================================
38
40
  // Configuration
@@ -72,17 +74,17 @@ function percentFromEnv(name: string, fallback: number): number {
72
74
  function lookupMaxCallsFromEnv(): number {
73
75
  const raw = process.env.MECH_COMPACT_LOOKUP_MAX_CALLS?.trim();
74
76
  const n = raw && /^\d+$/.test(raw) ? Number(raw) : NaN;
75
- return Number.isSafeInteger(n) && n >= 0 ? n : 1;
77
+ return Number.isSafeInteger(n) && n >= 0 ? n : 3;
76
78
  }
77
79
 
78
80
  const cfg = {
79
81
  defaultCapBudget: (process.env.MECH_COMPACT_MAX_SUMMARY_CHARS
80
82
  ? { unit: "chars", value: intFromEnv("MECH_COMPACT_MAX_SUMMARY_CHARS", 80_000) }
81
83
  : { unit: "percent", value: percentFromEnv("MECH_COMPACT_MAX_SUMMARY_PERCENT", 25) }) as CapBudget,
82
- lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 10),
84
+ lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 25),
83
85
  lookupMaxCalls: lookupMaxCallsFromEnv(),
84
86
  lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
85
- argSnippetChars: 160,
87
+ argSnippetChars: NORMAL_PREVIEW_CHARS,
86
88
  listMaxChars: 12_000,
87
89
  grepMaxChars: 12_000,
88
90
  showEntryMaxChars: 24_000,
@@ -294,6 +296,28 @@ interface TranscriptIndexSection {
294
296
  startLine: number;
295
297
  }
296
298
 
299
+ // Pair only selected messages, by call id AND tool name. Ambiguous concurrent
300
+ // ids stay unknown; sequential reuse is allowed after consuming a result.
301
+ function pairedToolResults(messages: AgentMessage[]): Map<object, Record<string, any>> {
302
+ const results = new Map<object, Record<string, any>>();
303
+ const pending = new Map<string, { block: object; name: string } | null>();
304
+ for (const message of messages) {
305
+ const m = message as unknown as Record<string, any>;
306
+ if (m.role === "assistant") {
307
+ for (const block of m.content ?? []) {
308
+ if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
309
+ pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
310
+ }
311
+ } else if (m.role === "toolResult") {
312
+ const call = pending.get(m.toolCallId);
313
+ if (!call || call.name !== m.toolName) continue;
314
+ results.set(call.block, m);
315
+ pending.delete(m.toolCallId);
316
+ }
317
+ }
318
+ return results;
319
+ }
320
+
297
321
  interface TranscriptIndexEntry {
298
322
  id: string;
299
323
  type: string;
@@ -303,6 +327,8 @@ interface TranscriptIndexEntry {
303
327
  /** 1-based line number of the last line of the block (inclusive) */
304
328
  endLine: number;
305
329
  sections?: TranscriptIndexSection[];
330
+ /** Raw, unambiguously matched call/result entries; never parsed from text. */
331
+ relatedIds?: string[];
306
332
  }
307
333
 
308
334
  function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index: TranscriptIndexEntry[] } {
@@ -414,6 +440,25 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
414
440
  if (b.sections && b.sections.length > 0) e.sections = b.sections.map((s) => ({ kind: s.kind, startLine: b.hrIdx + s.rel + 3 }));
415
441
  return e;
416
442
  });
443
+ const byMessage = new Map<object, string>();
444
+ const byCall = new Map<object, string>();
445
+ const messages: AgentMessage[] = [];
446
+ for (const entry of entries) {
447
+ if (entry.type !== "message") continue;
448
+ messages.push(entry.message);
449
+ byMessage.set(entry.message, entry.id);
450
+ if (entry.message.role === "assistant")
451
+ for (const block of entry.message.content ?? [])
452
+ if (block.type === "toolCall") byCall.set(block, entry.id);
453
+ }
454
+ const byId = new Map(index.map((entry) => [entry.id, entry]));
455
+ for (const [call, result] of pairedToolResults(messages)) {
456
+ const callId = byCall.get(call), resultId = byMessage.get(result);
457
+ if (!callId || !resultId) continue;
458
+ const callEntry = byId.get(callId)!, resultEntry = byId.get(resultId)!;
459
+ (callEntry.relatedIds ??= []).push(resultId);
460
+ resultEntry.relatedIds = [callId];
461
+ }
417
462
  return { lines, index };
418
463
  }
419
464
 
@@ -444,47 +489,128 @@ function argumentSnippet(value: unknown): string {
444
489
  return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
445
490
  }
446
491
 
447
- function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
492
+ function toolSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): ToolStub {
493
+ const a = args ?? {};
494
+ if (!["read", "write", "edit", "bash"].includes(name))
495
+ return { prefix: `${name}(${Object.entries(a).map(([k, v]) => `${k}=${argumentSnippet(v)}`).join(", ")})`, suffix: "" };
448
496
  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.
497
+ let command: ToolStub["command"];
498
+ const fileTool = ["read", "write", "edit"].includes(name) && typeof a.path === "string";
499
+ let base = fileTool ? `${name} ${JSON.stringify(checkpointPath(a.path as string, cwd))}` : name;
500
+ const range = name === "read" && fileTool &&
501
+ (a.offset === undefined || (Number.isSafeInteger(a.offset) && (a.offset as number) > 0)) &&
502
+ (a.limit === undefined || (Number.isSafeInteger(a.limit) && (a.limit as number) > 0));
503
+ if (range && (a.offset !== undefined || a.limit !== undefined)) {
504
+ const start = (a.offset as number | undefined) ?? 1;
505
+ const end = a.limit === undefined ? "" : start + (a.limit as number) - 1;
506
+ base += `:${start}-${end}`; // Requested range, not a claim about returned lines.
507
+ }
508
+ for (const [k, v] of Object.entries(a)) {
509
+ if (fileTool && k === "path") continue;
510
+ if (range && (k === "offset" || k === "limit")) continue;
511
+ if (name === "bash" && k === "timeout") continue;
512
+ if (name === "bash" && k === "command" && typeof v === "string")
513
+ command = commandPreview(JSON.stringify(checkpointCommand(v, cwd)));
453
514
  else if (name === "write" && k === "content" && typeof v === "string")
454
- s = `<${v.length} chars>`;
515
+ parts.push(`(${v.length} chars)`);
455
516
  else if (name === "edit" && k === "edits" && Array.isArray(v))
456
- s = String(v.length);
517
+ parts.push(`×${v.length}`);
457
518
  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}`);
519
+ parts.push(`${k}=<${v.length} chars>`);
520
+ else parts.push(`${k}=${argumentSnippet(v)}`);
462
521
  }
463
- return `${name}(${parts.join(", ")})`;
522
+ return command ? { prefix: `${base} `, command, suffix: parts.length ? ` ${parts.join(" ")}` : "" }
523
+ : { prefix: [base, ...parts].join(" "), suffix: "" };
464
524
  }
465
525
 
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
- }
526
+ function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
527
+ return renderToolStub(toolSignature(name, args, cwd));
528
+ }
529
+
530
+ // Conservative lexical categories for selected output observations. These do
531
+ // not parse shell syntax or establish whether a command succeeded.
532
+ function commandHints(command: string): { tests: boolean; network: boolean; historical: boolean } {
533
+ const core = command.replace(/^\s*cd\s+(?:"[^"\n]*"|'[^'\n]*'|[^\s;&|]+)\s*&&\s*/, "").trimStart();
534
+ 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);
535
+ const network = /^(?:curl|wget)\b/.test(core);
536
+ const readOnly = /^(?:cat|sed|awk|rg|grep|head|tail|find|ls|man|git)\b/.test(core);
537
+ const historical = !readOnly && (network || /^(?:timeout\s+\S+\s+)?tmux\b/.test(core) ||
538
+ /^(?:\S*\/)?(?:python[\d.]*|node|ruby|perl)\b[^\n]*(?:\s-[ce]\b|\s-\s*<<)/.test(core) ||
539
+ /^(?:uv run )?(?:\S*\/)?(?:python[\d.]*|node)\b/.test(core) ||
540
+ /^(?:time|hyperfine)\b|\b(?:bench(?:mark)?|timeit)\b/.test(core));
541
+ return { tests, network, historical };
542
+ }
543
+
544
+ function observationQuote(text: string): string {
545
+ if (JSON.stringify(text).length <= cfg.argSnippetChars) return JSON.stringify(text);
546
+ // Unlike a generic argument prefix, keep output quotations closed and escaped
547
+ // even when the source contains control characters or ends at a surrogate.
548
+ let end = Math.min(text.length, cfg.argSnippetChars);
549
+ while (JSON.stringify(text.slice(0, end) + "…").length > cfg.argSnippetChars) end--;
550
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
551
+ return JSON.stringify(text.slice(0, end) + "…");
552
+ }
553
+
554
+ function bashOutputLabel(command: string, result: Record<string, any>): string {
555
+ const content = result.content;
556
+ // Do not treat an image, structured-only result, or truncation notice as a
557
+ // tiny complete text observation. Summaries below quote selected text only.
558
+ const textOnly = typeof content === "string" || (Array.isArray(content) && content.length > 0 && content.every((b) => b?.type === "text" && typeof b.text === "string"));
559
+ if (!textOnly) return "";
560
+ const raw = textOf(content).text;
561
+ const structuredExit = result.structuredContent?.exit_code;
562
+ const hasStructuredExit = Number.isSafeInteger(structuredExit);
563
+ const suffix = /(?:^|\n)Command exited with code (-?\d+)\s*$/.exec(raw);
564
+ // Successful reads can print a fixture containing the wrapper's exact text.
565
+ // Prefer explicit metadata; trust a legacy nonzero footer only on tool error.
566
+ const exit = suffix && (hasStructuredExit ? Number(suffix[1]) === structuredExit : result.isError === true) ? suffix : undefined;
567
+ const bodyText = exit ? raw.slice(0, exit.index) : raw;
568
+ const body = bodyText.trim();
569
+ const partial = result.details?.truncation?.truncated === true || /\[(?:Output truncated|Showing last |Showing lines )/i.test(body);
570
+ const labels: string[] = [];
571
+ const reportedExit = hasStructuredExit ? structuredExit : exit ? Number(exit[1]) : undefined;
572
+ const exitCode = Number.isSafeInteger(reportedExit) ? reportedExit : undefined;
573
+ if (exitCode !== undefined && exitCode !== 0) labels.push(`exit ${exitCode}`); // Reported shell status, NOT pipeline/test status.
574
+ if (!partial && (bodyText === "" || body === "(no output)")) return [...labels, "no output"].join("; ");
575
+ const hints = commandHints(command);
576
+ const lines = body.replace(/\x1b\[[0-9;]*m/g, "").split("\n");
577
+ let observed: string[] = [];
578
+ if (hints.tests) {
579
+ observed = lines.filter((line) =>
580
+ /^=+ .*\b\d+ (?:passed|failed|errors?|skipped|xfailed)\b.*=+$/.test(line.trim()) ||
581
+ /^(?:\d+ (?:passed|failed|errors?|skipped|xfailed|deselected|warnings?)(?:, )?)+ in [\d.]+s$/.test(line.trim()) ||
582
+ /^(?:ℹ|#) (?:pass|fail) \d+$/.test(line.trim()) ||
583
+ /^BUILD (?:SUCCESSFUL|FAILED)\b/.test(line.trim()) ||
584
+ /^(?:PASS|FAIL): \d+\/\d+$/.test(line.trim())).slice(-3);
585
+ }
586
+ if (hints.network) {
587
+ 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]);
588
+ if (codes.length) labels.push(`output: http ${codes.slice(0, 4).join(",")}${codes.length > 4 ? ",…" : ""}`);
486
589
  }
590
+ // Only recognized execution commands get error-text scanning. In particular,
591
+ // never extract test/error labels from file reads, searches, or git views.
592
+ if (!observed.length && (hints.tests || hints.historical)) {
593
+ const errors = lines.filter((line) => line.trim()).slice(-6).filter((line) =>
594
+ /^(?:\s*\w*(?:Error|Exception):|Traceback \(most recent call last\):|error(?:\[\w+\])?:|fatal:)|command not found/.test(line));
595
+ observed = errors.slice(-1);
596
+ }
597
+ if (observed.length) labels.push(`output: ${observed.map((line) => observationQuote(line.trim())).join(" / ")}`);
598
+ else if (!labels.some((label) => label.startsWith("output:")) && hints.historical && !partial &&
599
+ bodyText.length <= 100 && JSON.stringify(bodyText).length <= cfg.argSnippetChars)
600
+ labels.push(`output: ${JSON.stringify(bodyText)}`);
601
+ // A commit hash is useful provenance, but only extract the git-generated
602
+ // bracketed form, not arbitrary lines that merely start with hex digits.
603
+ if (/^(?:git\b|.*&&\s*git\b)/.test(command) && /\bgit commit\b/.test(command)) {
604
+ const hash = /^\[[^\]\n]+ ([0-9a-f]{7,40})\]/m.exec(body)?.[1];
605
+ if (hash) labels.push(`commit ${hash}`);
606
+ }
607
+ return labels.join("; ");
608
+ }
609
+
610
+ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
611
+ const results = pairedToolResults(messages);
487
612
  const lines: string[] = [];
613
+ const tools: ToolLines = { version: 2, lines: [] };
488
614
  for (const msg of messages) {
489
615
  const m = msg as unknown as Record<string, any>;
490
616
  switch (msg.role) {
@@ -495,15 +621,26 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
495
621
  }
496
622
  case "assistant": {
497
623
  let prose = "";
498
- const calls: string[] = [];
624
+ const calls: ToolStub[] = [];
499
625
  for (const block of m.content ?? []) {
500
626
  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"}]`);
627
+ else if (block.type === "toolCall") {
628
+ const name = String(block.name), args = block.arguments ?? {};
629
+ const result = results.get(block);
630
+ const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
631
+ const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
632
+ const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
633
+ const stub = toolSignature(name, args, cwd);
634
+ stub.suffix += status + (label ? ` → ${label}` : "");
635
+ calls.push(stub);
636
+ }
503
637
  // thinking blocks: removed by design (kept in the session)
504
638
  }
505
639
  if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
506
- if (calls.length > 0) lines.push(`[Assistant tool calls]: ${calls.join("; ")}`);
640
+ if (calls.length > 0) {
641
+ tools.lines.push({ index: lines.length, calls, mergeable: !prose.trim() });
642
+ lines.push(renderToolLine(calls));
643
+ }
507
644
  break;
508
645
  }
509
646
  case "toolResult":
@@ -526,7 +663,7 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): string[] {
526
663
  break;
527
664
  }
528
665
  }
529
- return lines;
666
+ return { lines, ...(tools.lines.length ? { tools } : {}) };
530
667
  }
531
668
 
532
669
  // Startup reference retention is a lexical heuristic, not an interpretation of
@@ -640,7 +777,7 @@ function renderStartupReads(state: StartupReads, entries: SessionEntry[], firstK
640
777
  const retained = state.reads.filter((r) => !tail.has(r.entryId));
641
778
  if (retained.length === 0) return "";
642
779
  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.",
780
+ "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
781
  ...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
782
  ${r.text.join("\n")}
646
783
  </retained-read>`),
@@ -770,15 +907,17 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
770
907
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
771
908
  * (the base is opaque; the session holds the raw history).
772
909
  */
910
+ type StoredSpan = SpanContent & { at: string; reason: string; from?: string; to?: string };
911
+
773
912
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
774
913
  base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
775
- spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[];
914
+ spans: StoredSpan[];
776
915
  } {
777
916
  const spanDetails = (e: SessionEntry) => {
778
917
  if (e.type !== "compaction") return undefined;
779
918
  const d = (e as { details?: Record<string, any> }).details;
780
919
  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[] };
920
+ return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[]; tools?: ToolLines };
782
921
  };
783
922
  let baseIdx = -1;
784
923
  for (let i = branchEntries.length - 1; i >= 0; i--) {
@@ -798,7 +937,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
798
937
  summary: (baseEntry as { summary?: string }).summary ?? "",
799
938
  }
800
939
  : null;
801
- const spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[] = [];
940
+ const spans: StoredSpan[] = [];
802
941
  for (let i = Math.max(baseIdx + 1, 0); i < branchEntries.length; i++) {
803
942
  const sd = spanDetails(branchEntries[i]);
804
943
  if (sd)
@@ -810,50 +949,13 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
810
949
  from: typeof sd.from === "string" && sd.from !== "" ? sd.from : undefined,
811
950
  to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
812
951
  lines: sd.lines,
952
+ tools: sd.tools,
813
953
  });
814
954
  }
815
955
  return { base, spans };
816
956
  }
817
957
 
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
- };
833
-
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);
839
- }
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 };
848
- }
849
- // 3) drop oldest remaining lines until under budget (terminates: removes one per iteration)
850
- while (over() && items.length > 0) remove(0);
851
-
852
- return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
853
- }
854
-
855
958
  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
959
  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
960
  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
961
  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.";
@@ -867,7 +969,7 @@ const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier
867
969
 
868
970
  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}`;
869
971
 
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.";
972
+ 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
973
 
872
974
  const REORIENT_MESSAGE = "transparent-compact:reorient";
873
975
  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.`;
@@ -921,6 +1023,7 @@ async function buildMechanicalSummary(opts: {
921
1023
  branchEntries: SessionEntry[];
922
1024
  now: string;
923
1025
  spanLines: string[]; // this compaction's own span, un-capped
1026
+ spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
924
1027
  spanFrom?: string; // ISO timestamp of the first summarised message
925
1028
  spanTo?: string; // ISO timestamp of the last summarised message
926
1029
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
@@ -932,7 +1035,8 @@ async function buildMechanicalSummary(opts: {
932
1035
  chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
933
1036
  }): Promise<string | undefined> {
934
1037
  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 }];
1038
+ const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1039
+ lines: opts.spanLines, tools: opts.spanTools }];
936
1040
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
937
1041
 
938
1042
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -943,7 +1047,7 @@ async function buildMechanicalSummary(opts: {
943
1047
  let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
944
1048
  if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
945
1049
  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,
1050
+ (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
1051
  0,
948
1052
  );
949
1053
  // Closing line: where the verbatim (uncompacted) tail begins. Spans end at
@@ -964,16 +1068,17 @@ async function buildMechanicalSummary(opts: {
964
1068
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
965
1069
  if (maxChars !== undefined && retainedReads.length > maxChars)
966
1070
  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));
1071
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
968
1072
 
969
1073
  const blocks: string[] = [];
970
1074
  if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
971
- capped.forEach((lines, i) => {
1075
+ capped.lines.forEach((lines, i) => {
972
1076
  const s = allSpans[i];
973
- const trimmed = lines.length !== s.lines.length || lines.some((line, j) => line !== s.lines[j]);
1077
+ const trimmed = capped.trimmed[i];
974
1078
  const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
1079
+ const attributes = (capped.tightened[i] ? TIGHTENED_ATTR : "") + (trimmed ? SPAN_TRIMMED_ATTR : "");
975
1080
  blocks.push([
976
- trimmed ? `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>` : open,
1081
+ attributes ? `${open.slice(0, -1)}${attributes}>` : open,
977
1082
  ...(trimmed ? [SPAN_TRIMMED_NOTE] : []),
978
1083
  ...lines,
979
1084
  SPAN_CLOSE,
@@ -989,9 +1094,10 @@ async function buildMechanicalSummary(opts: {
989
1094
  opts.notify(MIXED_CONTEXT_WARNING);
990
1095
  }
991
1096
  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.");
1097
+ 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 →.");
1098
+ 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.");
1099
+ parts.push("- Under size pressure, `tools-tightened` marks 120/80-character previews or grouped tool-only lines. Conversation prose and tool calls are retained unless `trimmed` is also marked. Tightening stops as soon as the budget fits; outcome observations and identifying file paths are not shortened by these stages.");
1100
+ 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
1101
  parts.push(
996
1102
  "- 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
1103
  );
@@ -1189,16 +1295,22 @@ function grepTranscript(transcripts: Transcript[], opts: GrepOptions, onContinua
1189
1295
  return out.join("\n\n") + notice;
1190
1296
  }
1191
1297
 
1192
- function showEntry(transcripts: Transcript[], opts: { id: string; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1298
+ function showEntry(transcripts: Transcript[], opts: { id: string; includeRelated?: boolean; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
1193
1299
  const targets = opts.file ? transcripts.filter((d) => d.name === opts.file) : transcripts;
1194
1300
  const out: string[] = [];
1195
1301
  const headers: string[] = [];
1196
1302
  for (const d of targets) {
1197
1303
  const e = d.index.find((x) => x.id === opts.id);
1198
1304
  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]}`);
1305
+ const ids = new Set([e.id, ...(opts.includeRelated === true ? e.relatedIds ?? [] : [])]);
1306
+ // Chronological, one-hop expansion: a result includes its originating
1307
+ // assistant, not all sibling outputs. An assistant includes its results.
1308
+ for (const entry of d.index) {
1309
+ if (!ids.has(entry.id)) continue;
1310
+ const block = d.lines.slice(entry.startLine - 2, entry.endLine);
1311
+ out.push(`### ${d.name}\n${block.join("\n")}`);
1312
+ headers.push(`${d.name}: ${d.lines[entry.startLine - 1]}`);
1313
+ }
1202
1314
  }
1203
1315
  return out.length ? pageText(out.join("\n\n"), {
1204
1316
  offset: opts.offset, maxChars: cfg.showEntryMaxChars,
@@ -1222,7 +1334,8 @@ const GREP_FIELDS = {
1222
1334
  throughEntry: THROUGH_ENTRY_FIELD,
1223
1335
  };
1224
1336
  const SHOW_FIELDS = {
1225
- id: Type.String({ description: "Entry id" }),
1337
+ id: Type.String({ description: "ENTRY id" }),
1338
+ includeRelated: Type.Optional(Type.Boolean({ description: "Include unambiguously matched tool call/result entries (default false). Keep unchanged when paging." })),
1226
1339
  maxLines: Type.Optional(Type.Integer({ minimum: 1, description: "Max lines per page (default 400); character limit also applies" })),
1227
1340
  offset: OFFSET_FIELD,
1228
1341
  };
@@ -1240,14 +1353,15 @@ function lookupPartialFindings(text: string, marker: string): string {
1240
1353
 
1241
1354
  const LOOKUP_WRITEUP_PROMPT =
1242
1355
  "Search is finished; no further tool calls are allowed. Report what you found so far: the facts you confirmed (with ENTRY ids), " +
1243
- "what you couldn't find, and where you'd look next.";
1356
+ "what you could not locate in the material searched, and where you'd look next. " +
1357
+ "Budget exhaustion or an incomplete search does not establish absence from the transcript.";
1244
1358
 
1245
1359
  const LOOKUP_SYSTEM_PROMPT = `You are a context-lookup subagent for a coding agent whose main context was compacted by verbatim compaction. The full pre-compaction transcript — including assistant thinking blocks and complete tool outputs that were REMOVED from the main context — is in the transcript files named in the request.
1246
1360
 
1247
1361
  You have three tools:
1248
1362
  - list_entries: paginated overview of entries (id, role, timestamp, preview)
1249
1363
  - grep: paginated transcript search; matches come with surrounding lines and authoritative ENTRY attribution
1250
- - show_entry: retrieve an entry by id in bounded pages
1364
+ - show_entry: retrieve an entry by id in bounded pages; includeRelated=true also shows its matched tool call/result
1251
1365
 
1252
1366
  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.
1253
1367
 
@@ -1257,7 +1371,7 @@ Final answer rules (your final message is the ONLY text the main agent sees):
1257
1371
  - Return only the important findings. Do not narrate your search process.
1258
1372
  - Quote exact error messages, paths, values, and code verbatim where they matter.
1259
1373
  - Cite the ENTRY id (and file) for each finding so the main agent can verify.
1260
- - If the transcript does not contain the answer, say exactly what is missing.
1374
+ - A failed or incomplete search does not establish absence from the transcript. Distinguish "not found in the material searched" from "absent from the transcript". If the search was incomplete or budget-limited, state what you did not reach or confirm; do not claim the answer was never recorded or that the session ended before it occurred.
1261
1375
 
1262
1376
  Provenance rules — label each finding with its source type:
1263
1377
  - "user instruction" — what the user asked, pasted, or confirmed
@@ -1288,6 +1402,7 @@ function lookupPageKey(name: string, args: Record<string, any>): string | undefi
1288
1402
  break;
1289
1403
  case "show_entry":
1290
1404
  fields = [typeof args.id === "string" ? args.id : undefined, string("file"),
1405
+ typeof (args.includeRelated ?? false) === "boolean" ? (args.includeRelated ?? false) : undefined,
1291
1406
  number("maxLines", 400, 1), number("offset", 0)];
1292
1407
  break;
1293
1408
  default:
@@ -1318,7 +1433,7 @@ async function runLookupSubagent(opts: {
1318
1433
  },
1319
1434
  {
1320
1435
  name: "show_entry",
1321
- 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.",
1436
+ 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.",
1322
1437
  parameters: Type.Object({ ...SHOW_FIELDS, file: FILE_FIELD }),
1323
1438
  },
1324
1439
  ];
@@ -1389,7 +1504,10 @@ async function runLookupSubagent(opts: {
1389
1504
  if (text) lastText = text;
1390
1505
 
1391
1506
  if (toolCalls.length === 0) {
1392
- return truncateHead(text || "(subagent returned no answer)", cfg.lookupAnswerMaxChars);
1507
+ const answer = text || "(subagent returned no answer)";
1508
+ return pagingOnlyNotified
1509
+ ? lookupPartialFindings(answer, `[subagent reached the ${searchLimit}; findings may be incomplete]`)
1510
+ : truncateHead(answer, cfg.lookupAnswerMaxChars);
1393
1511
  }
1394
1512
 
1395
1513
  // Check the whole batch against cursors issued BEFORE this response.
@@ -1520,7 +1638,7 @@ function registerDirectTools(pi: ExtensionAPI): void {
1520
1638
  pi.registerTool({
1521
1639
  name: "context_grep",
1522
1640
  label: "Context: grep",
1523
- description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and authoritative entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1641
+ 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.",
1524
1642
  promptSnippet: "Fallback: search this conversation's evidence hidden by compaction",
1525
1643
  parameters: Type.Object(GREP_FIELDS),
1526
1644
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
@@ -1530,8 +1648,8 @@ function registerDirectTools(pi: ExtensionAPI): void {
1530
1648
  pi.registerTool({
1531
1649
  name: "context_show_entry",
1532
1650
  label: "Context: show entry",
1533
- 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.",
1534
- promptSnippet: "Fallback: retrieve this conversation's entries for post-compaction recovery",
1651
+ 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.",
1652
+ promptSnippet: "Recover a specific detail hidden by compaction at a known ENTRY id in this conversation.",
1535
1653
  parameters: Type.Object(SHOW_FIELDS),
1536
1654
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1537
1655
  return run(ctx, (t) => showEntry(t, params));
@@ -1703,7 +1821,8 @@ export default function (pi: ExtensionAPI) {
1703
1821
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1704
1822
  const spanFrom = toIso(msgTs(allMessages[0]));
1705
1823
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1706
- const spanLines = summarizeMessages(allMessages, ctx.cwd);
1824
+ const span = summarizeMessages(allMessages, ctx.cwd);
1825
+ const spanLines = span.lines;
1707
1826
 
1708
1827
  // 3) Freeze startup references after the second user prompt, then carry
1709
1828
  // their original outputs forward outside the trimmable conversation spans.
@@ -1714,6 +1833,7 @@ export default function (pi: ExtensionAPI) {
1714
1833
  branchEntries,
1715
1834
  now: nowIso,
1716
1835
  spanLines,
1836
+ spanTools: span.tools,
1717
1837
  spanFrom,
1718
1838
  spanTo,
1719
1839
  firstKeptEntryId: preparation.firstKeptEntryId,
@@ -1743,7 +1863,8 @@ export default function (pi: ExtensionAPI) {
1743
1863
  startupReads: retained,
1744
1864
  // Only this compaction's own span (un-capped lines). Earlier spans
1745
1865
  // are re-rendered from the earlier entries' details — no nesting.
1746
- span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
1866
+ span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
1867
+ lines: spanLines, ...(span.tools ? { tools: span.tools } : {}) },
1747
1868
  },
1748
1869
  },
1749
1870
  };
@@ -1762,7 +1883,7 @@ export default function (pi: ExtensionAPI) {
1762
1883
  label: "Context lookup",
1763
1884
  executionMode: "sequential",
1764
1885
  description:
1765
- `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. ${RECOVERY_TRIGGERS} A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} If findings are incomplete, use context_list_entries, context_grep, or context_show_entry, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE}`,
1886
+ `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}`,
1766
1887
  promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
1767
1888
  parameters: Type.Object({
1768
1889
  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." }),