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
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:
@@ -6,5 +6,4 @@ export declare const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export declare const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export declare const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
8
8
  export declare const CARRIED_INPUT_TYPE = "notesoup/carried-input";
9
- export declare const NEXT_WINDOW_PROMPT_TYPE = "notesoup/next-window-prompt";
10
9
  export declare const MARKER_TYPE = "notesoup/marker";
@@ -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";
@@ -76,13 +76,14 @@ export type ResetControlEvent = {
76
76
  readonly facts: ResetBeforeSettleFacts;
77
77
  };
78
78
  /** Construction intent, not final state: handled inputs can still arrive while notes load. Only `turn-end`
79
- * may latch a stop; overflow kinds spend recovery; only `overflow-recovery` carries passive run inputs. */
79
+ * may latch a stop; overflow kinds spend recovery; only hard-reserve and overflow carry passive run inputs. */
80
80
  export interface ResetBoundaryIntent {
81
81
  readonly effect: "build-boundary";
82
82
  readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
83
83
  readonly windowId: string;
84
84
  readonly continueAfterReset: boolean;
85
85
  readonly origin: ResetOrigin;
86
+ readonly carryRunInputs?: boolean;
86
87
  readonly tool?: {
87
88
  readonly lastWord?: string;
88
89
  };
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
2
  import { currentReset, currentWindowId } from "../window.js";
4
3
  import { nextHistorySeq } from "../history.js";
@@ -6,8 +5,6 @@ import { buildMarkerDraft } from "../marker.js";
6
5
  import { resetBoundaryCommitted } from "./committed.js";
7
6
  import { errorMessage } from "../../../src/error-message.js";
8
7
  import { carriedInputDrafts, isCarriedInputEntry } from "./artifacts.js";
9
- import { NEXT_WINDOW_PROMPT_TYPE } from "../entries.js";
10
- import { promptBlock } from "../text.js";
11
8
  function isAbort(message, outcome, ctx) {
12
9
  return outcome === "aborted" || (message.role === "assistant" && message.stopReason === "aborted") || ctx.signal?.aborted === true;
13
10
  }
@@ -25,15 +22,15 @@ function requestForWindow(request, windowId) {
25
22
  return request.phase === "pending" && request.windowId === windowId ? request : NO_REQUEST;
26
23
  }
27
24
  const spendsOverflow = (boundary) => boundary === "command-overflow" || boundary === "overflow-recovery";
28
- function boundaryIntent(request, windowId, boundary) {
25
+ function boundaryIntent(request, windowId, boundary, carryRunInputs = false) {
29
26
  const tool = request.phase === "none" ? undefined : request.tool;
30
27
  const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? true : true;
31
- return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
28
+ return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal", ...(carryRunInputs ? { carryRunInputs: true } : {}) };
32
29
  }
33
30
  /** Resolve once, after a successful current build. No delivery policy is left to the adapter. */
34
31
  export function finalizeResetBoundary(intent, request, passiveInputs = []) {
35
32
  const inputs = request.phase === "pending" && request.command ? request.command.inputs ?? []
36
- : intent.boundary === "overflow-recovery" ? passiveInputs : [];
33
+ : intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
37
34
  const resumeModel = intent.continueAfterReset || inputs.length > 0;
38
35
  const state = {
39
36
  request: NO_REQUEST,
@@ -90,8 +87,9 @@ export function reduceResetControl(state, event) {
90
87
  }
91
88
  // A direct tool request commits after the whole tool batch. The budget cutoff is
92
89
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
93
- if ((request.phase === "pending" && request.tool && !manual) || facts.hardReserveDue) {
94
- return boundaryIntent(request, facts.windowId, "turn-end");
90
+ const toolReset = request.phase === "pending" && request.tool !== undefined;
91
+ if ((toolReset && !manual) || facts.hardReserveDue) {
92
+ return boundaryIntent(request, facts.windowId, "turn-end", !manual && !toolReset && facts.hardReserveDue);
95
93
  }
96
94
  return { state: { request, overflow: "idle" }, effect: "none" };
97
95
  }
@@ -146,17 +144,16 @@ export function registerResetLifecycle(pi, options) {
146
144
  let lifecycleGeneration = 0;
147
145
  let control = initialResetControl();
148
146
  let runInputs = [];
149
- let commandId;
150
147
  // Once input returns handled, Pi no longer owns its original content. If close-out
151
- // fails/cancels, return that content to the transcript without starting another run.
152
- const restoreCommandInputs = () => {
148
+ // fails/cancels, restore it; only an ordinary error starts a turn to answer it.
149
+ const restoreCommandInputs = (triggerTurn = false) => {
153
150
  const request = control.request;
154
151
  if (request.phase !== "pending" || !request.command?.inputs?.length)
155
152
  return;
156
153
  const inputs = request.command.inputs;
157
154
  control = { ...control, request: { ...request, command: { ...request.command, inputs: [] } } };
158
155
  for (const draft of carriedInputDrafts(inputs)) {
159
- pi.sendMessage(draft, { triggerTurn: false });
156
+ pi.sendMessage(draft, { triggerTurn });
160
157
  }
161
158
  runInputs.push(...inputs);
162
159
  };
@@ -166,11 +163,9 @@ export function registerResetLifecycle(pi, options) {
166
163
  restoreCommandInputs();
167
164
  control = initialResetControl();
168
165
  runInputs = [];
169
- commandId = undefined;
170
166
  };
171
167
  const resetBoundaryResult = async (entries, ctx, intent) => {
172
- // Keep command state live while notes load: input arriving during this await must
173
- // join this very boundary even if its steer cannot reach the closing model.
168
+ // Keep command state live while notes load so input arriving during this await joins this boundary.
174
169
  const generation = lifecycleGeneration;
175
170
  const outerGeneration = options.getLifecycleGeneration?.();
176
171
  const sessionId = ctx.sessionManager.getSessionId();
@@ -213,37 +208,22 @@ export function registerResetLifecycle(pi, options) {
213
208
  ? [{ type: "text", text: event.text }, ...event.images]
214
209
  : event.text;
215
210
  control = reduceResetControl(control, { type: "input", windowId: request.windowId, input: content }).state;
216
- const steerContent = event.images?.length
217
- ? [{ type: "text", text: promptBlock(event.text) }, ...event.images]
218
- : promptBlock(event.text);
219
- pi.sendMessage({ customType: NEXT_WINDOW_PROMPT_TYPE, content: steerContent, display: false, details: { windowId: request.windowId, commandId } }, { deliverAs: "steer" });
220
211
  return { action: "handled" };
221
212
  });
222
213
  // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
223
214
  // safety reset is actually committed, cancel that empty follow-up before provider
224
215
  // work. Real queued user input is allowed through and answered before settlement.
225
216
  pi.on("context_with_system", (event, ctx) => {
226
- const request = control.request;
227
- // Steering can be queued during buildReset's await and arrive after the boundary.
228
- // It is closing-model context only; originals already live in the carried entries.
229
- const messages = event.messages.filter((message) => {
230
- if (message.role !== "custom" || message.customType !== NEXT_WINDOW_PROMPT_TYPE)
231
- return true;
232
- const details = message.details;
233
- return request.phase === "pending" && request.command !== undefined &&
234
- request.windowId === currentWindowId(ctx) && details?.windowId === request.windowId && commandId !== undefined && details?.commandId === commandId;
235
- });
236
- const filtered = messages.length === event.messages.length ? undefined : { messages };
237
217
  const stop = control.stopAfterReset;
238
218
  if (!sessionActive || !stop || ctx.hasPendingMessages())
239
- return filtered;
219
+ return undefined;
240
220
  const marker = currentReset(ctx);
241
221
  if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
242
- return filtered;
222
+ return undefined;
243
223
  const branch = ctx.sessionManager.getBranch();
244
224
  const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
245
225
  if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry)))
246
- return filtered;
226
+ return undefined;
247
227
  ctx.abort();
248
228
  const system = getCurrentSystemMessage(event.messages);
249
229
  return { messages: system ? [system] : [] };
@@ -270,9 +250,14 @@ export function registerResetLifecycle(pi, options) {
270
250
  });
271
251
  if (decision.effect === "build-boundary")
272
252
  return await resetBoundaryResult(entries, ctx, decision);
273
- if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
253
+ if (aborted)
274
254
  restoreCommandInputs();
255
+ else if (event.outcome === "error" && decision.state.request.phase === "none")
256
+ restoreCommandInputs(true);
275
257
  control = decision.state;
258
+ if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
259
+ event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages())
260
+ runInputs = [];
276
261
  if (!aborted && event.outcome !== "error" && options.isEnabled()) {
277
262
  const marker = buildMarkerDraft(ctx, entries);
278
263
  if (marker)
@@ -331,8 +316,6 @@ export function registerResetLifecycle(pi, options) {
331
316
  command(windowId, continueAfterReset, input) {
332
317
  const decision = reduceResetControl(control, { type: "command", windowId, continueAfterReset, ...(input !== undefined ? { input } : {}) });
333
318
  control = decision.state;
334
- if (decision.effect === "close-out-armed")
335
- commandId = randomUUID();
336
319
  return decision.effect;
337
320
  },
338
321
  request(windowId, lastWord) {
@@ -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 } 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 } from "./window.js";
9
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
@@ -26,6 +26,9 @@ function readPackageVersion() {
26
26
  return "dev";
27
27
  }
28
28
  const buildLabel = `v${readPackageVersion()}`;
29
+ const notesoupTools = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE]
30
+ .map(({ name, description }) => `${name}: ${description}`)
31
+ .join("\n") + "\nDiscover deferred tools through codemode or tool_search when available.";
29
32
  function branchHasWindowMarker(ctx, fromId) {
30
33
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
31
34
  }
@@ -78,7 +81,8 @@ export function registerContext(pi, settingsManager) {
78
81
  ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
79
82
  }
80
83
  };
81
- pi.on("before_agent_start", (_event, ctx) => {
84
+ pi.on("before_agent_start", (event, ctx) => {
85
+ event.systemPromptOptions.sections.notesoup_tools = notesoupTools;
82
86
  if (enabled)
83
87
  maybeSendMarker(pi, ctx);
84
88
  });
@@ -174,8 +178,8 @@ export function registerContext(pi, settingsManager) {
174
178
  cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
175
179
  },
176
180
  });
177
- const emptyBrainCommand = {
178
- description: "Flush memory to notes and continue in a fresh window; optional prompt runs there",
181
+ const emptyBrainCommand = (name) => ({
182
+ description: "Flush memory to notes, reset, and stop; optional text provides close-out context",
179
183
  handler: async (args, cmdCtx) => {
180
184
  if (!enabled) {
181
185
  cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
@@ -187,27 +191,27 @@ export function registerContext(pi, settingsManager) {
187
191
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId)
188
192
  return;
189
193
  }
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,
194
+ // Manual wipes close out at settlement, then stop unless later human input arrives. The hidden warning is triggered when idle,
191
195
  // steered into the running turn when busy — so the agent closes out promptly
192
196
  // instead of the reset waiting for the whole run.
193
197
  const prompt = args.trim() ? args : undefined;
194
- const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
198
+ const armed = resets.command(requestedWindowId, false);
195
199
  if (armed === "already-pending") {
196
200
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
197
201
  return;
198
202
  }
199
203
  cmdCtx.ui.notify("🥣 Dumping Brain", "info");
200
204
  try {
201
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
205
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/${name} ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
202
206
  }
203
207
  catch (error) {
204
208
  resets.clear();
205
209
  cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
206
210
  }
207
211
  },
208
- };
209
- pi.registerCommand("empty", emptyBrainCommand);
210
- pi.registerCommand("fresh-window", emptyBrainCommand);
212
+ });
213
+ pi.registerCommand("empty", emptyBrainCommand("empty"));
214
+ pi.registerCommand("fresh-window", emptyBrainCommand("fresh-window"));
211
215
  pi.registerTool(defineTool({
212
216
  name: "empty_brain",
213
217
  label: "Empty Brain",
@@ -8,8 +8,6 @@ export declare const PI_PRE_RESET_HINTS = "Anything you say here is erased with
8
8
  export { warningNotice as warningContent } from "../../src/budget/text.js";
9
9
  /** Odometer breadcrumb: the marker names its own seq, so history paging reads the landscape directly. */
10
10
  export declare function markerContent(seq: number): string;
11
- /** The closing model sees deferred input as a bare next-window prompt block. */
12
- export declare function promptBlock(commandLine: string): string;
13
11
  /** Approved manual close-out notices; both variants live here. */
14
12
  export declare const COMMAND_NOTICE: {
15
13
  prompted: string;
@@ -12,17 +12,13 @@ export { warningNotice as warningContent } from "../../src/budget/text.js";
12
12
  export function markerContent(seq) {
13
13
  return `<notesoup:marker seq="${seq}" />`;
14
14
  }
15
- /** The closing model sees deferred input as a bare next-window prompt block. */
16
- export function promptBlock(commandLine) {
17
- return `<notesoup:next_window_prompt>\n${commandLine}\n</notesoup:next_window_prompt>`;
18
- }
19
15
  /** Approved manual close-out notices; both variants live here. */
20
16
  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.",
17
+ 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
18
  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
19
  };
24
20
  /** Manual orders omit budget timing hints; deferred work sits outside the notice. */
25
21
  export function commandWarningContent(commandLine) {
26
22
  const notice = commandLine ? COMMAND_NOTICE.prompted : COMMAND_NOTICE.bare;
27
- return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${promptBlock(commandLine)}` : ""}`;
23
+ return `${GUIDANCE_OPEN_TAG}\n${notice}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}${commandLine ? `\n${commandLine}` : ""}`;
28
24
  }
@@ -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) {