notesoup 0.56.1 → 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 (52) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/runtime.js +8 -8
  3. package/dist/plugins/pi/text.js +1 -1
  4. package/dist/src/history/claude.d.ts +2 -0
  5. package/dist/src/history/claude.js +13 -2
  6. package/dist/src/history/codex-transcript.d.ts +15 -3
  7. package/dist/src/history/codex-transcript.js +57 -21
  8. package/dist/src/history/codex.d.ts +4 -2
  9. package/dist/src/history/codex.js +3 -3
  10. package/dist/src/history/corpus.d.ts +8 -1
  11. package/dist/src/history/corpus.js +17 -1
  12. package/dist/src/history/history.d.ts +16 -10
  13. package/dist/src/history/history.js +9 -9
  14. package/dist/src/history/local.d.ts +2 -0
  15. package/dist/src/history/local.js +35 -38
  16. package/dist/src/history/prefilter.d.ts +5 -0
  17. package/dist/src/history/prefilter.js +95 -0
  18. package/dist/src/history/query.d.ts +29 -27
  19. package/dist/src/history/query.js +82 -34
  20. package/dist/src/history/summary-cache.d.ts +10 -0
  21. package/dist/src/history/summary-cache.js +129 -0
  22. package/dist/src/tools/history.js +31 -20
  23. package/dist/test/agent-loop.test.js +18 -26
  24. package/dist/test/codex-history.test.js +90 -4
  25. package/dist/test/codex-plugin.test.js +6 -2
  26. package/dist/test/history-corpus.test.js +221 -33
  27. package/dist/test/history-prefilter.test.d.ts +1 -0
  28. package/dist/test/history-prefilter.test.js +174 -0
  29. package/dist/test/history-summary-cache.test.d.ts +1 -0
  30. package/dist/test/history-summary-cache.test.js +297 -0
  31. package/dist/test/history.integration.test.js +87 -52
  32. package/dist/test/model-facing-text.test.js +1 -1
  33. package/dist/test/reset-lifecycle.test.js +4 -6
  34. package/docs/history-sessions.md +26 -2
  35. package/docs/reset-lifecycle.md +4 -4
  36. package/docs/tool-results.md +4 -2
  37. package/package.json +1 -1
  38. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  39. package/plugins/claude/dist/claude/helper.js +425 -122
  40. package/plugins/codex/dist/codex/notesoup.js +423 -123
  41. package/plugins/pi/runtime.ts +8 -8
  42. package/plugins/pi/text.ts +1 -1
  43. package/src/history/claude.ts +16 -2
  44. package/src/history/codex-transcript.ts +52 -17
  45. package/src/history/codex.ts +5 -5
  46. package/src/history/corpus.ts +19 -2
  47. package/src/history/history.ts +11 -11
  48. package/src/history/local.ts +34 -38
  49. package/src/history/prefilter.ts +86 -0
  50. package/src/history/query.ts +77 -33
  51. package/src/history/summary-cache.ts +119 -0
  52. package/src/tools/history.ts +33 -20
@@ -170,8 +170,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
170
170
  },
171
171
  });
172
172
 
173
- const emptyBrainCommand = {
174
- description: "Flush memory to notes and continue in a fresh window; optional prompt runs there",
173
+ const emptyBrainCommand = (name: "empty" | "fresh-window") => ({
174
+ description: "Flush memory to notes, reset, and stop; optional text provides close-out context",
175
175
  handler: async (args: string, cmdCtx: ExtensionCommandContext) => {
176
176
  if (!enabled) {
177
177
  cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
@@ -182,26 +182,26 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
182
182
  await cmdCtx.waitForIdle();
183
183
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId) return;
184
184
  }
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,
185
+ // Manual wipes close out at settlement, then stop unless later human input arrives. The hidden warning is triggered when idle,
186
186
  // steered into the running turn when busy — so the agent closes out promptly
187
187
  // instead of the reset waiting for the whole run.
188
188
  const prompt = args.trim() ? args : undefined;
189
- const armed = resets.command(requestedWindowId, prompt !== undefined, prompt);
189
+ const armed = resets.command(requestedWindowId, false);
190
190
  if (armed === "already-pending") {
191
191
  cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
192
192
  return;
193
193
  }
194
194
  cmdCtx.ui.notify("🥣 Dumping Brain", "info");
195
195
  try {
196
- pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/empty ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
196
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/${name} ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
197
197
  } catch (error) {
198
198
  resets.clear();
199
199
  cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
200
200
  }
201
201
  },
202
- };
203
- pi.registerCommand("empty", emptyBrainCommand);
204
- pi.registerCommand("fresh-window", emptyBrainCommand);
202
+ });
203
+ pi.registerCommand("empty", emptyBrainCommand("empty"));
204
+ pi.registerCommand("fresh-window", emptyBrainCommand("fresh-window"));
205
205
 
206
206
  pi.registerTool(defineTool({
207
207
  name: "empty_brain",
@@ -23,7 +23,7 @@ export function promptBlock(commandLine: string): string {
23
23
 
24
24
  /** Approved manual close-out notices; both variants live here. */
25
25
  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.",
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 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
27
  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
28
  };
29
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
 
@@ -3,10 +3,12 @@ import { readdir, readFile, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { piHistoryFromJsonl } from "./pi.js";
6
- import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
6
+ import { offlineClaudeHistoryFromJsonl } from "./claude.js";
7
7
  import { readCodexHistory } from "./codex.js";
8
- import { readCodexTranscriptBytes } from "./codex-transcript.js";
8
+ import { createCodexTranscriptReader } from "./codex-transcript.js";
9
+ import { createHistoryPrefilter, historyFileMayMatch, type HistoryPrefilter } from "./prefilter.js";
9
10
  import { sessionIdentity, type HistoryCorpus, type HistorySession } from "./corpus.js";
11
+ import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
10
12
 
11
13
  export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
12
14
  export type LocalHistoryOptions = {
@@ -15,6 +17,8 @@ export type LocalHistoryOptions = {
15
17
  roots?: LocalHistoryRoots;
16
18
  home?: string;
17
19
  env?: NodeJS.ProcessEnv;
20
+ /** Internal hermetic-test seam, not a tool parameter or host setting. */
21
+ summaryCacheRoot?: string;
18
22
  /** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
19
23
  dshSessions?: () => Promise<HistorySession[]>;
20
24
  };
@@ -43,36 +47,7 @@ async function filesAt(root: string, depth: number): Promise<string[]> {
43
47
  return paths;
44
48
  }
45
49
 
46
- const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
47
- copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
48
- does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
49
- not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
50
- FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
51
- the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
52
-
53
- function escapeRegExp(value: string): string {
54
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
55
- }
56
-
57
- /** Only prove misses, not hits. Only \\uXXXX can encode a word character; other JSON escapes are control/quote/slash. */
58
- function mayMatch(text: string, queries: readonly string[], codex: boolean): boolean {
59
- if (codex && text.includes('"history_base"')) return true;
60
- const unescaped = text.includes("\\u")
61
- ? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
62
- : text;
63
- return queries.some((query) => {
64
- const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
65
- return tokens === null || tokens.every((token) => {
66
- const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
67
- return parts.every((part) => {
68
- const literal = new RegExp(escapeRegExp(part), "iu");
69
- return literal.test(unescaped) || (unescaped !== text && literal.test(text)) || literal.test(PRESENTATION);
70
- });
71
- });
72
- });
73
- }
74
-
75
- async function localSessions(harness: "pi" | "claude" | "codex", root: string): Promise<HistorySession[]> {
50
+ async function localSessions(harness: "pi" | "claude" | "codex", root: string, cacheRoot: string, prefilters: WeakMap<readonly string[], HistoryPrefilter>): Promise<HistorySession[]> {
76
51
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
77
52
  const sessions: HistorySession[] = [];
78
53
  for (const path of paths) {
@@ -86,13 +61,31 @@ async function localSessions(harness: "pi" | "claude" | "codex", root: string):
86
61
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
87
62
  sessions.push({
88
63
  harness, id, modifiedAt,
64
+ async loadRepresentative() {
65
+ return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
66
+ if (harness === "codex") {
67
+ const readBytes = createCodexTranscriptReader();
68
+ const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
69
+ await track(source);
70
+ return readBytes(source, remaining);
71
+ });
72
+ return { data: { projection: history.projection }, lineageSources: history.lineageSources };
73
+ }
74
+ const data = await this.load();
75
+ if (!data) throw new Error("Session returned no history");
76
+ return { data };
77
+ });
78
+ },
89
79
  async load(queries) {
90
- if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
91
- const text = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile(path, "utf8");
92
- if (queries?.length && !mayMatch(text, queries, harness === "codex")) return undefined;
80
+ if (queries?.length) {
81
+ let prefilter = prefilters.get(queries);
82
+ if (!prefilter) prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
83
+ if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return undefined;
84
+ }
93
85
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
86
+ const text = await readFile(path, "utf8");
94
87
  if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
95
- const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
88
+ const projection = offlineClaudeHistoryFromJsonl(text, id);
96
89
  const missing = projection.missingAncestors;
97
90
  return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
98
91
  },
@@ -107,17 +100,20 @@ export function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus
107
100
  currentHarness: options.current.harness,
108
101
  async sessions(onlyHarness) {
109
102
  const roots = rootsFor(options);
103
+ const env = options.env ?? process.env;
104
+ const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
110
105
  const discovered: HistorySession[] = [];
106
+ const prefilters = new WeakMap<readonly string[], HistoryPrefilter>();
111
107
  for (const harness of ["pi", "claude", "codex"] as const) {
112
108
  if (onlyHarness !== undefined && onlyHarness !== harness) continue;
113
109
  const root = roots[harness];
114
- if (root != null) discovered.push(...await localSessions(harness, root));
110
+ if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
115
111
  }
116
112
  if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
117
113
  discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
118
114
  const unique = new Map<string, HistorySession>();
119
115
  for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
120
- const current = { ...options.current, modifiedAt: Date.now() };
116
+ const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
121
117
  if (onlyHarness === undefined || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
122
118
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
123
119
  },
@@ -0,0 +1,86 @@
1
+ /** Conservative streaming proof-of-miss. A possible hit still needs the normal strict decoder. */
2
+ import { createReadStream } from "node:fs";
3
+ import { stat } from "node:fs/promises";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import * as zlib from "node:zlib";
7
+ import { CODEX_TRANSCRIPT_MAX_BYTES } from "./codex-transcript.js";
8
+
9
+ const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
11
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
12
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
13
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
14
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
15
+ const HISTORY_BASE = '"history_base"';
16
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
17
+
18
+ /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
19
+ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter {
20
+ let overlap = HISTORY_BASE.length;
21
+ const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
22
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
23
+ return parts.map((part) => {
24
+ overlap = Math.max(overlap, part.length);
25
+ return new RegExp(part, "iu");
26
+ }).filter((literal) => !literal.test(PRESENTATION));
27
+ }));
28
+ // No safe tokens (or generated text alone) cannot prove a miss.
29
+ const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
30
+ return async (chunks, codex = false) => {
31
+ const decoder = new StringDecoder("utf8");
32
+ const seen = alternatives.map((tokens) => tokens.map(() => false));
33
+ let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
34
+ // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
35
+ const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
36
+ const scan = (chunk: string, final = false) => {
37
+ const raw = rawTail + chunk, source = pending + chunk;
38
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
39
+ pending = "";
40
+ const decoded = needsNormalization ? source.replace(escapes, (match, hex: string | undefined, offset: number) => {
41
+ if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
42
+ // Tokens cannot include backslashes: an unresolved run needs only one separator,
43
+ // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
44
+ const literal = hex === undefined ? "\\" : `\\u${hex}`;
45
+ if (!final && offset + match.length === source.length) { pending = literal; return ""; }
46
+ return literal;
47
+ }) : chunk;
48
+ const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
49
+ if (codex && raw.includes(HISTORY_BASE)) possible = true;
50
+ else possible = alternatives.some((tokens, index) => {
51
+ const bits = seen[index]!;
52
+ for (let token = 0; token < tokens.length; token++) bits[token] ||= tokens[token]!.test(raw) || (normalized !== raw && tokens[token]!.test(normalized));
53
+ return bits.every(Boolean);
54
+ });
55
+ rawTail = raw.slice(-overlap);
56
+ normalizedTail = normalized.slice(-overlap);
57
+ };
58
+ for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
59
+ if (!possible) scan(decoder.end(), true);
60
+ return possible;
61
+ };
62
+ }
63
+
64
+ /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
65
+ export async function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity): Promise<boolean> {
66
+ if (codex) {
67
+ const info = await stat(path);
68
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
69
+ }
70
+ // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
71
+ const compressed = codex && path.endsWith(".jsonl.zst");
72
+ if (compressed && typeof zlib.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
73
+ const input = createReadStream(path);
74
+ const consume = async (chunks: AsyncIterable<Buffer>) => {
75
+ let size = 0;
76
+ async function* bounded() {
77
+ for await (const chunk of chunks) {
78
+ size += chunk.length;
79
+ if (size > maxBytes) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
80
+ yield chunk;
81
+ }
82
+ }
83
+ return prefilter(bounded(), codex);
84
+ };
85
+ return compressed ? pipeline(input, zlib.createZstdDecompress(), consume) : pipeline(input, consume);
86
+ }