notesoup 0.56.0 → 0.57.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.
Files changed (59) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/marker.d.ts +4 -2
  3. package/dist/plugins/pi/marker.js +18 -8
  4. package/dist/plugins/pi/reset/lifecycle.js +6 -0
  5. package/dist/plugins/pi/runtime.js +8 -8
  6. package/dist/plugins/pi/text.js +1 -1
  7. package/dist/src/history/claude.d.ts +2 -0
  8. package/dist/src/history/claude.js +13 -2
  9. package/dist/src/history/codex-transcript.d.ts +15 -3
  10. package/dist/src/history/codex-transcript.js +57 -21
  11. package/dist/src/history/codex.d.ts +4 -2
  12. package/dist/src/history/codex.js +3 -3
  13. package/dist/src/history/corpus.d.ts +8 -1
  14. package/dist/src/history/corpus.js +17 -1
  15. package/dist/src/history/history.d.ts +16 -10
  16. package/dist/src/history/history.js +9 -9
  17. package/dist/src/history/local.d.ts +2 -0
  18. package/dist/src/history/local.js +35 -38
  19. package/dist/src/history/prefilter.d.ts +5 -0
  20. package/dist/src/history/prefilter.js +95 -0
  21. package/dist/src/history/query.d.ts +29 -27
  22. package/dist/src/history/query.js +82 -34
  23. package/dist/src/history/summary-cache.d.ts +10 -0
  24. package/dist/src/history/summary-cache.js +129 -0
  25. package/dist/src/tools/history.js +31 -20
  26. package/dist/test/agent-loop.test.js +62 -27
  27. package/dist/test/codex-history.test.js +90 -4
  28. package/dist/test/codex-plugin.test.js +6 -2
  29. package/dist/test/history-corpus.test.js +221 -33
  30. package/dist/test/history-prefilter.test.d.ts +1 -0
  31. package/dist/test/history-prefilter.test.js +174 -0
  32. package/dist/test/history-summary-cache.test.d.ts +1 -0
  33. package/dist/test/history-summary-cache.test.js +297 -0
  34. package/dist/test/history.integration.test.js +87 -52
  35. package/dist/test/marker.test.js +46 -15
  36. package/dist/test/model-facing-text.test.js +1 -1
  37. package/dist/test/reset-lifecycle.test.js +4 -6
  38. package/docs/architecture.md +1 -1
  39. package/docs/history-sessions.md +26 -2
  40. package/docs/reset-lifecycle.md +4 -4
  41. package/docs/tool-results.md +4 -2
  42. package/package.json +1 -1
  43. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  44. package/plugins/claude/dist/claude/helper.js +425 -122
  45. package/plugins/codex/dist/codex/notesoup.js +423 -123
  46. package/plugins/pi/marker.ts +18 -12
  47. package/plugins/pi/reset/lifecycle.ts +5 -0
  48. package/plugins/pi/runtime.ts +8 -8
  49. package/plugins/pi/text.ts +1 -1
  50. package/src/history/claude.ts +16 -2
  51. package/src/history/codex-transcript.ts +52 -17
  52. package/src/history/codex.ts +5 -5
  53. package/src/history/corpus.ts +19 -2
  54. package/src/history/history.ts +11 -11
  55. package/src/history/local.ts +34 -38
  56. package/src/history/prefilter.ts +86 -0
  57. package/src/history/query.ts +77 -33
  58. package/src/history/summary-cache.ts +119 -0
  59. package/src/tools/history.ts +33 -20
package/README.md CHANGED
@@ -28,7 +28,7 @@ pi -e npm:notesoup
28
28
 
29
29
  ## What you get
30
30
 
31
- - **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops; `/fresh-window Continue reviewing the implementation` clears and continues. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
31
+ - **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops, with any command text available for close-out notes. Separate human input received during emptying continues in the fresh window. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
32
32
  - **A boot block at every window head.** Static once-per-window content (cache-stable) with the window identity, the recent-notes index, and a short protocol teaching the model how to recover: notes for its own bookkeeping, history tools for everything before the reset.
33
33
  - **`get_context_remaining`** — how much room the brain has left before the hard-reserve wipe, including the warning runway.
34
34
  - **Seven history/notes tools**, flattened from the original Codex actions:
@@ -1,9 +1,11 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { CustomMessageEntryDraft, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
2
  /** Spacing between durable seq breadcrumbs, in projected history seq. */
3
- export declare const MARKER_INTERVAL = 120;
3
+ export declare const MARKER_INTERVAL = 100;
4
4
  /**
5
5
  * Stamp the current seq every MARKER_INTERVAL seqs. The marker names the seq it occupies, so a
6
6
  * model paging history_list meets a breadcrumb that tells it where it is. Skipped while a reset
7
7
  * tail still awaits boot or continuation: a foreign message there would close the repair shape.
8
8
  */
9
+ export declare function buildMarkerDraft(ctx: ExtensionContext, pending?: readonly SessionBoundaryDraft[]): CustomMessageEntryDraft | undefined;
10
+ /** Run-start fallback; active runs append the same draft through the turn-end boundary. */
9
11
  export declare function maybeSendMarker(pi: ExtensionAPI, ctx: ExtensionContext): void;
@@ -1,16 +1,16 @@
1
1
  import { piSequenceCount } from "../../src/history/pi.js";
2
- import { BOOT_TYPE, MARKER_TYPE } from "./entries.js";
2
+ import { BOOT_TYPE, MARKER_TYPE, RESET_MARKER_TYPE } from "./entries.js";
3
3
  import { nextHistorySeq } from "./history.js";
4
4
  import { inspectResetTail } from "./reset/artifacts.js";
5
5
  import { markerContent } from "./text.js";
6
6
  import { currentReset } from "./window.js";
7
7
  /** Spacing between durable seq breadcrumbs, in projected history seq. */
8
- export const MARKER_INTERVAL = 120;
8
+ export const MARKER_INTERVAL = 100;
9
9
  /** Highest seq already anchored by a window boot or marker; 0 before the first. */
10
- function lastMarkerSeq(ctx) {
10
+ function lastMarkerSeq(ctx, pending) {
11
11
  let last = 0;
12
12
  let nextSeq = 1;
13
- for (const entry of ctx.sessionManager.getEntries()) {
13
+ for (const entry of [...ctx.sessionManager.getEntries(), ...pending]) {
14
14
  const count = piSequenceCount(entry);
15
15
  if (count === 0)
16
16
  continue;
@@ -26,15 +26,25 @@ function lastMarkerSeq(ctx) {
26
26
  * model paging history_list meets a breadcrumb that tells it where it is. Skipped while a reset
27
27
  * tail still awaits boot or continuation: a foreign message there would close the repair shape.
28
28
  */
29
- export function maybeSendMarker(pi, ctx) {
29
+ export function buildMarkerDraft(ctx, pending = []) {
30
+ if (pending.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE))
31
+ return;
30
32
  const reset = currentReset(ctx);
31
33
  if (reset) {
32
34
  const tail = inspectResetTail(ctx, reset.id, reset.data.windowId);
33
35
  if (tail && (!tail.boot || !tail.continuation))
34
36
  return;
35
37
  }
36
- const seq = nextHistorySeq(ctx);
37
- if (seq - lastMarkerSeq(ctx) < MARKER_INTERVAL)
38
+ const seq = nextHistorySeq(ctx, pending);
39
+ if (seq - lastMarkerSeq(ctx, pending) < MARKER_INTERVAL)
40
+ return;
41
+ return { type: "custom_message", customType: MARKER_TYPE, content: markerContent(seq), display: false, details: { seq } };
42
+ }
43
+ /** Run-start fallback; active runs append the same draft through the turn-end boundary. */
44
+ export function maybeSendMarker(pi, ctx) {
45
+ const draft = buildMarkerDraft(ctx);
46
+ if (!draft)
38
47
  return;
39
- pi.sendMessage({ customType: MARKER_TYPE, content: markerContent(seq), display: false, details: { seq } }, { triggerTurn: false });
48
+ const { type: _type, ...message } = draft;
49
+ pi.sendMessage(message, { triggerTurn: false });
40
50
  }
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
3
  import { currentReset, currentWindowId } from "../window.js";
4
4
  import { nextHistorySeq } from "../history.js";
5
+ import { buildMarkerDraft } from "../marker.js";
5
6
  import { resetBoundaryCommitted } from "./committed.js";
6
7
  import { errorMessage } from "../../../src/error-message.js";
7
8
  import { carriedInputDrafts, isCarriedInputEntry } from "./artifacts.js";
@@ -272,6 +273,11 @@ export function registerResetLifecycle(pi, options) {
272
273
  if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
273
274
  restoreCommandInputs();
274
275
  control = decision.state;
276
+ if (!aborted && event.outcome !== "error" && options.isEnabled()) {
277
+ const marker = buildMarkerDraft(ctx, entries);
278
+ if (marker)
279
+ entries.push(marker);
280
+ }
275
281
  return entries.length > 0 ? { entries } : undefined;
276
282
  });
277
283
  pi.on("agent_before_settle", async (event, ctx) => {
@@ -174,8 +174,8 @@ export function registerContext(pi, settingsManager) {
174
174
  cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
175
175
  },
176
176
  });
177
- const emptyBrainCommand = {
178
- description: "Flush memory to notes and continue in a fresh window; optional prompt runs there",
177
+ const emptyBrainCommand = (name) => ({
178
+ description: "Flush memory to notes, reset, and stop; optional text provides close-out context",
179
179
  handler: async (args, cmdCtx) => {
180
180
  if (!enabled) {
181
181
  cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
@@ -187,27 +187,27 @@ export function registerContext(pi, settingsManager) {
187
187
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId)
188
188
  return;
189
189
  }
190
- // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
190
+ // Manual wipes close out at settlement, then stop unless later human input arrives. The hidden warning is triggered when idle,
191
191
  // steered into the running turn when busy — so the agent closes out promptly
192
192
  // instead of the reset waiting for the whole run.
193
193
  const prompt = args.trim() ? args : undefined;
194
- const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
194
+ const armed = resets.command(requestedWindowId, false);
195
195
  if (armed === "already-pending") {
196
196
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
197
197
  return;
198
198
  }
199
199
  cmdCtx.ui.notify("🥣 Dumping Brain", "info");
200
200
  try {
201
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
201
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/${name} ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
202
202
  }
203
203
  catch (error) {
204
204
  resets.clear();
205
205
  cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
206
206
  }
207
207
  },
208
- };
209
- pi.registerCommand("empty", emptyBrainCommand);
210
- pi.registerCommand("fresh-window", emptyBrainCommand);
208
+ });
209
+ pi.registerCommand("empty", emptyBrainCommand("empty"));
210
+ pi.registerCommand("fresh-window", emptyBrainCommand("fresh-window"));
211
211
  pi.registerTool(defineTool({
212
212
  name: "empty_brain",
213
213
  label: "Empty Brain",
@@ -18,7 +18,7 @@ export function promptBlock(commandLine) {
18
18
  }
19
19
  /** Approved manual close-out notices; both variants live here. */
20
20
  export const COMMAND_NOTICE = {
21
- prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The prompt below, and anything the human sends from now on, should be handled after the reset.",
21
+ prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The command below is context for your notes, not a task for the fresh window. Anything the human sends separately from now on should be handled after the reset.",
22
22
  bare: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. Anything the human sends from now on should be handled after the reset.",
23
23
  };
24
24
  /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
@@ -13,4 +13,6 @@ export type ClaudeHistoryProjection = HistoryProjection & {
13
13
  export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
14
  /** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
15
15
  export declare function offlineClaudeHead(text: string): string;
16
+ /** Select an offline head and build its projection from the same decoded records. */
17
+ export declare function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection;
16
18
  export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
@@ -128,9 +128,12 @@ function bootOrdinal(row, retained) {
128
128
  }
129
129
  /** All addresses are allocated on the full first-occurrence log, before branch selection. */
130
130
  export function claudeHistoryFromJsonl(text, source) {
131
+ return claudeHistoryFromRows(rowsOf(text), source);
132
+ }
133
+ function claudeHistoryFromRows(rows, source) {
131
134
  const nodes = new Map();
132
135
  let nextSeq = 1;
133
- for (const row of rowsOf(text)) {
136
+ for (const row of rows) {
134
137
  // Ignore non-message records, including future metadata. If selected ancestry
135
138
  // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
136
139
  if (!MESSAGE_TYPES.has(row.type))
@@ -293,8 +296,11 @@ export function claudeHistoryFromJsonl(text, source) {
293
296
  }
294
297
  /** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
295
298
  export function offlineClaudeHead(text) {
299
+ return offlineClaudeHeadFromRows(rowsOf(text));
300
+ }
301
+ function offlineClaudeHeadFromRows(rows) {
296
302
  const latest = new Map();
297
- for (const row of rowsOf(text)) {
303
+ for (const row of rows) {
298
304
  if (!MESSAGE_TYPES.has(row.type))
299
305
  continue;
300
306
  const uuid = requiredString(row.uuid, "uuid");
@@ -334,6 +340,11 @@ export function offlineClaudeHead(text) {
334
340
  const candidates = nonAttachments.length ? nonAttachments : leaves;
335
341
  return candidates.at(-1);
336
342
  }
343
+ /** Select an offline head and build its projection from the same decoded records. */
344
+ export function offlineClaudeHistoryFromJsonl(text, sessionId) {
345
+ const rows = rowsOf(text);
346
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
347
+ }
337
348
  export async function readClaudeHistory(source) {
338
349
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
339
350
  throw new Error("Claude history transcript_path is unavailable");
@@ -2,6 +2,12 @@ export type CodexTranscriptSource = {
2
2
  transcriptPath: string;
3
3
  threadId: string;
4
4
  };
5
+ /** A successful native discovery decision, rechecked before trusting an offline summary. */
6
+ export type CodexLineageSource = {
7
+ home: string;
8
+ rolloutId: string;
9
+ path: string;
10
+ };
5
11
  export type CodexTranscriptState = {
6
12
  threadId: string;
7
13
  rootSessionId: string;
@@ -27,15 +33,21 @@ export type CodexRecord = {
27
33
  /** Native window at this point, absent only when the producer did not persist it. */
28
34
  windowId?: string;
29
35
  };
36
+ export declare const CODEX_TRANSCRIPT_MAX_BYTES: number;
30
37
  export declare function nativeObject(value: unknown, field: string): NativeObject;
31
38
  export declare function nativeString(value: unknown, field: string): string;
32
- /** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
33
- export declare function readCodexTranscriptBytes(path: string, remaining?: number): Promise<Buffer>;
39
+ /** Fingerprints alone cannot detect a newly ambiguous or missing native rollout source. */
40
+ export declare function validateCodexLineageSources(sources: CodexLineageSource[]): Promise<boolean>;
41
+ export type CodexTranscriptReader = (path: string, remaining?: number) => Promise<Buffer>;
42
+ /** One load only: prefilter and lineage decoder share the original decoded Buffers. */
43
+ export declare function createCodexTranscriptReader(): CodexTranscriptReader;
34
44
  /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
35
- export declare function readCodexTranscript(source: CodexTranscriptSource): Promise<{
45
+ export declare function readCodexTranscript(source: CodexTranscriptSource, readBytes?: CodexTranscriptReader): Promise<{
36
46
  state: CodexTranscriptState;
37
47
  records: CodexRecord[];
38
48
  highestSeq: number;
49
+ dependencies: string[];
50
+ lineageSources: CodexLineageSource[];
39
51
  }>;
40
52
  /** Same decoder and ownership as history; no independently guessed boot window. */
41
53
  export declare function readCodexTranscriptState(source: CodexTranscriptSource): Promise<CodexTranscriptState>;
@@ -12,7 +12,8 @@ const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(
12
12
  const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
13
13
  const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
14
14
  // Explicit resource limits, not guessed sequence offsets or partial successful history.
15
- const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
15
+ export const CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
16
+ const MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
16
17
  export function nativeObject(value, field) {
17
18
  if (typeof value !== "object" || value === null || Array.isArray(value))
18
19
  throw new Error(`Invalid Codex ${field}: expected an object`);
@@ -189,34 +190,70 @@ async function referencedPath(home, rolloutId) {
189
190
  throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
190
191
  return matches[0];
191
192
  }
192
- /** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
193
- export async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
194
- const info = await stat(path);
195
- if (!info.isFile() || info.size > remaining)
196
- throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
197
- const bytes = await readFile(path);
198
- // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
199
- if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function")
200
- throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
201
- const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
202
- if (decoded.length > remaining)
203
- throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
204
- return decoded;
193
+ async function resolveLineageSource(home, rolloutId) {
194
+ const path = await realpath(await referencedPath(home, rolloutId));
195
+ if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path)))
196
+ throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
197
+ return path;
198
+ }
199
+ /** Fingerprints alone cannot detect a newly ambiguous or missing native rollout source. */
200
+ export async function validateCodexLineageSources(sources) {
201
+ try {
202
+ for (const source of sources)
203
+ if (await resolveLineageSource(source.home, source.rolloutId) !== source.path)
204
+ return false;
205
+ return true;
206
+ }
207
+ catch {
208
+ return false;
209
+ }
210
+ }
211
+ /** One load only: prefilter and lineage decoder share the original decoded Buffers. */
212
+ export function createCodexTranscriptReader() {
213
+ const cache = new Map();
214
+ return async (path, remaining = CODEX_TRANSCRIPT_MAX_BYTES) => {
215
+ const canonical = await realpath(path);
216
+ let pending = cache.get(canonical);
217
+ if (!pending) {
218
+ pending = (async () => {
219
+ const info = await stat(canonical);
220
+ if (!info.isFile() || info.size > remaining)
221
+ throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
222
+ const stored = await readFile(canonical);
223
+ if (stored.length > remaining)
224
+ throw new Error("Unavailable Codex transcript: read size limit exceeded");
225
+ // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
226
+ if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function")
227
+ throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
228
+ const bytes = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
229
+ return { bytes, storedSize: Math.max(info.size, stored.length) };
230
+ })();
231
+ cache.set(canonical, pending);
232
+ }
233
+ const { bytes, storedSize } = await pending;
234
+ // Reuse never exempts a semantic consumption from its remaining lineage budget.
235
+ if (storedSize > remaining)
236
+ throw new Error("Unavailable Codex transcript: read size limit exceeded");
237
+ if (bytes.length > remaining)
238
+ throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
239
+ return bytes;
240
+ };
205
241
  }
206
242
  /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
207
- export async function readCodexTranscript(source) {
243
+ export async function readCodexTranscript(source, readBytes = createCodexTranscriptReader()) {
208
244
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath)
209
245
  throw new Error("Codex transcript_path is unavailable");
210
246
  id(source.threadId, "requested threadId");
211
247
  try {
212
248
  let path = await realpath(source.transcriptPath), cutoff, home;
213
- let remaining = MAX_BYTES;
249
+ let remaining = CODEX_TRANSCRIPT_MAX_BYTES;
214
250
  const segments = [], seen = new Set();
251
+ const lineageSources = [];
215
252
  while (true) {
216
253
  if (segments.length >= MAX_SEGMENTS || seen.has(path))
217
254
  throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
218
255
  seen.add(path);
219
- const bytes = await readCodexTranscriptBytes(path, remaining);
256
+ const bytes = await readBytes(path, remaining);
220
257
  remaining -= bytes.length;
221
258
  const segment = segmentFromBytes(bytes, cutoff);
222
259
  if (segments.length === 0 && segment.meta.id !== source.threadId)
@@ -233,9 +270,8 @@ export async function readCodexTranscript(source) {
233
270
  if (base.end_ordinal_exclusive === 0)
234
271
  throw new Error("Invalid Codex lineage: history_base must include source metadata");
235
272
  home ??= storageHome(path);
236
- path = await realpath(await referencedPath(home, base.thread_id));
237
- if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path)))
238
- throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
273
+ path = await resolveLineageSource(home, base.thread_id);
274
+ lineageSources.push({ home, rolloutId: base.thread_id, path });
239
275
  cutoff = base;
240
276
  }
241
277
  // history_base is physical; forked_from_ordinal_exclusive is the logical
@@ -304,7 +340,7 @@ export async function readCodexTranscript(source) {
304
340
  // compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
305
341
  if (settingsModel ?? contextModel)
306
342
  state.model = settingsModel ?? contextModel;
307
- return { state, records, highestSeq: lastSeq };
343
+ return { state, records, highestSeq: lastSeq, dependencies: [...seen], lineageSources };
308
344
  }
309
345
  catch (error) {
310
346
  throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
@@ -1,8 +1,10 @@
1
1
  /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
2
  import { type HistoryProjection } from "./history.js";
3
- import { type CodexTranscriptSource, type CodexTranscriptState } from "./codex-transcript.js";
3
+ import { type CodexLineageSource, type CodexTranscriptReader, type CodexTranscriptSource, type CodexTranscriptState } from "./codex-transcript.js";
4
4
  export type { CodexTranscriptSource } from "./codex-transcript.js";
5
5
  export type CodexHistoryState = CodexTranscriptState & {
6
6
  projection: HistoryProjection;
7
+ dependencies: string[];
8
+ lineageSources: CodexLineageSource[];
7
9
  };
8
- export declare function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState>;
10
+ export declare function readCodexHistory(source: CodexTranscriptSource, readBytes?: CodexTranscriptReader): Promise<CodexHistoryState>;
@@ -110,8 +110,8 @@ function standaloneTool(record, item) {
110
110
  const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
111
111
  return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
112
112
  }
113
- export async function readCodexHistory(source) {
114
- const { state, records, highestSeq } = await readCodexTranscript(source);
113
+ export async function readCodexHistory(source, readBytes) {
114
+ const { state, records, highestSeq, dependencies, lineageSources } = await readCodexTranscript(source, readBytes);
115
115
  const facts = new Map(), callsSeen = new Set(), responseIdsSeen = new Set();
116
116
  const windows = new Map(), branchSeqs = new Set();
117
117
  const addWindow = (nativeId, createdAt) => {
@@ -234,5 +234,5 @@ export async function readCodexHistory(source) {
234
234
  if (item)
235
235
  addWindow(record.windowId).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
236
236
  }
237
- return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
237
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs), dependencies, lineageSources };
238
238
  }
@@ -1,16 +1,22 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
2
  import { type Outcome } from "../tools/result.js";
3
- import type { HistoryProjection } from "./history.js";
3
+ import type { HistoryEvent, HistoryProjection } from "./history.js";
4
4
  export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
5
5
  export type HistorySessionData = {
6
6
  projection: HistoryProjection;
7
7
  notice?: string;
8
8
  };
9
+ export type HistorySessionRepresentative = {
10
+ event: HistoryEvent | undefined;
11
+ notice?: string;
12
+ };
9
13
  export type HistorySession = {
10
14
  harness: HistoryHarness;
11
15
  id: string;
12
16
  modifiedAt: number;
13
17
  load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
18
+ /** Strict, unfiltered overview only; never used for a live binding or filtered history. */
19
+ loadRepresentative?(): Promise<HistorySessionRepresentative>;
14
20
  };
15
21
  export type HistoryCorpus = {
16
22
  currentHarness: HistoryHarness;
@@ -31,6 +37,7 @@ export declare function parseSessionSelector(value: string): Outcome<SessionSele
31
37
  /** '*' is the only metacharacter; all other characters match literally. */
32
38
  export declare function matchesSession(session: HistorySession, selector: SessionSelector): boolean;
33
39
  export declare function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>>;
40
+ export declare function loadHistoryRepresentative(session: HistorySession): Promise<Outcome<HistorySessionRepresentative>>;
34
41
  export declare function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
35
42
  export declare function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
36
43
  export declare function currentHistory(context: HistoryContext): HistoryProjection | Promise<HistoryProjection>;
@@ -1,5 +1,6 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
2
  import { failure, success } from "../tools/result.js";
3
+ import { sessionRepresentative } from "./query.js";
3
4
  const HARNESSES = new Set(["pi", "claude", "codex", "dsh"]);
4
5
  export function sessionIdentity(session) {
5
6
  return `${session.harness}:${session.id}`;
@@ -41,6 +42,21 @@ export async function resolveSession(corpus, selector) {
41
42
  return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
42
43
  return success(matches[0]);
43
44
  }
45
+ export async function loadHistoryRepresentative(session) {
46
+ if (session.loadRepresentative) {
47
+ try {
48
+ return success(await session.loadRepresentative());
49
+ }
50
+ catch (error) {
51
+ return unavailableSession(session, error);
52
+ }
53
+ }
54
+ const result = await loadHistorySession(session);
55
+ return result.ok ? success({ event: sessionRepresentative(result.data.projection, {}), notice: result.data.notice }) : result;
56
+ }
57
+ function unavailableSession(session, error) {
58
+ return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
59
+ }
44
60
  export async function loadHistorySession(session, queries) {
45
61
  try {
46
62
  const data = await session.load(queries);
@@ -49,7 +65,7 @@ export async function loadHistorySession(session, queries) {
49
65
  return success(data);
50
66
  }
51
67
  catch (error) {
52
- return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
68
+ return unavailableSession(session, error);
53
69
  }
54
70
  }
55
71
  export function currentHistory(context) {
@@ -110,6 +110,15 @@ export declare function toolSummary(event: HistoryEvent): Static<typeof ToolSumm
110
110
  export declare function nestedCallSummary(event: HistoryEvent): {
111
111
  nested_calls?: Static<typeof NestedCallSummarySchema>;
112
112
  };
113
+ /** A run of tool/context events the conversation view replaces with counts. */
114
+ export declare const HistoryFoldedRowSchema: Type.TObject<{
115
+ session: Type.TOptional<Type.TString>;
116
+ first_seq: Type.TInteger;
117
+ last_seq: Type.TInteger;
118
+ count: Type.TInteger;
119
+ tools: Type.TRecord<"^.*$", Type.TInteger>;
120
+ }>;
121
+ export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
113
122
  /** Stable identity and a verbatim preview, starting at the search match when present. */
114
123
  export declare const HistoryPageItemSchema: Type.TObject<{
115
124
  content: Type.TString;
@@ -120,21 +129,18 @@ export declare const HistoryPageItemSchema: Type.TObject<{
120
129
  output_truncated: Type.TOptional<Type.TLiteral<true>>;
121
130
  full_output_path: Type.TOptional<Type.TString>;
122
131
  session: Type.TOptional<Type.TString>;
132
+ folded_before: Type.TOptional<Type.TObject<{
133
+ session: Type.TOptional<Type.TString>;
134
+ first_seq: Type.TInteger;
135
+ last_seq: Type.TInteger;
136
+ count: Type.TInteger;
137
+ tools: Type.TRecord<"^.*$", Type.TInteger>;
138
+ }>>;
123
139
  seq: Type.TInteger;
124
140
  role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
125
141
  created_at: Type.TUnion<[Type.TString, Type.TNull]>;
126
142
  }>;
127
143
  export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
128
- /** A run of tool/context events the conversation view replaces with counts. */
129
- export declare const HistoryFoldedRowSchema: Type.TObject<{
130
- session: Type.TOptional<Type.TString>;
131
- folded: Type.TLiteral<true>;
132
- first_seq: Type.TInteger;
133
- last_seq: Type.TInteger;
134
- count: Type.TInteger;
135
- tools: Type.TRecord<"^.*$", Type.TInteger>;
136
- }>;
137
- export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
138
144
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
139
145
  export declare const MAX_FOLD_TOOL_NAMES = 20;
140
146
  /** Longest tool name a fold row lists. */
@@ -134,9 +134,18 @@ export function nestedCallSummary(event) {
134
134
  const nested = event.execution?.nestedCalls;
135
135
  return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
136
136
  }
137
+ /** A run of tool/context events the conversation view replaces with counts. */
138
+ export const HistoryFoldedRowSchema = Type.Object({
139
+ session: Type.Optional(Type.String()),
140
+ first_seq: Type.Integer({ minimum: 1 }),
141
+ last_seq: Type.Integer({ minimum: 1 }),
142
+ count: Type.Integer({ minimum: 1 }),
143
+ tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
144
+ }, { additionalProperties: false });
137
145
  /** Stable identity and a verbatim preview, starting at the search match when present. */
138
146
  export const HistoryPageItemSchema = Type.Object({
139
147
  session: Type.Optional(Type.String()),
148
+ folded_before: Type.Optional(HistoryFoldedRowSchema),
140
149
  seq: Type.Integer({ minimum: 1 }),
141
150
  role: HistoryRoleSchema,
142
151
  created_at: Type.Union([Type.String(), Type.Null()]),
@@ -145,15 +154,6 @@ export const HistoryPageItemSchema = Type.Object({
145
154
  truncated: Type.Boolean({ description: "Preview is partial." }),
146
155
  offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
147
156
  }, { additionalProperties: false });
148
- /** A run of tool/context events the conversation view replaces with counts. */
149
- export const HistoryFoldedRowSchema = Type.Object({
150
- session: Type.Optional(Type.String()),
151
- folded: Type.Literal(true),
152
- first_seq: Type.Integer({ minimum: 1 }),
153
- last_seq: Type.Integer({ minimum: 1 }),
154
- count: Type.Integer({ minimum: 1 }),
155
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
156
- }, { additionalProperties: false });
157
157
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
158
158
  export const MAX_FOLD_TOOL_NAMES = 20;
159
159
  /** Longest tool name a fold row lists. */
@@ -6,6 +6,8 @@ export type LocalHistoryOptions = {
6
6
  roots?: LocalHistoryRoots;
7
7
  home?: string;
8
8
  env?: NodeJS.ProcessEnv;
9
+ /** Internal hermetic-test seam, not a tool parameter or host setting. */
10
+ summaryCacheRoot?: string;
9
11
  /** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
10
12
  dshSessions?: () => Promise<HistorySession[]>;
11
13
  };