@foliox/transparent-compact-pi 0.12.0 → 0.13.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0
4
+
5
+ - Add `context_expand` to recover the original call and matched result behind a
6
+ quoted visible tool stub, or the full text of a size-truncated passage, without
7
+ a subagent. Ambiguous matches return nearby prose and selection handles;
8
+ large results and candidate lists are paginated.
9
+ - Track expansion provenance in session metadata without adding visible checkpoint
10
+ references. Preserve it through repeated compaction, read retention, filtering,
11
+ and checkpoint revisions. Checkpoints without expansion provenance still use
12
+ `context_lookup` for recovery.
13
+ - Simplify repeated recovery guidance while keeping `context_lookup` favoured for
14
+ historical questions and broader recovery. Selection and pagination instructions
15
+ appear in tool responses only when needed.
16
+ opt-in direct-recovery mode retains its existing tools and excludes expansion.
17
+
3
18
  ## 0.12.0
4
19
 
5
20
  - Add explicit main-agent context-recovery opt-in through
@@ -18,7 +18,7 @@
18
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
- * Fallback tools neither count nor reset it.
21
+ * Expansion calls neither count nor reset it.
22
22
  * MECH_COMPACT_LOOKUP_SESSION_FILE absolute session JSONL path to search
23
23
  * instead of the current branch (study override)
24
24
  */
@@ -34,6 +34,8 @@ import { buildSessionProjection, SessionManager } from "@earendil-works/pi-codin
34
34
  import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
35
35
  import { capSpans, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
36
36
  import { recoveryText, startMainAgentLookup } from "./lib/main-agent-lookup.js";
37
+ import { expandTargets, expansionDigest, formatExpansionResult, pairedToolResults } from "./lib/context-expansion.js";
38
+ import type { ExpansionAnchor, ExpansionQuery, ExpansionResult, ExpansionTarget } from "./lib/context-expansion.js";
37
39
  import { ToolRenderer, TOOL_DISPLAY_EXPLANATION } from "./lib/tool-stubs/renderer.mjs";
38
40
  import { checkpointPath } from "./lib/tool-stubs/display.mjs";
39
41
  import { Locations } from "./lib/tool-stubs/locations.mjs";
@@ -308,28 +310,6 @@ interface TranscriptIndexSection {
308
310
  startLine: number;
309
311
  }
310
312
 
311
- // Pair only selected messages, by call id AND tool name. Ambiguous concurrent
312
- // ids stay unknown; sequential reuse is allowed after consuming a result.
313
- function pairedToolResults(messages: AgentMessage[]): Map<object, Record<string, any>> {
314
- const results = new Map<object, Record<string, any>>();
315
- const pending = new Map<string, { block: object; name: string } | null>();
316
- for (const message of messages) {
317
- const m = message as unknown as Record<string, any>;
318
- if (m.role === "assistant") {
319
- for (const block of m.content ?? []) {
320
- if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
321
- pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
322
- }
323
- } else if (m.role === "toolResult") {
324
- const call = pending.get(m.toolCallId);
325
- if (!call || call.name !== m.toolName) continue;
326
- results.set(call.block, m);
327
- pending.delete(m.toolCallId);
328
- }
329
- }
330
- return results;
331
- }
332
-
333
313
  interface TranscriptIndexEntry {
334
314
  id: string;
335
315
  type: string;
@@ -563,19 +543,25 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
563
543
  const results = pairedToolResults(messages);
564
544
  const lines: string[] = [], turnIds: (string | null)[] = [], readPositions: ReadPosition[] = [];
565
545
  const tools: ToolLines = { version: 2, lines: [] };
546
+ const expansionAnchors: ExpansionAnchor[] = [];
566
547
  for (const [messageIndex, msg] of messages.entries()) {
567
548
  const start = lines.length;
549
+ const entryId = sources?.[messageIndex]?.entryId;
568
550
  const m = msg as unknown as Record<string, any>;
569
551
  switch (msg.role) {
570
552
  case "user": {
571
553
  const { text, images } = textOf(m.content);
572
- if (text.trim() || images > 0) lines.push(`[User]: ${text}`);
554
+ if (text.trim() || images > 0) {
555
+ if (entryId) expansionAnchors.push({ index: lines.length, source: { kind: "prose", entryId, digest: expansionDigest(m.content) } });
556
+ lines.push(`[User]: ${text}`);
557
+ }
573
558
  break;
574
559
  }
575
560
  case "assistant": {
576
561
  let prose = "";
577
562
  const calls: ToolStub[] = [];
578
- for (const block of m.content ?? []) {
563
+ const callAnchors: Omit<ExpansionAnchor, "index">[] = [];
564
+ for (const [blockIndex, block] of (m.content ?? []).entries()) {
579
565
  if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
580
566
  else if (block.type === "toolCall") {
581
567
  const name = String(block.name), args = block.arguments ?? {};
@@ -583,12 +569,18 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
583
569
  const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
584
570
  const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
585
571
  const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
572
+ if (entryId && typeof block.id === "string") callAnchors.push({ callIndex: calls.length,
573
+ source: { kind: "tool", entryId, blockIndex, callId: block.id, name, digest: expansionDigest([name, block.id, args]) } });
586
574
  calls.push(await renderer.render(name, args, status + (label ? ` → ${label}` : "")));
587
575
  }
588
576
  // thinking blocks: removed by design (kept in the session)
589
577
  }
590
- if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
578
+ if (prose.trim()) {
579
+ if (entryId) expansionAnchors.push({ index: lines.length, source: { kind: "prose", entryId, digest: expansionDigest(prose.trim()) } });
580
+ lines.push(`[Assistant]: ${prose.trim()}`);
581
+ }
591
582
  if (calls.length > 0) {
583
+ expansionAnchors.push(...callAnchors.map((anchor) => ({ ...anchor, index: lines.length })));
592
584
  tools.lines.push({ index: lines.length, calls, mergeable: !prose.trim() });
593
585
  lines.push(renderToolLine(calls));
594
586
  }
@@ -604,6 +596,8 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
604
596
  case "bashExecution": {
605
597
  const calls = [await renderer.render("bash", { command: String(m.command ?? "") }, " [output removed]")];
606
598
  const prefix = "[BashExecution]: ";
599
+ if (entryId) expansionAnchors.push({ index: lines.length, callIndex: 0,
600
+ source: { kind: "bash", entryId, digest: expansionDigest([m.command ?? "", m.output ?? ""]) } });
607
601
  tools.lines.push({ index: lines.length, calls, mergeable: false, prefix });
608
602
  lines.push(renderToolLine(calls, NORMAL_PREVIEW_CHARS, prefix));
609
603
  break;
@@ -623,7 +617,8 @@ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRendere
623
617
  }
624
618
  for (let i = start; i < lines.length; i++) turnIds.push(sources?.[messageIndex]?.owner ?? null);
625
619
  }
626
- return { lines, ...(sources ? { turnIds } : {}), ...(readPositions.length ? { readPositions } : {}), ...(tools.lines.length ? { tools } : {}) };
620
+ return { lines, ...(sources ? { turnIds } : {}), ...(readPositions.length ? { readPositions } : {}), ...(tools.lines.length ? { tools } : {}),
621
+ ...(expansionAnchors.length ? { expansionAnchors } : {}) };
627
622
  }
628
623
 
629
624
  const SECTION_HEADER = "### Compacted conversation (oldest first)";
@@ -693,6 +688,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
693
688
  tools: sd.tools,
694
689
  turnIds: sd.turnIds,
695
690
  readPositions: sd.readPositions,
691
+ expansionAnchors: sd.expansionAnchors,
696
692
  });
697
693
  }
698
694
  return { base, spans };
@@ -706,6 +702,7 @@ interface FilterRevision {
706
702
  fidelity?: TurnFidelities;
707
703
  slots?: TurnSlot[];
708
704
  readRetention: ReadRetention;
705
+ expansionTargets: ExpansionTarget[];
709
706
  }
710
707
 
711
708
  function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
@@ -846,7 +843,6 @@ function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, c
846
843
  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.";
847
844
  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.";
848
845
  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.";
849
- 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.";
850
846
 
851
847
  const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_NOTE} Selected retained reads and the uncompacted tail remain available as evidence. Recover only hidden information needed for the current task.
852
848
  1. **Restore only information needed to continue.** Re-read project files when you need their current contents; cheap local rereads and recomputations are reasonable. If you need an earlier observation, the source of a finding, or the reason for a conclusion that compaction hid, use \`context_lookup\`. This can avoid repeating slow or unreliable research. Restore inputs, not completed actions: do not redo writes, edits, or other state-changing actions merely because their results are hidden. **Before using \`write\` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.**
@@ -856,12 +852,11 @@ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_N
856
852
  const REVISION_NOTE_PREFIX = "- Checkpoint context revised: ";
857
853
  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}`;
858
854
 
859
- 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.`;
855
+ 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.`;
860
856
 
861
- const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Use `context_lookup` for omitted observations or provenance; inspect sources for current state.";
857
+ const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Prefer `context_lookup` for omitted observations or provenance. To expand a specific visible tool stub directly, quote it to `context_expand`. Inspect sources for current state.";
862
858
 
863
859
  const REORIENT_MESSAGE = "transparent-compact:reorient";
864
- const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead. ${RECOVERY_FILESYSTEM_RULE} Keep these evidence/recovery rules in force as work continues.`;
865
860
 
866
861
  function latestVerbatimCompaction(entries: SessionEntry[]) {
867
862
  for (let i = entries.length - 1; i >= 0; i--) {
@@ -872,7 +867,7 @@ function latestVerbatimCompaction(entries: SessionEntry[]) {
872
867
  }
873
868
 
874
869
  function reorientationMessage(entries: SessionEntry[], compactionId: string, filtered = false, revisionId = compactionId, fidelity = false) {
875
- return { customType: REORIENT_MESSAGE, content: `${recoveryText(entries, REORIENT_BLOCK)}${filtered ? `\n\n${FILTER_EXPLANATION}` : ""}${fidelity ? `\n\n${FIDELITY_EXPLANATION}` : ""}\n\n${RECOVERY_RECAP}`,
870
+ return { customType: REORIENT_MESSAGE, content: `${recoveryText(entries, REORIENT_BLOCK)}${filtered ? `\n\n${FILTER_EXPLANATION}` : ""}${fidelity ? `\n\n${FIDELITY_EXPLANATION}` : ""}`,
876
871
  display: false, details: { compactionId, ...(revisionId !== compactionId ? { revisionId } : {}) } };
877
872
  }
878
873
 
@@ -944,6 +939,8 @@ async function buildMechanicalSummary(opts: {
944
939
  locations?: LocationEntry[];
945
940
  spanTurnIds?: (string | null)[];
946
941
  spanReadPositions?: ReadPosition[];
942
+ spanExpansionAnchors?: ExpansionAnchor[];
943
+ expansionTargets?: ExpansionTarget[]; // output: final visible fragments and internal provenance
947
944
  filteredTurnIds?: string[];
948
945
  fidelity?: TurnFidelities;
949
946
  slots?: TurnSlot[]; // generated output placements; no raw payloads
@@ -968,6 +965,7 @@ async function buildMechanicalSummary(opts: {
968
965
  const inserted = retainReadSpans(opts.revisedAt ? spans : [...spans, {
969
966
  at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
970
967
  lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds, readPositions: opts.spanReadPositions,
968
+ expansionAnchors: opts.spanExpansionAnchors,
971
969
  }], retained, excluded);
972
970
  if (inserted.unplaced.length) throw new Error(`Cannot retain read ${inserted.unplaced[0].entryId} (${inserted.unplaced[0].path}): its original position is not in a verbatim span. Choose another read or set it to OFF.`);
973
971
  const rendered = fidelitySpans(filterSpans(inserted.spans, excluded), fidelity);
@@ -1010,7 +1008,21 @@ async function buildMechanicalSummary(opts: {
1010
1008
  opts.notify(`transparent-compact: retained reads alone are ${retainedChars.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
1011
1009
  if (maxChars !== undefined && nativeChars > maxChars)
1012
1010
  opts.notify(`transparent-compact: full-fidelity turns alone are ~${nativeChars.toLocaleString()} estimated chars (budget ${maxChars.toLocaleString()}); they are kept un-capped. Only PROSE can be trimmed.`);
1013
- const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost, guidance);
1011
+ const anchors = allSpans.map((span) => {
1012
+ const rows = new Map<number, ExpansionAnchor[]>();
1013
+ for (const anchor of span.expansionAnchors ?? []) {
1014
+ const group = rows.get(anchor.index) ?? []; group.push(anchor); rows.set(anchor.index, group);
1015
+ }
1016
+ return rows;
1017
+ });
1018
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost, guidance,
1019
+ opts.expansionTargets && ((span, index, text, calls) => {
1020
+ for (const anchor of anchors[span].get(index) ?? []) {
1021
+ if (anchor.source.kind === "prose" && text === allSpans[span].lines[index]) continue;
1022
+ const display = anchor.callIndex === undefined ? text : calls?.find((call) => call.index === anchor.callIndex)?.text;
1023
+ if (display) opts.expansionTargets!.push({ text: display, source: anchor.source });
1024
+ }
1025
+ }));
1014
1026
  if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
1015
1027
 
1016
1028
  const blocks: string[] = [];
@@ -1487,7 +1499,7 @@ async function runLookupSubagent(opts: {
1487
1499
  // Session-backed transcript (rendered only when a recovery tool is called)
1488
1500
  // ============================================================================
1489
1501
 
1490
- function sessionTranscript(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }): Transcript {
1502
+ function sessionEntries(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }): SessionEntry[] {
1491
1503
  const override = process.env.MECH_COMPACT_LOOKUP_SESSION_FILE?.trim();
1492
1504
  let entries: SessionEntry[];
1493
1505
  if (override) {
@@ -1502,16 +1514,30 @@ function sessionTranscript(ctx: { sessionManager: { getBranch: () => SessionEntr
1502
1514
  // and context edits never remove earlier thinking or tool results here.
1503
1515
  entries = ctx.sessionManager.getBranch();
1504
1516
  }
1505
- const { lines, index } = branchToTranscript(entries);
1517
+ return entries;
1518
+ }
1519
+
1520
+ function sessionTranscript(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }): Transcript {
1521
+ const { lines, index } = branchToTranscript(sessionEntries(ctx));
1506
1522
  return { name: "session", file: "session", lines, index };
1507
1523
  }
1508
1524
 
1525
+ /** Read only the active checkpoint's generated expansion index. */
1526
+ export function expandCheckpointText(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, query: ExpansionQuery): ExpansionResult {
1527
+ const branch = ctx.sessionManager.getBranch(), compaction = latestVerbatimCompaction(branch);
1528
+ if (!compaction) return { status: "not-found" };
1529
+ const revision = latestFilterRevision(branch);
1530
+ const targets = revision ? revision.data.expansionTargets :
1531
+ (compaction.details as { expansionTargets?: ExpansionTarget[] }).expansionTargets;
1532
+ return expandTargets(sessionEntries(ctx), targets ?? [], query);
1533
+ }
1534
+
1509
1535
  // ============================================================================
1510
1536
  // Main-agent lookup admission
1511
1537
  // ============================================================================
1512
1538
 
1513
1539
  /** Count prior lookup attempts since the last user/ordinary-work/bash boundary.
1514
- * Text and thinking neither increase nor reset the count. Deduplicate call/result ids, and include
1540
+ * Expansion results, text, and thinking neither increase nor reset the count. Deduplicate call/result ids, and include
1515
1541
  * earlier siblings in the current assistant message even before results exist:
1516
1542
  * two parallel lookups cannot both claim the first slot. Later siblings are
1517
1543
  * excluded. Raw branch state follows reload, resume, compaction, and forks. */
@@ -1524,6 +1550,7 @@ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEnt
1524
1550
  const m = e.message;
1525
1551
  if (m.role === "user" || m.role === "bashExecution") break;
1526
1552
  if (m.role === "toolResult") {
1553
+ if (m.toolName === "context_expand") continue;
1527
1554
  if (m.toolName !== "context_lookup") break;
1528
1555
  calls.add(m.toolCallId);
1529
1556
  } else if (m.role === "assistant") {
@@ -1749,9 +1776,9 @@ export default function (pi: ExtensionAPI) {
1749
1776
  kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
1750
1777
  JSON.stringify(Object.entries(modes).sort()) === JSON.stringify(Object.entries(previousFidelity).sort());
1751
1778
  const cap = capSettings(entries);
1752
- const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }) => buildMechanicalSummary({
1779
+ const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }, expansionTargets?: ExpansionTarget[]) => buildMechanicalSummary({
1753
1780
  reason: canonical.span.reason, tokensBefore: compaction.tokensBefore, branchEntries: entries,
1754
- now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
1781
+ now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation, expansionTargets,
1755
1782
  firstKeptEntryId: compaction.firstKeptEntryId,
1756
1783
  ...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
1757
1784
  retention, canonical.readFiles, canonical.modifiedFiles, pruned),
@@ -1808,7 +1835,8 @@ export default function (pi: ExtensionAPI) {
1808
1835
  if (unchanged(excluded, keptAsides, fidelity) && sameRetention()) {
1809
1836
  ctx.ui.notify("No checkpoint context changes.", "info"); return;
1810
1837
  }
1811
- const summary = await renderCheckpoint(excluded, fidelity, slots, false);
1838
+ const expansionTargets: ExpansionTarget[] = [];
1839
+ const summary = await renderCheckpoint(excluded, fidelity, slots, false, undefined, expansionTargets);
1812
1840
  if (summary === undefined) return;
1813
1841
  checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
1814
1842
  const current = ctx.sessionManager.getBranch();
@@ -1816,7 +1844,7 @@ export default function (pi: ExtensionAPI) {
1816
1844
  latestFilterRevision(current)?.id !== revisionId || ctx.sessionManager.getLeafId() !== entries.at(-1)?.id || !ctx.isIdle() || ctx.hasPendingMessages()) {
1817
1845
  ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
1818
1846
  }
1819
- pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary, readRetention: retention,
1847
+ pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary, readRetention: retention, expansionTargets,
1820
1848
  filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
1821
1849
  ...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
1822
1850
  ctx.ui.notify("Checkpoint context updated. No additional history compacted; recent messages and boundary unchanged.", "info");
@@ -2020,6 +2048,7 @@ export default function (pi: ExtensionAPI) {
2020
2048
  const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
2021
2049
  const span = await summarizeMessages(allMessages, renderer, preparedMessageSources(branchEntries, allMessages), (text) => recoveryText(branchEntries, text));
2022
2050
  const spanLines = span.lines;
2051
+ const expansionTargets: ExpansionTarget[] = [];
2023
2052
 
2024
2053
  // 3) Explicit read choices apply independently after whole-turn filtering.
2025
2054
  const catalog = readCatalog(branchEntries, ctx.cwd);
@@ -2049,6 +2078,7 @@ export default function (pi: ExtensionAPI) {
2049
2078
  locations: renderer.locations.entries,
2050
2079
  spanTurnIds: span.turnIds,
2051
2080
  spanReadPositions: span.readPositions,
2081
+ spanExpansionAnchors: span.expansionAnchors, expansionTargets,
2052
2082
  filteredTurnIds, fidelity, slots,
2053
2083
  spanFrom,
2054
2084
  spanTo,
@@ -2079,6 +2109,7 @@ export default function (pi: ExtensionAPI) {
2079
2109
  modifiedFiles: canonicalModifiedFiles,
2080
2110
  readRetention: canonicalRetained,
2081
2111
  locations: renderer.locations.entries,
2112
+ expansionTargets,
2082
2113
  ...(filteredTurnIds.length ? { filteredTurnIds } : {}),
2083
2114
  ...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
2084
2115
  ...(Object.keys(fidelity).length ? { fidelity, slots } : {}),
@@ -2086,7 +2117,8 @@ export default function (pi: ExtensionAPI) {
2086
2117
  // are re-rendered from the earlier entries' details — no nesting.
2087
2118
  span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
2088
2119
  lines: spanLines, turnIds: span.turnIds, ...(span.readPositions ? { readPositions: span.readPositions } : {}),
2089
- ...(span.tools ? { tools: span.tools } : {}) },
2120
+ ...(span.tools ? { tools: span.tools } : {}),
2121
+ ...(span.expansionAnchors ? { expansionAnchors: span.expansionAnchors } : {}) },
2090
2122
  },
2091
2123
  },
2092
2124
  };
@@ -2106,7 +2138,7 @@ export default function (pi: ExtensionAPI) {
2106
2138
  label: "Context lookup",
2107
2139
  executionMode: "sequential",
2108
2140
  description:
2109
- `Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction. Ask \`context_lookup\` where an earlier finding came from, what a command actually printed, or why you reached a conclusion, especially when earlier notes conflict with new evidence. A subagent searches this conversation's full raw active branch in its own context and returns relevant findings. ${RECOVERY_SOURCE_GUIDANCE} ${RECOVERY_SCOPE_RULE} ${RECOVERY_FILESYSTEM_RULE}`,
2141
+ `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}`,
2110
2142
  promptSnippet: "Retrieve earlier outputs, findings, decisions, and reasoning hidden by compaction, including the provenance of earlier conclusions",
2111
2143
  parameters: Type.Object({
2112
2144
  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." }),
@@ -2140,4 +2172,24 @@ export default function (pi: ExtensionAPI) {
2140
2172
  }
2141
2173
  },
2142
2174
  });
2175
+
2176
+ pi.registerTool({
2177
+ name: "context_expand",
2178
+ label: "Context expansion",
2179
+ description: "Use `context_expand` to expand one visible compacted tool stub or truncated passage by quoting it. Ambiguous matches return candidates; large results are paginated. Use for focused recovery rather than exploration; prefer `context_lookup` for historical questions, locating relevant evidence, or broader recovery.",
2180
+ parameters: Type.Object({
2181
+ text: Type.String({ minLength: 1, maxLength: 4000, description: "Literal text copied from the compacted stub or truncated passage to expand." }),
2182
+ selector: Type.Optional(Type.String({ description: "Candidate selector returned by an ambiguous response. Repeat the original text unchanged." })),
2183
+ cursor: Type.Optional(Type.String({ description: "Continuation cursor returned by a limited response. Keep text and selector unchanged." })),
2184
+ }),
2185
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
2186
+ if (signal?.aborted) return { content: [{ type: "text", text: "Context expansion cancelled." }], details: undefined, isError: true };
2187
+ try {
2188
+ const result = expandCheckpointText(ctx, params);
2189
+ return { content: [{ type: "text", text: formatExpansionResult(result) }], details: undefined, isError: result.status === "invalid" };
2190
+ } catch (error) {
2191
+ return { content: [{ type: "text", text: `context_expand failed: ${errMsg(error)}` }], details: undefined, isError: true };
2192
+ }
2193
+ },
2194
+ });
2143
2195
  }
@@ -27,6 +27,8 @@ export interface ToolLine {
27
27
  export interface ToolLines { version: 2; lines: ToolLine[] }
28
28
  export interface SpanContent { lines: string[]; tools?: ToolLines; protectedLines?: number[] }
29
29
  export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[]; locationIds: string[] }
30
+ /** Observe final rows without adding identifiers or changing presentation. */
31
+ export type CapRowObserver = (span: number, index: number, text: string, calls?: { index: number; text: string }[]) => void;
30
32
  export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
31
33
  return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
32
34
  }
@@ -84,13 +86,17 @@ interface Row {
84
86
  * Every rung walks oldest first, across all spans (not just the new one).
85
87
  */
86
88
  export function capSpans(spans: SpanContent[], budget = Infinity, extraChars: (ids: string[]) => number = () => 0,
87
- guidance: (text: string) => string = (text) => text): CappedSpans {
89
+ guidance: (text: string) => string = (text) => text, observe?: CapRowObserver): CappedSpans {
88
90
  const tightened = spans.map(() => false), trimmed = spans.map(() => false);
89
91
  const records = spans.map(toolRecords);
90
92
  const references = (calls: ToolStub[]) => [...new Set(calls.flatMap((call) => call.locations ?? []))];
91
93
  const initialIds = references(records.flatMap((map) => [...map.values()].flatMap((record) => record.calls)));
92
94
  let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0) + extraChars(initialIds);
93
- if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed, locationIds: initialIds };
95
+ if (size <= budget) {
96
+ if (observe) spans.forEach((span, n) => span.lines.forEach((text, index) => observe(n, index, text,
97
+ records[n].get(index)?.calls.map((call, index) => ({ index, text: renderToolStub(call) })))));
98
+ return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed, locationIds: initialIds };
99
+ }
94
100
  const states = spans.map((span, spanIndex) => {
95
101
  const ownRecords = records[spanIndex];
96
102
  return span.lines.map((text, index): Row => {
@@ -109,6 +115,9 @@ export function capSpans(spans: SpanContent[], budget = Infinity, extraChars: (i
109
115
  const lines: string[] = [];
110
116
  for (let i = 0; i < rows.length; i++) {
111
117
  const row = rows[i];
118
+ observe?.(span, row.index, row.text, row.calls?.map((call) => ({
119
+ index: records[span].get(row.index)!.calls.indexOf(call), text: renderToolStub(call, row.preview),
120
+ })));
112
121
  if (joined(rows, i)) lines[lines.length - 1] += `; ${row.text.slice(TOOL_PREFIX.length)}`;
113
122
  else lines.push(row.text);
114
123
  if (row.tightened || joined(rows, i)) tightened[span] = true;
@@ -164,7 +173,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity, extraChars: (i
164
173
  if (row.protected || !line.startsWith("[User]:") || line.length <= 120) continue;
165
174
  let end = 120;
166
175
  if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
167
- const stub = `${line.slice(0, end)}${guidance(`…[truncated +${line.length - end} chars — use context_lookup]`)}`;
176
+ const stub = `${line.slice(0, end)}${guidance(`…[truncated +${line.length - end} chars — use context_expand to expand, or context_lookup to ask a question]`)}`;
168
177
  if (stub.length >= line.length) continue;
169
178
  row.text = stub;
170
179
  trimmed[span] = true;
@@ -0,0 +1,190 @@
1
+ /** Quote-to-expand backend. No tool registration, prompts, model calls, or writes.
2
+ * Targets come from renderer provenance, never from parsing checkpoint text.
3
+ */
4
+ import { createHash } from "node:crypto";
5
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
6
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
7
+
8
+ export type ExpansionSource = (
9
+ | { kind: "tool"; entryId: string; blockIndex: number; callId: string; name: string }
10
+ | { kind: "prose" | "bash"; entryId: string }
11
+ ) & { digest: string };
12
+ export interface ExpansionAnchor { index: number; source: ExpansionSource; callIndex?: number }
13
+ export interface ExpansionTarget { text: string; source: ExpansionSource }
14
+ export interface ExpansionQuery { text: string; selector?: string; cursor?: string }
15
+ export interface ExpansionCandidate {
16
+ selector: string;
17
+ kind: ExpansionSource["kind"];
18
+ preview: string;
19
+ before?: string;
20
+ after?: string;
21
+ }
22
+ export type ExpansionResult =
23
+ | { status: "not-found" }
24
+ | { status: "invalid"; reason: "query" | "selector" | "cursor" }
25
+ | { status: "unavailable" }
26
+ | { status: "ambiguous"; total: number; candidates: ExpansionCandidate[]; nextCursor?: string }
27
+ | { status: "expanded"; kind: ExpansionSource["kind"]; entryIds: string[]; content: string; nextCursor?: string };
28
+
29
+ export function remapExpansionAnchors(anchors: ExpansionAnchor[] | undefined, indices: Map<number, number>): ExpansionAnchor[] | undefined {
30
+ return anchors?.filter((anchor) => indices.has(anchor.index)).map((anchor) => ({ ...anchor, index: indices.get(anchor.index)! }));
31
+ }
32
+
33
+ // Pair by call ID AND tool name. Concurrent duplicate IDs stay ambiguous;
34
+ // sequential reuse is allowed only after consuming a result.
35
+ export function pairedToolResults(messages: AgentMessage[]): Map<object, Record<string, any>> {
36
+ const results = new Map<object, Record<string, any>>();
37
+ const pending = new Map<string, { block: object; name: string } | null>();
38
+ for (const message of messages) {
39
+ const m = message as unknown as Record<string, any>;
40
+ if (m.role === "assistant") {
41
+ for (const block of m.content ?? []) {
42
+ if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
43
+ pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
44
+ }
45
+ } else if (m.role === "toolResult") {
46
+ const call = pending.get(m.toolCallId);
47
+ if (!call || call.name !== m.toolName) continue;
48
+ results.set(call.block, m);
49
+ pending.delete(m.toolCallId);
50
+ }
51
+ }
52
+ return results;
53
+ }
54
+
55
+ function textContent(content: unknown, separator = ""): string {
56
+ if (typeof content === "string") return content;
57
+ return Array.isArray(content) ? content.filter((block) => block?.type === "text" && typeof block.text === "string")
58
+ .map((block) => block.text).join(separator) : "";
59
+ }
60
+ const imageCount = (content: unknown) => Array.isArray(content) ? content.filter((block) => block?.type === "image").length : 0;
61
+ const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 32);
62
+ export const expansionDigest = hash;
63
+ function head(text: string, length: number): string {
64
+ let end = Math.min(length, text.length);
65
+ if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end])) end--;
66
+ return text.slice(0, end);
67
+ }
68
+ function preview(entry: SessionEntry): string {
69
+ if (entry.type !== "message" || (entry.message.role !== "user" && entry.message.role !== "assistant")) return "";
70
+ const value = textContent(entry.message.content, "\n").trim();
71
+ return value ? head(value, 160) : "";
72
+ }
73
+ function neighbours(entries: readonly SessionEntry[], at: number): { before?: string; after?: string } {
74
+ const result: { before?: string; after?: string } = {};
75
+ if (at < 0) return result;
76
+ for (const [key, step] of [["before", -1], ["after", 1]] as const) {
77
+ for (let i = at + step; i >= 0 && i < entries.length; i += step) {
78
+ const text = preview(entries[i]);
79
+ if (text) { result[key] = text; break; }
80
+ }
81
+ }
82
+ return result;
83
+ }
84
+ function cursor(key: string, offset: number): string {
85
+ return Buffer.from(JSON.stringify({ key, offset })).toString("base64url");
86
+ }
87
+ function offsetOf(value: string | undefined, key: string): number | undefined {
88
+ if (value === undefined) return 0;
89
+ if (typeof value !== "string" || value.length > 256 || !/^[\w-]+$/.test(value)) return undefined;
90
+ try {
91
+ const decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
92
+ return decoded.key === key && Number.isSafeInteger(decoded.offset) && decoded.offset >= 0 ? decoded.offset : undefined;
93
+ } catch { return undefined; }
94
+ }
95
+
96
+ /** Literal, case-sensitive matching of a displayed fragment, not history search.
97
+ * Selectors exist only in results; cursors bind the query and exact backing data.
98
+ * The tool adapter formats these results without changing the recovered content.
99
+ */
100
+ export function expandTargets(entries: readonly SessionEntry[], targets: readonly ExpansionTarget[], query: ExpansionQuery,
101
+ limits: { maxChars?: number; maxCandidates?: number } = {}): ExpansionResult {
102
+ if (!query || typeof query.text !== "string" || !query.text.trim() || query.text.length > 4000)
103
+ return { status: "invalid", reason: "query" };
104
+ const maxChars = limits.maxChars ?? 12000, maxCandidates = limits.maxCandidates ?? 8;
105
+ if (!Number.isSafeInteger(maxChars) || maxChars < 2 || !Number.isSafeInteger(maxCandidates) || maxCandidates < 1)
106
+ throw new Error("Invalid expansion limits.");
107
+ const quote = query.text.trim().replace(/^\[Tools\]:\s*/, "");
108
+ if (!quote) return { status: "invalid", reason: "query" };
109
+ const positions = new Map(entries.map((entry, index) => [entry.id, index]));
110
+ const matches: { target: ExpansionTarget; candidate: ExpansionCandidate }[] = [];
111
+ const seen = new Set<string>();
112
+ for (const target of targets) {
113
+ if (!target.text.includes(quote)) continue;
114
+ const adjacent = neighbours(entries, positions.get(target.source.entryId) ?? -1);
115
+ const selector = hash([quote, target.source]);
116
+ if (seen.has(selector)) continue;
117
+ seen.add(selector);
118
+ matches.push({ target, candidate: { selector, kind: target.source.kind, preview: head(target.text, 200), ...adjacent } });
119
+ }
120
+ if (!matches.length) return query.selector === undefined ? { status: "not-found" } : { status: "invalid", reason: "selector" };
121
+ const selected = query.selector === undefined ? (matches.length === 1 ? matches[0] : undefined)
122
+ : matches.find((match) => match.candidate.selector === query.selector);
123
+ if (query.selector !== undefined && !selected) return { status: "invalid", reason: "selector" };
124
+ if (!selected) {
125
+ const key = hash(["matches", matches.map((match) => match.candidate)]), offset = offsetOf(query.cursor, key);
126
+ if (offset === undefined || offset >= matches.length) return { status: "invalid", reason: "cursor" };
127
+ const candidates = matches.slice(offset, offset + maxCandidates).map((match) => match.candidate);
128
+ const end = offset + candidates.length;
129
+ return { status: "ambiguous", total: matches.length, candidates, ...(end < matches.length ? { nextCursor: cursor(key, end) } : {}) };
130
+ }
131
+ const source = selected.target.source, entry = entries[positions.get(source.entryId) ?? -1];
132
+ if (!entry || entry.type !== "message") return { status: "unavailable" };
133
+ const m = entry.message as unknown as Record<string, any>;
134
+ const entryIds = [entry.id];
135
+ let content: string;
136
+ if (source.kind === "tool") {
137
+ const call = m.role === "assistant" && m.content?.[source.blockIndex];
138
+ if (!call || call.type !== "toolCall" || call.id !== source.callId || call.name !== source.name ||
139
+ hash([call.name, call.id, call.arguments ?? {}]) !== source.digest) return { status: "unavailable" };
140
+ const messages = entries.filter((e) => e.type === "message").map((e) => e.message);
141
+ const result = pairedToolResults(messages).get(call);
142
+ const resultEntry = result && entries.find((e) => e.type === "message" && e.message === result);
143
+ if (resultEntry) entryIds.push(resultEntry.id);
144
+ content = JSON.stringify({ call: { name: call.name, arguments: call.arguments ?? {} }, result: result ? {
145
+ toolName: result.toolName, isError: result.isError, text: textContent(result.content),
146
+ imagesOmitted: imageCount(result.content), ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
147
+ } : null }, null, 2);
148
+ } else if (source.kind === "bash") {
149
+ if (m.role !== "bashExecution" || hash([m.command ?? "", m.output ?? ""]) !== source.digest) return { status: "unavailable" };
150
+ content = JSON.stringify({ command: m.command, output: m.output, exitCode: m.exitCode, cancelled: m.cancelled, truncated: m.truncated }, null, 2);
151
+ } else {
152
+ if (m.role !== "user" && m.role !== "assistant") return { status: "unavailable" };
153
+ content = textContent(m.content, m.role === "assistant" ? "\n" : "");
154
+ if (hash(m.role === "assistant" ? content.trim() : m.content) !== source.digest) return { status: "unavailable" };
155
+ }
156
+ const key = hash(["content", selected.candidate.selector, entryIds, content]), offset = offsetOf(query.cursor, key);
157
+ if (offset === undefined || (offset >= content.length && !(offset === 0 && content.length === 0)) ||
158
+ (offset > 0 && /[\uD800-\uDBFF]/.test(content[offset - 1]) && /[\uDC00-\uDFFF]/.test(content[offset])))
159
+ return { status: "invalid", reason: "cursor" };
160
+ const page = head(content.slice(offset), maxChars), end = offset + page.length;
161
+ return { status: "expanded", kind: source.kind, entryIds, content: page, ...(end < content.length ? { nextCursor: cursor(key, end) } : {}) };
162
+ }
163
+
164
+ /** Procedural guidance appears only in tool results, when it is needed. */
165
+ export function formatExpansionResult(result: ExpansionResult): string {
166
+ let text: string;
167
+ switch (result.status) {
168
+ case "expanded":
169
+ text = `Historical expansion (ENTRY ${result.entryIds.join(", ")}):\n${result.content}`;
170
+ break;
171
+ case "ambiguous":
172
+ text = `${result.total} matches. To expand one, repeat the same text with its selector, omitting cursor.\n\n` +
173
+ result.candidates.map((candidate) => [
174
+ `selector: ${candidate.selector}`,
175
+ `preview: ${JSON.stringify(candidate.preview)}`,
176
+ ...(candidate.before ? [`before: ${JSON.stringify(candidate.before)}`] : []),
177
+ ...(candidate.after ? [`after: ${JSON.stringify(candidate.after)}`] : []),
178
+ ].join("\n")).join("\n\n");
179
+ break;
180
+ case "not-found":
181
+ return "No matching fragment in the current checkpoint. Use context_lookup if recovery is still needed.";
182
+ case "unavailable":
183
+ return "The original source is unavailable. Use context_lookup if recovery is still needed.";
184
+ case "invalid":
185
+ return result.reason === "query" ? "context_expand failed: invalid text." :
186
+ "Invalid selector or cursor. Repeat the original text without selector or cursor.";
187
+ }
188
+ if (result.nextCursor) text += `\n\nMore content is available. Continue only if needed using the returned cursor; keep text and selector unchanged.\ncursor: ${result.nextCursor}`;
189
+ return text;
190
+ }
@@ -20,7 +20,10 @@ function selected(entries: readonly SessionEntry[]): boolean {
20
20
  export function recoveryText(entries: readonly SessionEntry[], text: string): string {
21
21
  if (!selected(entries)) return text;
22
22
  if (text.startsWith("**Recovering hidden details.**")) return DIRECT_INSTRUCTIONS;
23
- return text.replaceAll("`context_lookup`", "the context-recovery tools")
23
+ return text
24
+ .replace(" To expand a specific visible tool stub directly, quote it to `context_expand`.", "")
25
+ .replace("use context_expand to expand, or context_lookup to ask a question", "use context_lookup")
26
+ .replaceAll("`context_lookup`", "the context-recovery tools")
24
27
  .replaceAll("context_lookup", "the context-recovery tools");
25
28
  }
26
29
 
@@ -53,11 +56,13 @@ export function startMainAgentLookup(pi: ExtensionAPI, ctx: ExtensionContext, ba
53
56
 
54
57
  // Hidden, not just inactive: neither codemode nor tool search may offer the
55
58
  // alternative implementation. Leave the original registration alone otherwise.
56
- pi.registerTool({
57
- name: "context_lookup", label: "Context lookup", description: "", exposure: "hidden",
58
- parameters: Type.Object({}),
59
- async execute() { throw new Error("This session uses direct context recovery."); },
60
- });
59
+ for (const [name, label] of [["context_lookup", "Context lookup"], ["context_expand", "Context expansion"]]) {
60
+ pi.registerTool({
61
+ name, label, description: "", exposure: "hidden",
62
+ parameters: Type.Object({}),
63
+ async execute() { throw new Error("This session uses direct context recovery."); },
64
+ });
65
+ }
61
66
  const tools = [
62
67
  { ...backend.list, name: "context_list_entries", label: "Context entries",
63
68
  description: "List compacted session history ENTRY headers and previews in bounded pages. Follow the reported offset and throughEntry only when needed." },
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
5
5
  import { originalProjection, turnOwners } from "./turn-context.js";
6
6
  import type { TurnSpan } from "./turn-filter.js";
7
+ import { remapExpansionAnchors } from "./context-expansion.js";
7
8
 
8
9
  export type ReadMode = "off" | "first" | "latest";
9
10
  export interface ReadRetention {
@@ -222,7 +223,8 @@ export function retainReadSpans<T extends TurnSpan>(spans: T[], reads: ReadOutpu
222
223
  lines.push(span.lines[index]); turnIds.push(span.turnIds?.[index] ?? null);
223
224
  }
224
225
  const tools = span.tools && { ...span.tools, lines: span.tools.lines.map((record) => ({ ...record, index: indices.get(record.index)! })) };
225
- return { ...span, lines, turnIds, tools, protectedLines };
226
+ return { ...span, lines, turnIds, tools, protectedLines,
227
+ expansionAnchors: remapExpansionAnchors(span.expansionAnchors, indices) };
226
228
  });
227
229
  return { spans: rendered, unplaced: reads.filter((read) => !placed.has(read.entryId)) };
228
230
  }
@@ -3,6 +3,7 @@ import { buildSessionProjection, estimateTokens } from "@earendil-works/pi-codin
3
3
  import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
5
5
  import type { TurnSpan } from "./turn-filter.js";
6
+ import { remapExpansionAnchors } from "./context-expansion.js";
6
7
 
7
8
  export type Fidelity = "tools" | "full";
8
9
  export type TurnMode = "pruned" | "prose" | Fidelity;
@@ -96,7 +97,8 @@ export function fidelitySpans<T extends TurnSpan>(spans: T[], fidelity: TurnFide
96
97
  });
97
98
  const tools = span.tools && { ...span.tools, lines: span.tools.lines.filter((r) => indices.has(r.index))
98
99
  .map((r) => ({ ...r, index: indices.get(r.index)! })) };
99
- return { ...span, lines, turnIds, tools, protectedLines };
100
+ return { ...span, lines, turnIds, tools, protectedLines,
101
+ expansionAnchors: remapExpansionAnchors(span.expansionAnchors, indices) };
100
102
  });
101
103
  for (const id of Object.keys(fidelity)) if (!markers.has(id)) throw new Error(`Turn ${id} has no editable checkpoint position.`);
102
104
  return { spans: result, markers };
@@ -3,6 +3,8 @@ import { matchesKey, Key, truncateToWidth, visibleWidth, wrapTextWithAnsi } from
3
3
  import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
4
  import { FILTER_MARKER } from "./checkpoint-cap.js";
5
5
  import type { SpanContent, ToolLines } from "./checkpoint-cap.js";
6
+ import { remapExpansionAnchors } from "./context-expansion.js";
7
+ import type { ExpansionAnchor } from "./context-expansion.js";
6
8
  export { FILTER_MARKER } from "./checkpoint-cap.js";
7
9
  export { turnOwners } from "./turn-context.js";
8
10
  import { MODE_LABELS, MODE_SYMBOLS } from "./turn-context.js";
@@ -37,6 +39,8 @@ export const FILTER_EXPLANATION = "`[Turn manually filtered]` marks a user turn
37
39
  export interface ReadPosition { entryId: string; index: number }
38
40
  export interface TurnSpan extends SpanContent {
39
41
  turnIds?: (string | null)[];
42
+ /** Internal provenance only; never rendered into checkpoint text. */
43
+ expansionAnchors?: ExpansionAnchor[];
40
44
  /** Read-result entry IDs at boundaries between canonical prose/tool lines. */
41
45
  readPositions?: ReadPosition[];
42
46
  }
@@ -78,7 +82,8 @@ export function filterSpans<T extends TurnSpan>(spans: T[], excluded: Set<string
78
82
  const tools: ToolLines | undefined = span.tools && { ...span.tools, lines: span.tools.lines
79
83
  .filter((record) => indices.has(record.index))
80
84
  .map((record) => ({ ...record, index: indices.get(record.index)! })) };
81
- return { ...span, lines, turnIds, tools, protectedLines };
85
+ return { ...span, lines, turnIds, tools, protectedLines,
86
+ expansionAnchors: remapExpansionAnchors(span.expansionAnchors, indices) };
82
87
  });
83
88
  }
84
89
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Model-free, deterministic, and self-aware compaction; with session-backed subagent context recovery, and optional context pruning and fidelity controls.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -55,7 +55,6 @@
55
55
  "node": ">=22.19.0"
56
56
  },
57
57
  "pi": {
58
- "changelogPath": "",
59
58
  "extensions": [
60
59
  "./extensions/index.ts"
61
60
  ],
@@ -23,12 +23,12 @@ those tasks; use ordinary file tools as needed for the requested analysis.
23
23
 
24
24
  This skill pairs with the `@foliox/transparent-compact-pi` extension, which provides:
25
25
 
26
- - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Explicitly selected read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders and a recap follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
27
- - **`context_lookup`** — a subagent searches the full raw session branch in its **own** context and returns relevant findings. At lookup time, the extension mechanically renders the branch into entry-anchored text with an authoritative entry/section index, in memory.
26
+ - **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Explicitly selected read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
27
+ - **`context_lookup`** — a subagent searches the full raw session branch in its **own** context and returns relevant findings.
28
28
 
29
29
  Pi normally saves sessions under `~/.pi/agent/sessions/`; custom session locations also work. In-memory sessions retain history only while the process lives and cannot be resumed after exit.
30
30
 
31
- If `context_lookup` is not in your tool list, report that recovery is unavailable. Do not search session files manually for compaction recovery.
31
+ If `context_lookup` is not in your tool list, report that subagent recovery is unavailable.
32
32
 
33
33
  ## When to use
34
34
 
@@ -40,6 +40,9 @@ Tool stubs do not preserve the full supporting material. Most output
40
40
  and detailed payloads are omitted. Inline observations are historical, not verification
41
41
  of unshown details or current state. Unlabelled calls do not establish exit 0 or passing tests.
42
42
 
43
+ Prefer `context_lookup` for historical recovery. If you only need to expand one
44
+ visible tool stub or truncated passage, quote it to `context_expand` instead.
45
+
43
46
  Ask `context_lookup` a **specific historical question** to recover hidden supporting
44
47
  evidence. This can avoid repeating slow or unreliable research. For example:
45
48
  "Where did our earlier Holi 2026 date come from: a
@@ -63,16 +66,13 @@ narrow the search.
63
66
 
64
67
  For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically. It does **not** search abandoned branches or unrelated sessions. If the detail is absent, report that limitation instead of claiming it was recovered or widening this recovery search through filesystem tools.
65
68
 
66
- A study harness may configure `MECH_COMPACT_LOOKUP_SESSION_FILE` to make the extension search a full session rather than a pruned fork. This is extension configuration, not a tool argument or a file the main agent should read. Do not discover or change the override to broaden a lookup.
67
-
68
69
  ## Rules
69
70
 
70
- 1. **For recovery of details hidden by compaction, do not read or grep raw session JSONL files through filesystem tools.** Use `context_lookup`. Raw filesystem recovery would refill the compacted context. This restriction does not apply to user-requested session audits, debugging, or cross-session analysis.
71
- 2. Ask narrowly scoped questions using exact error strings, file paths, function names, or the command whose output you need. Recover tightly related details together; use separate queries for independent facts. Ask the subagent for evidence, not for a solution to the broader task.
72
- 3. Findings cite ENTRY ids and the logical transcript name. Retain these citations when relying on recovered facts. The renderer preserves full thinking, text, tool-call arguments, and tool results, although individual search results have output limits.
73
- 4. Distinguish **user instructions**, **observed tool output**, and **reasoning at the time**. A recovered `[thinking]` block is a historical hypothesis, not verified fact. Earlier assistant prose is not independently observed evidence either.
74
- 5. Historical tool output proves what was observed then, not what is true now. Review uncommitted work and re-verify current build/test state when needed. **Before using `write` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.** This is not a blanket reread requirement for small exact-match `edit`s.
75
- 6. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive. A partial search does not establish that something never happened.
71
+ 1. Ask narrowly scoped questions using exact error strings, file paths, function names, or the command whose output you need. Recover tightly related details together; use separate queries for independent facts. Ask the subagent for evidence, not for a solution to the broader task.
72
+ 2. Findings cite ENTRY ids and the logical transcript name. Retain these citations when relying on recovered facts. The renderer preserves full thinking, text, tool-call arguments, and tool results, although individual search results have output limits.
73
+ 3. Distinguish **user instructions**, **observed tool output**, and **reasoning at the time**. A recovered `[thinking]` block is a historical hypothesis, not verified fact. Earlier assistant prose is not independently observed evidence either.
74
+ 4. Historical tool output proves what was observed then, not what is true now. Review uncommitted work and re-verify current build/test state when needed. **Before using `write` to replace an existing file, re-read it unless its current contents are already visible in context. Do not reconstruct unchanged sections from memory.** This is not a blanket reread requirement for small exact-match `edit`s.
75
+ 5. Lookups can return incomplete findings or fail. State what remains missing; do not invent details or treat a partial answer as exhaustive. A partial search does not establish that something never happened.
76
76
 
77
77
  ## Independent exports
78
78