notesoup 0.56.1 → 0.57.1

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 (60) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/entries.d.ts +0 -1
  3. package/dist/plugins/pi/entries.js +0 -1
  4. package/dist/plugins/pi/reset/lifecycle.d.ts +2 -1
  5. package/dist/plugins/pi/reset/lifecycle.js +19 -36
  6. package/dist/plugins/pi/runtime.js +14 -10
  7. package/dist/plugins/pi/text.d.ts +0 -2
  8. package/dist/plugins/pi/text.js +2 -6
  9. package/dist/src/history/claude.d.ts +2 -0
  10. package/dist/src/history/claude.js +13 -2
  11. package/dist/src/history/codex-transcript.d.ts +15 -3
  12. package/dist/src/history/codex-transcript.js +57 -21
  13. package/dist/src/history/codex.d.ts +4 -2
  14. package/dist/src/history/codex.js +3 -3
  15. package/dist/src/history/corpus.d.ts +8 -1
  16. package/dist/src/history/corpus.js +17 -1
  17. package/dist/src/history/history.d.ts +16 -10
  18. package/dist/src/history/history.js +9 -9
  19. package/dist/src/history/local.d.ts +2 -0
  20. package/dist/src/history/local.js +35 -38
  21. package/dist/src/history/prefilter.d.ts +5 -0
  22. package/dist/src/history/prefilter.js +95 -0
  23. package/dist/src/history/query.d.ts +29 -27
  24. package/dist/src/history/query.js +82 -34
  25. package/dist/src/history/summary-cache.d.ts +10 -0
  26. package/dist/src/history/summary-cache.js +129 -0
  27. package/dist/src/tools/history.js +31 -20
  28. package/dist/test/agent-loop.test.js +143 -110
  29. package/dist/test/codex-history.test.js +90 -4
  30. package/dist/test/codex-plugin.test.js +6 -2
  31. package/dist/test/history-corpus.test.js +221 -33
  32. package/dist/test/history-prefilter.test.d.ts +1 -0
  33. package/dist/test/history-prefilter.test.js +174 -0
  34. package/dist/test/history-summary-cache.test.d.ts +1 -0
  35. package/dist/test/history-summary-cache.test.js +297 -0
  36. package/dist/test/history.integration.test.js +87 -52
  37. package/dist/test/marker.test.js +1 -1
  38. package/dist/test/model-facing-text.test.js +3 -4
  39. package/dist/test/reset-lifecycle.test.js +52 -12
  40. package/docs/history-sessions.md +26 -2
  41. package/docs/reset-lifecycle.md +14 -13
  42. package/docs/tool-results.md +4 -2
  43. package/package.json +1 -1
  44. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  45. package/plugins/claude/dist/claude/helper.js +425 -122
  46. package/plugins/codex/dist/codex/notesoup.js +423 -123
  47. package/plugins/pi/entries.ts +0 -1
  48. package/plugins/pi/reset/lifecycle.ts +19 -35
  49. package/plugins/pi/runtime.ts +14 -10
  50. package/plugins/pi/text.ts +2 -7
  51. package/src/history/claude.ts +16 -2
  52. package/src/history/codex-transcript.ts +52 -17
  53. package/src/history/codex.ts +5 -5
  54. package/src/history/corpus.ts +19 -2
  55. package/src/history/history.ts +11 -11
  56. package/src/history/local.ts +34 -38
  57. package/src/history/prefilter.ts +86 -0
  58. package/src/history/query.ts +77 -33
  59. package/src/history/summary-cache.ts +119 -0
  60. package/src/tools/history.ts +33 -20
@@ -6,5 +6,4 @@ export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
8
8
  export const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
- export const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
10
9
  export const MARKER_TYPE = "notesoup/marker";
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
3
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
4
3
  import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
@@ -9,8 +8,6 @@ import { resetBoundaryCommitted } from "./committed.js";
9
8
  import type { ResetOrigin } from "../../../src/budget/text.js";
10
9
  import { errorMessage } from "../../../src/error-message.js";
11
10
  import { carriedInputDrafts, isCarriedInputEntry, type CarriedInput } from "./artifacts.js";
12
- import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
13
- import { promptBlock } from "../text.js";
14
11
 
15
12
  type BudgetOwner = {
16
13
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
@@ -87,13 +84,14 @@ export type ResetControlEvent =
87
84
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
88
85
 
89
86
  /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
90
- * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
87
+ * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
91
88
  export interface ResetBoundaryIntent {
92
89
  readonly effect: "build-boundary";
93
90
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
94
91
  readonly windowId: string;
95
92
  readonly continueAfterReset: boolean;
96
93
  readonly origin: ResetOrigin;
94
+ readonly carryRunInputs?: boolean;
97
95
  readonly tool?: { readonly lastWord?: string };
98
96
  }
99
97
 
@@ -106,16 +104,16 @@ function requestForWindow(request: ResetRequest, windowId: string): ResetRequest
106
104
 
107
105
  const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
108
106
 
109
- function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
107
+ function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"], carryRunInputs = false): ResetBoundaryIntent {
110
108
  const tool = request.phase === "none" ? undefined : request.tool;
111
109
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
112
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
110
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
113
111
  }
114
112
 
115
113
  /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
116
114
  export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest, passiveInputs: readonly CarriedInput[] = []) {
117
115
  const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
118
- : intent.boundary === "overflow-recovery" ? passiveInputs : [];
116
+ : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
119
117
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
120
118
  const state: ResetControlState = {
121
119
  request: NO_REQUEST,
@@ -170,8 +168,9 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
170
168
  }
171
169
  // A direct tool request commits after the whole tool batch. The budget cutoff is
172
170
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
173
- if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
174
- return boundaryIntent(request, facts.windowId, "turn-end");
171
+ const toolReset = request.phase === "pending" && request.tool !== undefined;
172
+ if ((toolReset && !manual) || facts.hardReserveDue) {
173
+ return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
175
174
  }
176
175
  return { state: { request, overflow: "idle" }, effect: "none" };
177
176
  }
@@ -220,17 +219,16 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
220
219
  let lifecycleGeneration = 0;
221
220
  let control = initialResetControl();
222
221
  let runInputs: CarriedInput[] = [];
223
- let commandId: string | undefined;
224
222
 
225
223
  // Once input returns handled, Pi no longer owns its original content. If close-out
226
- // fails/cancels, return that content to the transcript without starting another run.
227
- const restoreCommandInputs = () => {
224
+ // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
225
+ const restoreCommandInputs = (triggerTurn = false) => {
228
226
  const request = control.request;
229
227
  if (request.phase !== "pending" || !request.command?.inputs?.length) return;
230
228
  const inputs = request.command.inputs;
231
229
  control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
232
230
  for (const draft of carriedInputDrafts(inputs)) {
233
- pi.sendMessage(draft, { triggerTurn: false });
231
+ pi.sendMessage(draft, { triggerTurn });
234
232
  }
235
233
  runInputs.push(...inputs);
236
234
  };
@@ -239,11 +237,9 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
239
237
  if (preserveInputs) restoreCommandInputs();
240
238
  control = initialResetControl();
241
239
  runInputs = [];
242
- commandId = undefined;
243
240
  };
244
241
  const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
245
- // Keep command state live while notes load: input arriving during this await must
246
- // join this very boundary even if its steer cannot reach the closing model.
242
+ // Keep command state live while notes load so input arriving during this await joins this boundary.
247
243
  const generation = lifecycleGeneration;
248
244
  const outerGeneration = options.getLifecycleGeneration?.();
249
245
  const sessionId = ctx.sessionManager.getSessionId();
@@ -281,10 +277,6 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
281
277
  ? [{ type: "text", text: event.text }, ...event.images]
282
278
  : event.text;
283
279
  control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
284
- const steerContent: CarriedInput = event.images?.length
285
- ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
286
- : promptBlock(event.text);
287
- pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
288
280
  return { action: "handled" };
289
281
  });
290
282
 
@@ -292,23 +284,13 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
292
284
  // safety reset is actually committed, cancel that empty follow-up before provider
293
285
  // work. Real queued user input is allowed through and answered before settlement.
294
286
  pi.on("context_with_system", (event, ctx) => {
295
- const request = control.request;
296
- // Steering can be queued during buildReset's await and arrive after the boundary.
297
- // It is closing-model context only; originals already live in the carried entries.
298
- const messages = event.messages.filter((message) => {
299
- if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE) return true;
300
- const details = message.details as { windowId?: unknown; commandId?: unknown } | undefined;
301
- return request.phase === "pending" && request.command !== undefined &&
302
- request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
303
- });
304
- const filtered = messages.length === event.messages.length ? undefined : { messages };
305
287
  const stop = control.stopAfterReset;
306
- if (!sessionActive || !stop || ctx.hasPendingMessages()) return filtered;
288
+ if (!sessionActive || !stop || ctx.hasPendingMessages()) return undefined;
307
289
  const marker = currentReset(ctx);
308
- if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return filtered;
290
+ if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
309
291
  const branch = ctx.sessionManager.getBranch();
310
292
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
311
- if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return filtered;
293
+ if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return undefined;
312
294
  ctx.abort();
313
295
  const system = getCurrentSystemMessage(event.messages);
314
296
  return { messages: system ? [system] : [] };
@@ -334,8 +316,11 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
334
316
  },
335
317
  });
336
318
  if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
337
- if (aborted || (event.outcome === "error" && decision.state.request.phase === "none")) restoreCommandInputs();
319
+ if (aborted) restoreCommandInputs();
320
+ else if (event.outcome === "error" && decision.state.request.phase === "none") restoreCommandInputs(true);
338
321
  control = decision.state;
322
+ if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
323
+ event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages()) runInputs = [];
339
324
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
340
325
  const marker = buildMarkerDraft(ctx, entries);
341
326
  if (marker) entries.push(marker);
@@ -390,7 +375,6 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
390
375
  command(windowId: string, continueAfterReset: boolean, input?: CarriedInput) {
391
376
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
392
377
  control = decision.state;
393
- if (decision.effect === "close-out-armed") commandId = randomUUID();
394
378
  return decision.effect;
395
379
  },
396
380
  request(windowId: string, lastWord?: string) {
@@ -3,7 +3,7 @@ import { resetBoundaryCommitted } from "./reset/committed.js";
3
3
  import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type SettingsManager } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
- import { output } from "./tool-result.js";
6
+ import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE, output } from "./tool-result.js";
7
7
  import { emptyBrainRenderers } from "./render.js";
8
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
9
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
@@ -24,6 +24,9 @@ function readPackageVersion(): string {
24
24
  }
25
25
 
26
26
  const buildLabel = `v${readPackageVersion()}`;
27
+ const notesoupTools = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE]
28
+ .map(({ name, description }) => `${name}: ${description}`)
29
+ .join("\n") + "\nDiscover deferred tools through codemode or tool_search when available.";
27
30
 
28
31
  function branchHasWindowMarker(ctx: ExtensionContext, fromId?: string): boolean {
29
32
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
@@ -77,7 +80,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
77
80
  if (markerResetOrigin(marker) === "forced") ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
78
81
  }
79
82
  };
80
- pi.on("before_agent_start", (_event, ctx) => {
83
+ pi.on("before_agent_start", (event, ctx) => {
84
+ event.systemPromptOptions.sections.notesoup_tools = notesoupTools;
81
85
  if (enabled) maybeSendMarker(pi, ctx);
82
86
  });
83
87
  pi.on("turn_start", (_event, ctx) => {
@@ -170,8 +174,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
170
174
  },
171
175
  });
172
176
 
173
- const emptyBrainCommand = {
174
- description: "Flush memory to notes and continue in a fresh window; optional prompt runs there",
177
+ const emptyBrainCommand = (name: "empty" | "fresh-window") => ({
178
+ description: "Flush memory to notes, reset, and stop; optional text provides close-out context",
175
179
  handler: async (args: string, cmdCtx: ExtensionCommandContext) => {
176
180
  if (!enabled) {
177
181
  cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
@@ -182,26 +186,26 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
182
186
  await cmdCtx.waitForIdle();
183
187
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId) return;
184
188
  }
185
- // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
189
+ // Manual wipes close out at settlement, then stop unless later human input arrives. The hidden warning is triggered when idle,
186
190
  // steered into the running turn when busy — so the agent closes out promptly
187
191
  // instead of the reset waiting for the whole run.
188
192
  const prompt = args.trim() ? args : undefined;
189
- const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
193
+ const armed = resets.command(requestedWindowId, false);
190
194
  if (armed === "already-pending") {
191
195
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
192
196
  return;
193
197
  }
194
198
  cmdCtx.ui.notify("🥣 Dumping Brain", "info");
195
199
  try {
196
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
200
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/${name} ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
197
201
  } catch (error) {
198
202
  resets.clear();
199
203
  cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
200
204
  }
201
205
  },
202
- };
203
- pi.registerCommand("empty", emptyBrainCommand);
204
- pi.registerCommand("fresh-window", emptyBrainCommand);
206
+ });
207
+ pi.registerCommand("empty", emptyBrainCommand("empty"));
208
+ pi.registerCommand("fresh-window", emptyBrainCommand("fresh-window"));
205
209
 
206
210
  pi.registerTool(defineTool({
207
211
  name: "empty_brain",
@@ -16,19 +16,14 @@ export function markerContent(seq: number): string {
16
16
  return `<notesoup:marker seq="${seq}" />`;
17
17
  }
18
18
 
19
- /** The closing model sees deferred input as a bare next-window prompt block. */
20
- export function promptBlock(commandLine: string): string {
21
- return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
22
- }
23
-
24
19
  /** Approved manual close-out notices; both variants live here. */
25
20
  export const COMMAND_NOTICE = {
26
- 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.",
27
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.",
28
23
  };
29
24
 
30
25
  /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
31
26
  export function commandWarningContent(commandLine?: string): string {
32
27
  const notice = commandLine ? COMMAND_NOTICE.prompted : COMMAND_NOTICE.bare;
33
- return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${promptBlock(commandLine)}` : ""}`;
28
+ return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${commandLine}` : ""}`;
34
29
  }
@@ -115,9 +115,13 @@ function bootOrdinal(row: Row, retained: boolean): number | undefined {
115
115
 
116
116
  /** All addresses are allocated on the full first-occurrence log, before branch selection. */
117
117
  export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection {
118
+ return claudeHistoryFromRows(rowsOf(text), source);
119
+ }
120
+
121
+ function claudeHistoryFromRows(rows: Row[], source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection {
118
122
  const nodes = new Map<string, Node>();
119
123
  let nextSeq = 1;
120
- for (const row of rowsOf(text)) {
124
+ for (const row of rows) {
121
125
  // Ignore non-message records, including future metadata. If selected ancestry
122
126
  // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
123
127
  if (!MESSAGE_TYPES.has(row.type as string)) continue;
@@ -253,8 +257,12 @@ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistoryS
253
257
 
254
258
  /** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
255
259
  export function offlineClaudeHead(text: string): string {
260
+ return offlineClaudeHeadFromRows(rowsOf(text));
261
+ }
262
+
263
+ function offlineClaudeHeadFromRows(rows: Row[]): string {
256
264
  const latest = new Map<string, Row>();
257
- for (const row of rowsOf(text)) {
265
+ for (const row of rows) {
258
266
  if (!MESSAGE_TYPES.has(row.type as string)) continue;
259
267
  const uuid = requiredString(row.uuid, "uuid");
260
268
  latest.delete(uuid);
@@ -285,6 +293,12 @@ export function offlineClaudeHead(text: string): string {
285
293
  return candidates.at(-1)!;
286
294
  }
287
295
 
296
+ /** Select an offline head and build its projection from the same decoded records. */
297
+ export function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection {
298
+ const rows = rowsOf(text);
299
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
300
+ }
301
+
288
302
  export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
289
303
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
290
304
  return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
@@ -8,6 +8,8 @@ import { basename, dirname, join, relative, sep } from "node:path";
8
8
  import * as zlib from "node:zlib";
9
9
 
10
10
  export type CodexTranscriptSource = { transcriptPath: string; threadId: string };
11
+ /** A successful native discovery decision, rechecked before trusting an offline summary. */
12
+ export type CodexLineageSource = { home: string; rolloutId: string; path: string };
11
13
  export type CodexTranscriptState = {
12
14
  threadId: string;
13
15
  rootSessionId: string;
@@ -41,7 +43,8 @@ const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(
41
43
  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"]);
42
44
  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"]);
43
45
  // Explicit resource limits, not guessed sequence offsets or partial successful history.
44
- const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
46
+ export const CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
47
+ const MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
45
48
  export function nativeObject(value: unknown, field: string): NativeObject {
46
49
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an object`);
47
50
  return value as NativeObject;
@@ -172,30 +175,62 @@ async function referencedPath(home: string, rolloutId: string): Promise<string>
172
175
  if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
173
176
  return matches[0]!;
174
177
  }
175
- /** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
176
- export async function readCodexTranscriptBytes(path: string, remaining = MAX_BYTES): Promise<Buffer> {
177
- const info = await stat(path);
178
- if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
179
- const bytes = await readFile(path);
180
- // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
181
- if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
182
- const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
183
- if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
184
- return decoded;
178
+ async function resolveLineageSource(home: string, rolloutId: string): Promise<string> {
179
+ const path = await realpath(await referencedPath(home, rolloutId));
180
+ if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
181
+ return path;
182
+ }
183
+
184
+ /** Fingerprints alone cannot detect a newly ambiguous or missing native rollout source. */
185
+ export async function validateCodexLineageSources(sources: CodexLineageSource[]): Promise<boolean> {
186
+ try {
187
+ for (const source of sources) if (await resolveLineageSource(source.home, source.rolloutId) !== source.path) return false;
188
+ return true;
189
+ } catch { return false; }
190
+ }
191
+
192
+ export type CodexTranscriptReader = (path: string, remaining?: number) => Promise<Buffer>;
193
+
194
+ /** One load only: prefilter and lineage decoder share the original decoded Buffers. */
195
+ export function createCodexTranscriptReader(): CodexTranscriptReader {
196
+ const cache = new Map<string, Promise<{ bytes: Buffer; storedSize: number }>>();
197
+ return async (path, remaining = CODEX_TRANSCRIPT_MAX_BYTES) => {
198
+ const canonical = await realpath(path);
199
+ let pending = cache.get(canonical);
200
+ if (!pending) {
201
+ pending = (async () => {
202
+ const info = await stat(canonical);
203
+ if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
204
+ const stored = await readFile(canonical);
205
+ if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
206
+ // 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
207
+ if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
208
+ const bytes = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
209
+ return { bytes, storedSize: Math.max(info.size, stored.length) };
210
+ })();
211
+ cache.set(canonical, pending);
212
+ }
213
+ const { bytes, storedSize } = await pending;
214
+ // Reuse never exempts a semantic consumption from its remaining lineage budget.
215
+ if (storedSize > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
216
+ if (bytes.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
217
+ return bytes;
218
+ };
185
219
  }
186
220
 
187
221
  /** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
188
- export async function readCodexTranscript(source: CodexTranscriptSource): Promise<{ state: CodexTranscriptState; records: CodexRecord[]; highestSeq: number }> {
222
+ export async function readCodexTranscript(source: CodexTranscriptSource, readBytes = createCodexTranscriptReader()): Promise<{ state: CodexTranscriptState; records: CodexRecord[]; highestSeq: number; dependencies: string[]; lineageSources: CodexLineageSource[] }> {
189
223
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
190
224
  id(source.threadId, "requested threadId");
191
225
  try {
192
226
  let path = await realpath(source.transcriptPath), cutoff: Position | undefined, home: string | undefined;
193
- let remaining = MAX_BYTES;
227
+ let remaining = CODEX_TRANSCRIPT_MAX_BYTES;
194
228
  const segments: Segment[] = [], seen = new Set<string>();
229
+ const lineageSources: CodexLineageSource[] = [];
195
230
  while (true) {
196
231
  if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
197
232
  seen.add(path);
198
- const bytes = await readCodexTranscriptBytes(path, remaining);
233
+ const bytes = await readBytes(path, remaining);
199
234
  remaining -= bytes.length;
200
235
  const segment = segmentFromBytes(bytes, cutoff);
201
236
  if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
@@ -208,8 +243,8 @@ export async function readCodexTranscript(source: CodexTranscriptSource): Promis
208
243
  if (!base) break;
209
244
  if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
210
245
  home ??= storageHome(path);
211
- path = await realpath(await referencedPath(home, base.thread_id));
212
- if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
246
+ path = await resolveLineageSource(home, base.thread_id);
247
+ lineageSources.push({ home, rolloutId: base.thread_id, path });
213
248
  cutoff = base;
214
249
  }
215
250
  // history_base is physical; forked_from_ordinal_exclusive is the logical
@@ -265,7 +300,7 @@ export async function readCodexTranscript(source: CodexTranscriptSource): Promis
265
300
  // Native latest model settings win over a frozen companion TurnContext after
266
301
  // compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
267
302
  if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
268
- return { state, records, highestSeq: lastSeq };
303
+ return { state, records, highestSeq: lastSeq, dependencies: [...seen], lineageSources };
269
304
  } catch (error) {
270
305
  throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
271
306
  }
@@ -1,8 +1,8 @@
1
1
  /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
2
  import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
3
- import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./codex-transcript.js";
3
+ import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexLineageSource, type CodexTranscriptReader, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./codex-transcript.js";
4
4
  export type { CodexTranscriptSource } from "./codex-transcript.js";
5
- export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection };
5
+ export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection; dependencies: string[]; lineageSources: CodexLineageSource[] };
6
6
 
7
7
  const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
8
8
  const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
@@ -104,8 +104,8 @@ function standaloneTool(record: CodexRecord, item: NativeObject): DecodedHistory
104
104
  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" };
105
105
  }
106
106
 
107
- export async function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState> {
108
- const { state, records, highestSeq } = await readCodexTranscript(source);
107
+ export async function readCodexHistory(source: CodexTranscriptSource, readBytes?: CodexTranscriptReader): Promise<CodexHistoryState> {
108
+ const { state, records, highestSeq, dependencies, lineageSources } = await readCodexTranscript(source, readBytes);
109
109
  const facts = new Map<string, ToolFact>(), callsSeen = new Set<string>(), responseIdsSeen = new Set<string>();
110
110
  const windows = new Map<string, DecodedHistoryWindow>(), branchSeqs = new Set<number>();
111
111
  const addWindow = (nativeId: string, createdAt?: string): DecodedHistoryWindow => {
@@ -189,5 +189,5 @@ export async function readCodexHistory(source: CodexTranscriptSource): Promise<C
189
189
  }
190
190
  if (item) addWindow(record.windowId!).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
191
191
  }
192
- return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
192
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs), dependencies, lineageSources };
193
193
  }
@@ -1,14 +1,18 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
2
  import { failure, success, type Outcome } from "../tools/result.js";
3
- import type { HistoryProjection } from "./history.js";
3
+ import type { HistoryEvent, HistoryProjection } from "./history.js";
4
+ import { sessionRepresentative } from "./query.js";
4
5
 
5
6
  export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
6
7
  export type HistorySessionData = { projection: HistoryProjection; notice?: string };
8
+ export type HistorySessionRepresentative = { event: HistoryEvent | undefined; notice?: string };
7
9
  export type HistorySession = {
8
10
  harness: HistoryHarness;
9
11
  id: string;
10
12
  modifiedAt: number;
11
13
  load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
14
+ /** Strict, unfiltered overview only; never used for a live binding or filtered history. */
15
+ loadRepresentative?(): Promise<HistorySessionRepresentative>;
12
16
  };
13
17
  export type HistoryCorpus = {
14
18
  currentHarness: HistoryHarness;
@@ -57,6 +61,19 @@ export async function resolveSession(corpus: HistoryCorpus | undefined, selector
57
61
  return success(matches[0]!);
58
62
  }
59
63
 
64
+ export async function loadHistoryRepresentative(session: HistorySession): Promise<Outcome<HistorySessionRepresentative>> {
65
+ if (session.loadRepresentative) {
66
+ try { return success(await session.loadRepresentative()); }
67
+ catch (error) { return unavailableSession(session, error); }
68
+ }
69
+ const result = await loadHistorySession(session);
70
+ return result.ok ? success({ event: sessionRepresentative(result.data.projection, {}), notice: result.data.notice }) : result;
71
+ }
72
+
73
+ function unavailableSession(session: HistorySession, error: unknown): Outcome<never> {
74
+ return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
75
+ }
76
+
60
77
  export function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
61
78
  export function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
62
79
  export async function loadHistorySession(session: HistorySession, queries?: readonly string[]): Promise<Outcome<HistorySessionData | undefined>> {
@@ -66,7 +83,7 @@ export async function loadHistorySession(session: HistorySession, queries?: read
66
83
  return success(data);
67
84
  }
68
85
  catch (error) {
69
- return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
86
+ return unavailableSession(session, error);
70
87
  }
71
88
  }
72
89
 
@@ -207,9 +207,20 @@ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<
207
207
  return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
208
208
  }
209
209
 
210
+ /** A run of tool/context events the conversation view replaces with counts. */
211
+ export const HistoryFoldedRowSchema = Type.Object({
212
+ session: Type.Optional(Type.String()),
213
+ first_seq: Type.Integer({ minimum: 1 }),
214
+ last_seq: Type.Integer({ minimum: 1 }),
215
+ count: Type.Integer({ minimum: 1 }),
216
+ tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
217
+ }, { additionalProperties: false });
218
+ export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
219
+
210
220
  /** Stable identity and a verbatim preview, starting at the search match when present. */
211
221
  export const HistoryPageItemSchema = Type.Object({
212
222
  session: Type.Optional(Type.String()),
223
+ folded_before: Type.Optional(HistoryFoldedRowSchema),
213
224
  seq: Type.Integer({ minimum: 1 }),
214
225
  role: HistoryRoleSchema,
215
226
  created_at: Type.Union([Type.String(), Type.Null()]),
@@ -220,17 +231,6 @@ export const HistoryPageItemSchema = Type.Object({
220
231
  }, { additionalProperties: false });
221
232
  export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
222
233
 
223
- /** A run of tool/context events the conversation view replaces with counts. */
224
- export const HistoryFoldedRowSchema = Type.Object({
225
- session: Type.Optional(Type.String()),
226
- folded: Type.Literal(true),
227
- first_seq: Type.Integer({ minimum: 1 }),
228
- last_seq: Type.Integer({ minimum: 1 }),
229
- count: Type.Integer({ minimum: 1 }),
230
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
231
- }, { additionalProperties: false });
232
- export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
233
-
234
234
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
235
235
  export const MAX_FOLD_TOOL_NAMES = 20;
236
236