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
@@ -7447,13 +7447,13 @@ function Default(...args) {
7447
7447
  }
7448
7448
 
7449
7449
  // node_modules/typebox/build/value/pipeline/pipeline.mjs
7450
- function Pipeline(pipeline) {
7450
+ function Pipeline(pipeline2) {
7451
7451
  return (...args) => {
7452
7452
  const [context2, type, value] = arguments_exports.Match(args, {
7453
7453
  3: (context3, type2, value2) => [context3, type2, value2],
7454
7454
  2: (type2, value2) => [{}, type2, value2]
7455
7455
  });
7456
- return pipeline.reduce((result, func) => func(context2, type, result), value);
7456
+ return pipeline2.reduce((result, func) => func(context2, type, result), value);
7457
7457
  };
7458
7458
  }
7459
7459
 
@@ -8680,7 +8680,7 @@ function createNotesStore(input) {
8680
8680
  const [first, second] = [fromPath, path].sort();
8681
8681
  return withPathQueue(first, () => withPathQueue(second, mutate));
8682
8682
  }
8683
- async function rename2(fromAddress, toAddress) {
8683
+ async function rename3(fromAddress, toAddress) {
8684
8684
  const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
8685
8685
  return { meta, replacedCrumpledTarget };
8686
8686
  }
@@ -8780,7 +8780,7 @@ function createNotesStore(input) {
8780
8780
  function searchWithStatus(queries, options = {}) {
8781
8781
  return searchRows(queries, options, { namespacesUnavailable: [] });
8782
8782
  }
8783
- return { write, read, update, rename: rename2, forget, list, search, listWithStatus, searchWithStatus };
8783
+ return { write, read, update, rename: rename3, forget, list, search, listWithStatus, searchWithStatus };
8784
8784
  }
8785
8785
 
8786
8786
  // src/tools/output.ts
@@ -8983,8 +8983,16 @@ function nestedCallSummary(event) {
8983
8983
  const nested = event.execution?.nestedCalls;
8984
8984
  return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
8985
8985
  }
8986
+ var HistoryFoldedRowSchema = typebox_exports.Object({
8987
+ session: typebox_exports.Optional(typebox_exports.String()),
8988
+ first_seq: typebox_exports.Integer({ minimum: 1 }),
8989
+ last_seq: typebox_exports.Integer({ minimum: 1 }),
8990
+ count: typebox_exports.Integer({ minimum: 1 }),
8991
+ tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
8992
+ }, { additionalProperties: false });
8986
8993
  var HistoryPageItemSchema = typebox_exports.Object({
8987
8994
  session: typebox_exports.Optional(typebox_exports.String()),
8995
+ folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
8988
8996
  seq: typebox_exports.Integer({ minimum: 1 }),
8989
8997
  role: HistoryRoleSchema,
8990
8998
  created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
@@ -8993,14 +9001,6 @@ var HistoryPageItemSchema = typebox_exports.Object({
8993
9001
  truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
8994
9002
  offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
8995
9003
  }, { additionalProperties: false });
8996
- var HistoryFoldedRowSchema = typebox_exports.Object({
8997
- session: typebox_exports.Optional(typebox_exports.String()),
8998
- folded: typebox_exports.Literal(true),
8999
- first_seq: typebox_exports.Integer({ minimum: 1 }),
9000
- last_seq: typebox_exports.Integer({ minimum: 1 }),
9001
- count: typebox_exports.Integer({ minimum: 1 }),
9002
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
9003
- }, { additionalProperties: false });
9004
9004
  var MAX_FOLD_TOOL_NAMES = 20;
9005
9005
  var MAX_FOLD_TOOL_NAME_CHARS = 120;
9006
9006
  function visibleItem(event, maxChars, matchOffset) {
@@ -9385,6 +9385,14 @@ var notesSearch = {
9385
9385
  };
9386
9386
 
9387
9387
  // src/history/query.ts
9388
+ var multiPages = /* @__PURE__ */ new WeakSet();
9389
+ function isMultiPage(page) {
9390
+ return multiPages.has(page);
9391
+ }
9392
+ function markMultiPage(page) {
9393
+ multiPages.add(page);
9394
+ return page;
9395
+ }
9388
9396
  var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
9389
9397
  function timeBound(name, value) {
9390
9398
  if (value === void 0) return success(void 0);
@@ -9402,20 +9410,12 @@ function resolveTimeBounds(params) {
9402
9410
  }
9403
9411
  return success({ ...since.data === void 0 ? {} : { sinceMs: since.data }, ...until.data === void 0 ? {} : { untilMs: until.data } });
9404
9412
  }
9405
- var HistoryOlderSchema = typebox_exports.Object({
9406
- session: typebox_exports.Optional(typebox_exports.String()),
9407
- before_seq: typebox_exports.Integer({ minimum: 1 })
9408
- }, { additionalProperties: false });
9409
- var HistoryNewerSchema = typebox_exports.Object({
9410
- session: typebox_exports.Optional(typebox_exports.String()),
9411
- after_seq: typebox_exports.Integer({ minimum: 1 }),
9412
- from: typebox_exports.Literal("oldest")
9413
- }, { additionalProperties: false });
9414
9413
  var HistoryPageSchema = typebox_exports.Object({
9415
9414
  notice: typebox_exports.Optional(typebox_exports.String()),
9416
- items: typebox_exports.Array(typebox_exports.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
9417
- page_older: typebox_exports.Union([HistoryOlderSchema, typebox_exports.Null()], { description: "Args to merge into `history_list` for older events." }),
9418
- page_newer: typebox_exports.Union([HistoryNewerSchema, typebox_exports.Null()], { description: "Args to merge into `history_list` for newer events." })
9415
+ items: typebox_exports.Array(HistoryPageItemSchema),
9416
+ folded_after: typebox_exports.Optional(HistoryFoldedRowSchema),
9417
+ has_older: typebox_exports.Boolean(),
9418
+ has_newer: typebox_exports.Boolean()
9419
9419
  }, { additionalProperties: false });
9420
9420
  function truncateHistoryItem(item, fits) {
9421
9421
  if (fits(item)) return item;
@@ -9440,7 +9440,7 @@ function foldedRun(events, session) {
9440
9440
  }
9441
9441
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
9442
9442
  const tools = Object.fromEntries(entries);
9443
- return { ...session === void 0 ? {} : { session }, folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9443
+ return { ...session === void 0 ? {} : { session }, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9444
9444
  }
9445
9445
  function prepareSelection(projection, params) {
9446
9446
  const folds = !params.roles && params.query === void 0;
@@ -9461,19 +9461,19 @@ function prepareSelection(projection, params) {
9461
9461
  }
9462
9462
  function pageData(prepared, start, end, maxChars, preview) {
9463
9463
  const { candidates, tail } = prepared;
9464
- const identity2 = prepared.session === void 0 ? {} : { session: prepared.session };
9465
9464
  const items = [];
9466
9465
  for (let index = start; index < end; index++) {
9467
9466
  const candidate = candidates[index];
9468
- if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
9469
- items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } }));
9467
+ const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } });
9468
+ items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
9470
9469
  }
9471
- if (end === candidates.length && tail) items.push(tail);
9472
- return {
9470
+ const page = {
9473
9471
  items,
9474
- page_older: !prepared.multi && start > 0 && start < end ? { ...identity2, before_seq: candidates[start].event.seq } : null,
9475
- page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity2, after_seq: candidates[end - 1].event.seq, from: "oldest" } : null
9472
+ ...end === candidates.length && tail ? { folded_after: tail } : {},
9473
+ has_older: start > 0 && start < end || !!prepared.discarded && prepared.from !== "oldest",
9474
+ has_newer: end < candidates.length && start < end || !!prepared.discarded && prepared.from === "oldest"
9476
9475
  };
9476
+ return prepared.multi ? markMultiPage(page) : page;
9477
9477
  }
9478
9478
  function resolveSelection(params) {
9479
9479
  const bounds = resolveTimeBounds(params);
@@ -9500,19 +9500,62 @@ function sessionRepresentative(projection, scoped) {
9500
9500
  if (scoped.roles) return events.at(-1);
9501
9501
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9502
9502
  }
9503
- function selectCorpusPage(sessions, scoped, fits, maxChars) {
9504
- const candidates = sessions.flatMap(({ session, projection }) => {
9505
- if (scoped.query !== void 0) return prepareSelection(projection, { ...scoped, session }).candidates;
9506
- const event = sessionRepresentative(projection, scoped);
9507
- return event === void 0 ? [] : [{ session, event }];
9508
- });
9509
- const time = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
9510
- candidates.sort((a, b) => time(a.event) - time(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq);
9511
- return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
9512
- }
9503
+ var eventTime = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
9504
+ var compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
9505
+ var CorpusCollector = class {
9506
+ constructor(scoped) {
9507
+ this.scoped = scoped;
9508
+ this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
9509
+ }
9510
+ scoped;
9511
+ candidates = [];
9512
+ limit;
9513
+ discarded = false;
9514
+ admit(candidate) {
9515
+ let low = 0, high = this.candidates.length;
9516
+ while (low < high) {
9517
+ const mid = low + high >>> 1;
9518
+ if (compareCorpus(this.candidates[mid], candidate) <= 0) low = mid + 1;
9519
+ else high = mid;
9520
+ }
9521
+ if (this.candidates.length === this.limit) {
9522
+ this.discarded = true;
9523
+ if (this.scoped.from === "oldest") {
9524
+ if (low === this.limit) return;
9525
+ this.candidates.pop();
9526
+ } else {
9527
+ if (low === 0) return;
9528
+ this.candidates.shift();
9529
+ low--;
9530
+ }
9531
+ }
9532
+ this.candidates.splice(low, 0, candidate);
9533
+ }
9534
+ /** Admit an already selected strict overview event without selecting it a second time. */
9535
+ addRepresentative(session, event) {
9536
+ if (!event) return false;
9537
+ this.admit({ session, event });
9538
+ return true;
9539
+ }
9540
+ /** Returns whether this session contributes an overview representative. */
9541
+ add(session, projection) {
9542
+ if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
9543
+ for (const event of filteredItems(projection, this.scoped, false)) {
9544
+ const document = eventDocument(event);
9545
+ if ((event.role === "user" || event.role === "assistant") && document === "") continue;
9546
+ const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
9547
+ if (matchOffset >= 0) this.admit({ session, event, matchOffset });
9548
+ }
9549
+ return true;
9550
+ }
9551
+ page(fits, maxChars, unvisited = false) {
9552
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
9553
+ }
9554
+ };
9513
9555
  function selectPrepared(prepared, scoped, fits, maxChars) {
9514
9556
  const { candidates } = prepared;
9515
- const newest = scoped.from !== "oldest";
9557
+ const from = scoped.from ?? (scoped.after_seq !== void 0 ? "oldest" : "newest");
9558
+ const newest = from === "newest";
9516
9559
  let start = newest ? candidates.length : 0;
9517
9560
  let end = start;
9518
9561
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -9575,13 +9618,27 @@ async function resolveSession(corpus, selector) {
9575
9618
  if (matches.length > 1) 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.`);
9576
9619
  return success(matches[0]);
9577
9620
  }
9621
+ async function loadHistoryRepresentative(session) {
9622
+ if (session.loadRepresentative) {
9623
+ try {
9624
+ return success(await session.loadRepresentative());
9625
+ } catch (error) {
9626
+ return unavailableSession(session, error);
9627
+ }
9628
+ }
9629
+ const result = await loadHistorySession(session);
9630
+ return result.ok ? success({ event: sessionRepresentative(result.data.projection, {}), notice: result.data.notice }) : result;
9631
+ }
9632
+ function unavailableSession(session, error) {
9633
+ return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
9634
+ }
9578
9635
  async function loadHistorySession(session, queries) {
9579
9636
  try {
9580
9637
  const data = await session.load(queries);
9581
9638
  if (data === void 0 && !queries?.length) throw new Error("Session returned no history");
9582
9639
  return success(data);
9583
9640
  } catch (error) {
9584
- return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
9641
+ return unavailableSession(session, error);
9585
9642
  }
9586
9643
  }
9587
9644
  function currentHistory(context2) {
@@ -9622,15 +9679,23 @@ function renderFoldedRow(row) {
9622
9679
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
9623
9680
  const identity2 = row.session === void 0 ? {} : { session: row.session };
9624
9681
  const expand = `
9625
- \u2192 expand: ${JSON.stringify({ ...identity2, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
9682
+ \u2192 expand: ${JSON.stringify({ ...identity2, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
9626
9683
  return `${row.session === void 0 ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
9627
9684
  }
9628
9685
  function renderPage(page) {
9629
- if (page.items.length === 0) return `${page.notice ?? ""}No events match these filters.`;
9630
- const body = page.items.map((item) => "folded" in item ? renderFoldedRow(item) : renderPageItem(item)).join("\n\n");
9686
+ if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
9687
+ const body = [...page.items.flatMap((item) => [...item.folded_before ? [renderFoldedRow(item.folded_before)] : [], renderPageItem(item)]), ...page.folded_after ? [renderFoldedRow(page.folded_after)] : []].join("\n\n");
9688
+ if (isMultiPage(page)) {
9689
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9690
+ return (page.notice ?? "") + body + (directions ? `
9691
+
9692
+ \u2192 more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
9693
+ }
9694
+ const first = page.items[0];
9695
+ const last = page.items.at(-1);
9631
9696
  const cursors = [
9632
- page.page_older === null ? "" : `\u2192 older: ${JSON.stringify(page.page_older)}`,
9633
- page.page_newer === null ? "" : `\u2192 newer: ${JSON.stringify(page.page_newer)}`
9697
+ page.has_older ? `\u2192 older: ${JSON.stringify({ ...first.session === void 0 ? {} : { session: first.session }, before_seq: first.seq })}` : "",
9698
+ page.has_newer ? `\u2192 newer: ${JSON.stringify({ ...last.session === void 0 ? {} : { session: last.session }, after_seq: last.seq })}` : ""
9634
9699
  ].filter((line) => line !== "");
9635
9700
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}
9636
9701
 
@@ -9638,8 +9703,7 @@ ${cursors.join(" | ")}`);
9638
9703
  }
9639
9704
  function renderRead(data) {
9640
9705
  const tool = toolHeader(data);
9641
- const afterSeq = data.seq - 10;
9642
- const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...data.session === void 0 ? {} : { session: data.session }, ...afterSeq >= 1 ? { after_seq: afterSeq } : {}, before_seq: data.seq + 10 })})`;
9706
+ const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...data.session === void 0 ? {} : { session: data.session }, after_seq: Math.max(0, data.seq - 10), before_seq: data.seq + 10 })})`;
9643
9707
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9644
9708
  }
9645
9709
  var plainText = (text) => text;
@@ -9649,11 +9713,11 @@ var historyListParameters = typebox_exports.Object({
9649
9713
  query: typebox_exports.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
9650
9714
  roles: historyRoles(),
9651
9715
  before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
9652
- after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
9716
+ after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
9653
9717
  since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
9654
9718
  until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
9655
- from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
9656
- limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
9719
+ from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
9720
+ limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
9657
9721
  max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` }))
9658
9722
  }, { additionalProperties: false });
9659
9723
  var historyList = {
@@ -9676,19 +9740,26 @@ var historyList = {
9676
9740
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
9677
9741
  const queries = Array.isArray(scoped.data.query) ? scoped.data.query : void 0;
9678
9742
  if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9679
- const loaded2 = [];
9743
+ const representative = !queries && scoped.data.roles === void 0 && scoped.data.since === void 0 && scoped.data.until === void 0;
9744
+ const collector = new CorpusCollector(scoped.data);
9745
+ let qualifying = 0;
9680
9746
  const notices = [];
9681
- for (const session of sessions) {
9682
- const result3 = await loadHistorySession(session, queries);
9747
+ let unvisited = false;
9748
+ for (const [index, session] of sessions.entries()) {
9749
+ const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
9683
9750
  if (!result3.ok || !result3.data) continue;
9684
- if (!queries && !sessionRepresentative(result3.data.projection, scoped.data)) continue;
9685
- loaded2.push({ session: sessionIdentity(session), projection: result3.data.projection });
9751
+ const added = "projection" in result3.data ? collector.add(sessionIdentity(session), result3.data.projection) : collector.addRepresentative(sessionIdentity(session), result3.data.event);
9752
+ if (!added) continue;
9753
+ qualifying++;
9686
9754
  if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
9687
- if (!queries && loaded2.length >= Math.max(1, params.limit ?? 20)) break;
9755
+ if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
9756
+ unvisited = index + 1 < sessions.length;
9757
+ break;
9758
+ }
9688
9759
  }
9689
9760
  const notice2 = notices.length ? { notice: notices.join("") } : {};
9690
- const result2 = selectCorpusPage(loaded2, scoped.data, (page) => fits({ ...page, ...notice2 }), maxChars);
9691
- return result2.ok ? success({ ...result2.data, ...notice2 }) : result2;
9761
+ const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
9762
+ return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
9692
9763
  }
9693
9764
  const target = await resolveSession(corpus, selector.data);
9694
9765
  if (!target.ok) return target;
@@ -9759,9 +9830,9 @@ var historyRead = {
9759
9830
  };
9760
9831
 
9761
9832
  // src/history/local.ts
9762
- import { readdir as readdir4, readFile as readFile4, stat as stat2 } from "node:fs/promises";
9763
- import { homedir } from "node:os";
9764
- import { join as join5 } from "node:path";
9833
+ import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
9834
+ import { homedir as homedir2 } from "node:os";
9835
+ import { join as join6 } from "node:path";
9765
9836
 
9766
9837
  // src/history/pi.ts
9767
9838
  function mapRole(role) {
@@ -10022,9 +10093,12 @@ function bootOrdinal(row, retained) {
10022
10093
  return Number.isSafeInteger(ordinal) ? ordinal : void 0;
10023
10094
  }
10024
10095
  function claudeHistoryFromJsonl(text, source) {
10096
+ return claudeHistoryFromRows(rowsOf(text), source);
10097
+ }
10098
+ function claudeHistoryFromRows(rows, source) {
10025
10099
  const nodes = /* @__PURE__ */ new Map();
10026
10100
  let nextSeq = 1;
10027
- for (const row of rowsOf(text)) {
10101
+ for (const row of rows) {
10028
10102
  if (!MESSAGE_TYPES.has(row.type)) continue;
10029
10103
  const uuid = requiredString(row.uuid, "uuid");
10030
10104
  parent(row);
@@ -10143,9 +10217,9 @@ function claudeHistoryFromJsonl(text, source) {
10143
10217
  const windows = [...windowsById.values()].sort((a, b) => a.ordinal === void 0 ? b.ordinal === void 0 ? 0 : 1 : b.ordinal === void 0 ? -1 : a.ordinal - b.ordinal);
10144
10218
  return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : void 0 };
10145
10219
  }
10146
- function offlineClaudeHead(text) {
10220
+ function offlineClaudeHeadFromRows(rows) {
10147
10221
  const latest = /* @__PURE__ */ new Map();
10148
- for (const row of rowsOf(text)) {
10222
+ for (const row of rows) {
10149
10223
  if (!MESSAGE_TYPES.has(row.type)) continue;
10150
10224
  const uuid = requiredString(row.uuid, "uuid");
10151
10225
  latest.delete(uuid);
@@ -10177,6 +10251,10 @@ function offlineClaudeHead(text) {
10177
10251
  const candidates = nonAttachments.length ? nonAttachments : leaves;
10178
10252
  return candidates.at(-1);
10179
10253
  }
10254
+ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10255
+ const rows = rowsOf(text);
10256
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10257
+ }
10180
10258
  async function readClaudeHistory(source) {
10181
10259
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10182
10260
  return claudeHistoryFromJsonl(await readFile2(source.transcriptPath, "utf8"), source);
@@ -10191,7 +10269,7 @@ var UUID_RE = new RegExp(`^${UUID}$`);
10191
10269
  var FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
10192
10270
  var RECORD_TYPES = /* @__PURE__ */ 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"]);
10193
10271
  var RESPONSE_TYPES = /* @__PURE__ */ 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"]);
10194
- var MAX_BYTES = 128 * 1024 * 1024;
10272
+ var CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
10195
10273
  var MAX_SEGMENTS = 64;
10196
10274
  var MAX_DIRECTORY_ENTRIES = 1e5;
10197
10275
  function nativeObject(value, field) {
@@ -10325,26 +10403,54 @@ async function referencedPath(home, rolloutId) {
10325
10403
  if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
10326
10404
  return matches[0];
10327
10405
  }
10328
- async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
10329
- const info = await stat(path);
10330
- if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10331
- const bytes = await readFile3(path);
10332
- if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
10333
- const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
10334
- if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
10335
- return decoded;
10406
+ async function resolveLineageSource(home, rolloutId) {
10407
+ const path = await realpath2(await referencedPath(home, rolloutId));
10408
+ if (![join4(home, "sessions"), join4(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
10409
+ return path;
10336
10410
  }
10337
- async function readCodexTranscript(source) {
10411
+ async function validateCodexLineageSources(sources) {
10412
+ try {
10413
+ for (const source of sources) if (await resolveLineageSource(source.home, source.rolloutId) !== source.path) return false;
10414
+ return true;
10415
+ } catch {
10416
+ return false;
10417
+ }
10418
+ }
10419
+ function createCodexTranscriptReader() {
10420
+ const cache = /* @__PURE__ */ new Map();
10421
+ return async (path, remaining = CODEX_TRANSCRIPT_MAX_BYTES) => {
10422
+ const canonical = await realpath2(path);
10423
+ let pending = cache.get(canonical);
10424
+ if (!pending) {
10425
+ pending = (async () => {
10426
+ const info = await stat(canonical);
10427
+ if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10428
+ const stored = await readFile3(canonical);
10429
+ if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
10430
+ if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
10431
+ const bytes2 = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
10432
+ return { bytes: bytes2, storedSize: Math.max(info.size, stored.length) };
10433
+ })();
10434
+ cache.set(canonical, pending);
10435
+ }
10436
+ const { bytes, storedSize } = await pending;
10437
+ if (storedSize > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
10438
+ if (bytes.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
10439
+ return bytes;
10440
+ };
10441
+ }
10442
+ async function readCodexTranscript(source, readBytes = createCodexTranscriptReader()) {
10338
10443
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
10339
10444
  id(source.threadId, "requested threadId");
10340
10445
  try {
10341
10446
  let path = await realpath2(source.transcriptPath), cutoff, home;
10342
- let remaining = MAX_BYTES;
10447
+ let remaining = CODEX_TRANSCRIPT_MAX_BYTES;
10343
10448
  const segments = [], seen = /* @__PURE__ */ new Set();
10449
+ const lineageSources = [];
10344
10450
  while (true) {
10345
10451
  if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
10346
10452
  seen.add(path);
10347
- const bytes = await readCodexTranscriptBytes(path, remaining);
10453
+ const bytes = await readBytes(path, remaining);
10348
10454
  remaining -= bytes.length;
10349
10455
  const segment = segmentFromBytes(bytes, cutoff);
10350
10456
  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)`);
@@ -10357,8 +10463,8 @@ async function readCodexTranscript(source) {
10357
10463
  if (!base) break;
10358
10464
  if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
10359
10465
  home ??= storageHome(path);
10360
- path = await realpath2(await referencedPath(home, base.thread_id));
10361
- if (![join4(home, "sessions"), join4(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
10466
+ path = await resolveLineageSource(home, base.thread_id);
10467
+ lineageSources.push({ home, rolloutId: base.thread_id, path });
10362
10468
  cutoff = base;
10363
10469
  }
10364
10470
  for (let index = 0; index < segments.length; index++) {
@@ -10408,7 +10514,7 @@ async function readCodexTranscript(source) {
10408
10514
  }
10409
10515
  Object.assign(state, { currentWindowId: window, currentWindowNumber: number, firstWindowId: first, previousWindowId: previousWindow });
10410
10516
  if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
10411
- return { state, records, highestSeq: lastSeq };
10517
+ return { state, records, highestSeq: lastSeq, dependencies: [...seen], lineageSources };
10412
10518
  } catch (error) {
10413
10519
  throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
10414
10520
  }
@@ -10520,8 +10626,8 @@ function standaloneTool(record, item) {
10520
10626
  const name = `${nativeString(item.server, "MCP server")}/${nativeString(item.tool, "MCP tool")}`;
10521
10627
  return { ...base, role: "tool", toolName: name, arguments: nativeObject(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
10522
10628
  }
10523
- async function readCodexHistory(source) {
10524
- const { state, records, highestSeq } = await readCodexTranscript(source);
10629
+ async function readCodexHistory(source, readBytes) {
10630
+ const { state, records, highestSeq, dependencies, lineageSources } = await readCodexTranscript(source, readBytes);
10525
10631
  const facts = /* @__PURE__ */ new Map(), callsSeen = /* @__PURE__ */ new Set(), responseIdsSeen = /* @__PURE__ */ new Set();
10526
10632
  const windows = /* @__PURE__ */ new Map(), branchSeqs = /* @__PURE__ */ new Set();
10527
10633
  const addWindow = (nativeId, createdAt) => {
@@ -10616,17 +10722,216 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10616
10722
  }
10617
10723
  if (item) addWindow(record.windowId).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
10618
10724
  }
10619
- return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
10725
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs), dependencies, lineageSources };
10726
+ }
10727
+
10728
+ // src/history/prefilter.ts
10729
+ import { createReadStream } from "node:fs";
10730
+ import { stat as stat2 } from "node:fs/promises";
10731
+ import { pipeline } from "node:stream/promises";
10732
+ import { StringDecoder } from "node:string_decoder";
10733
+ import * as zlib2 from "node:zlib";
10734
+ var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10735
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
10736
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
10737
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
10738
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
10739
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
10740
+ var HISTORY_BASE = '"history_base"';
10741
+ function createHistoryPrefilter(queries) {
10742
+ let overlap = HISTORY_BASE.length;
10743
+ const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
10744
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
10745
+ return parts.map((part) => {
10746
+ overlap = Math.max(overlap, part.length);
10747
+ return new RegExp(part, "iu");
10748
+ }).filter((literal) => !literal.test(PRESENTATION));
10749
+ }));
10750
+ const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10751
+ return async (chunks, codex = false) => {
10752
+ const decoder = new StringDecoder("utf8");
10753
+ const seen = alternatives.map((tokens) => tokens.map(() => false));
10754
+ let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
10755
+ const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
10756
+ const scan = (chunk, final = false) => {
10757
+ const raw = rawTail + chunk, source = pending + chunk;
10758
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
10759
+ pending = "";
10760
+ const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
10761
+ if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
10762
+ const literal = hex === void 0 ? "\\" : `\\u${hex}`;
10763
+ if (!final && offset + match.length === source.length) {
10764
+ pending = literal;
10765
+ return "";
10766
+ }
10767
+ return literal;
10768
+ }) : chunk;
10769
+ const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
10770
+ if (codex && raw.includes(HISTORY_BASE)) possible = true;
10771
+ else possible = alternatives.some((tokens, index) => {
10772
+ const bits = seen[index];
10773
+ for (let token = 0; token < tokens.length; token++) bits[token] ||= tokens[token].test(raw) || normalized !== raw && tokens[token].test(normalized);
10774
+ return bits.every(Boolean);
10775
+ });
10776
+ rawTail = raw.slice(-overlap);
10777
+ normalizedTail = normalized.slice(-overlap);
10778
+ };
10779
+ for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
10780
+ if (!possible) scan(decoder.end(), true);
10781
+ return possible;
10782
+ };
10783
+ }
10784
+ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10785
+ if (codex) {
10786
+ const info = await stat2(path);
10787
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10788
+ }
10789
+ const compressed = codex && path.endsWith(".jsonl.zst");
10790
+ if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10791
+ const input = createReadStream(path);
10792
+ const consume = async (chunks) => {
10793
+ let size = 0;
10794
+ async function* bounded() {
10795
+ for await (const chunk of chunks) {
10796
+ size += chunk.length;
10797
+ if (size > maxBytes) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
10798
+ yield chunk;
10799
+ }
10800
+ }
10801
+ return prefilter(bounded(), codex);
10802
+ };
10803
+ return compressed ? pipeline(input, zlib2.createZstdDecompress(), consume) : pipeline(input, consume);
10804
+ }
10805
+
10806
+ // src/history/summary-cache.ts
10807
+ import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10808
+ import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10809
+ import { homedir } from "node:os";
10810
+ import { join as join5 } from "node:path";
10811
+ var VERSION = "strict-representative-v1";
10812
+ var MAX_ENTRY_BYTES = 8 * 1024 * 1024;
10813
+ var FingerprintSchema = typebox_exports.Object({
10814
+ path: typebox_exports.String(),
10815
+ dev: typebox_exports.String(),
10816
+ ino: typebox_exports.String(),
10817
+ size: typebox_exports.String(),
10818
+ mtimeNs: typebox_exports.String(),
10819
+ ctimeNs: typebox_exports.String()
10820
+ }, { additionalProperties: false });
10821
+ var EventSchema = typebox_exports.Object({
10822
+ seq: typebox_exports.Integer({ minimum: 1 }),
10823
+ windowId: typebox_exports.String(),
10824
+ role: HistoryRoleSchema,
10825
+ createdAt: typebox_exports.Optional(typebox_exports.String()),
10826
+ text: typebox_exports.String(),
10827
+ execution: typebox_exports.Optional(typebox_exports.Object({
10828
+ name: typebox_exports.String(),
10829
+ status: ToolCallStatusSchema,
10830
+ arguments: typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())),
10831
+ outputTruncated: typebox_exports.Optional(typebox_exports.Boolean()),
10832
+ fullOutputPath: typebox_exports.Optional(typebox_exports.String()),
10833
+ nestedCalls: typebox_exports.Optional(typebox_exports.Object({ complete: typebox_exports.Boolean(), calls: typebox_exports.Array(typebox_exports.Object({
10834
+ id: typebox_exports.String(),
10835
+ name: typebox_exports.String(),
10836
+ status: ToolCallStatusSchema,
10837
+ arguments: typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())),
10838
+ argumentsBytes: typebox_exports.Optional(typebox_exports.Number()),
10839
+ durationMs: typebox_exports.Optional(typebox_exports.Number()),
10840
+ error: typebox_exports.Optional(typebox_exports.String())
10841
+ }, { additionalProperties: false })) }, { additionalProperties: false }))
10842
+ }, { additionalProperties: false }))
10843
+ }, { additionalProperties: false });
10844
+ var EntrySchema = typebox_exports.Object({
10845
+ version: typebox_exports.Literal(VERSION),
10846
+ path: typebox_exports.String(),
10847
+ session: typebox_exports.String(),
10848
+ event: typebox_exports.Union([EventSchema, typebox_exports.Null()]),
10849
+ notice: typebox_exports.Optional(typebox_exports.String()),
10850
+ fingerprints: typebox_exports.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
10851
+ lineageSources: typebox_exports.Array(typebox_exports.Object({ home: typebox_exports.String(), rolloutId: typebox_exports.String(), path: typebox_exports.String() }, { additionalProperties: false }), { maxItems: 63 })
10852
+ }, { additionalProperties: false });
10853
+ function historySummaryCacheRoot(home = homedir(), env = process.env, platform = process.platform) {
10854
+ return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
10855
+ }
10856
+ async function fingerprint(path) {
10857
+ const info = await stat3(path, { bigint: true });
10858
+ if (!info.isFile()) throw new Error("Not a regular transcript file");
10859
+ return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
10860
+ }
10861
+ async function unchanged(sources) {
10862
+ for (const source of sources) if (JSON.stringify(await fingerprint(source.path)) !== JSON.stringify(source)) return false;
10863
+ return true;
10864
+ }
10865
+ function completeDependencies(path, harness, sources, lineage) {
10866
+ if (harness !== "codex" && lineage.length !== 0) return false;
10867
+ const expected = [path, ...lineage.map((source) => source.path)];
10868
+ return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
10869
+ }
10870
+ async function readEntry(path) {
10871
+ const file = await open(path, "r");
10872
+ try {
10873
+ const info = await file.stat();
10874
+ if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return void 0;
10875
+ const buffer = Buffer.alloc(info.size + 1);
10876
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
10877
+ if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return void 0;
10878
+ return JSON.parse(buffer.toString("utf8", 0, bytesRead));
10879
+ } finally {
10880
+ await file.close();
10881
+ }
10882
+ }
10883
+ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
10884
+ let canonical, cachePath;
10885
+ const identity2 = sessionIdentity(session);
10886
+ try {
10887
+ canonical = await realpath3(transcriptPath);
10888
+ cachePath = join5(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
10889
+ const entry = await readEntry(cachePath);
10890
+ if (Check2(EntrySchema, entry) && entry.path === canonical && entry.session === identity2 && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources) && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints) && await realpath3(transcriptPath) === canonical) {
10891
+ return { event: entry.event === null ? void 0 : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
10892
+ }
10893
+ } catch {
10894
+ }
10895
+ const fingerprints = /* @__PURE__ */ new Map();
10896
+ let stable = canonical !== void 0;
10897
+ const track = async (path) => {
10898
+ try {
10899
+ if (!fingerprints.has(path)) fingerprints.set(path, await fingerprint(path));
10900
+ } catch {
10901
+ stable = false;
10902
+ }
10903
+ };
10904
+ if (canonical) await track(canonical);
10905
+ const { data, lineageSources = [] } = await load(track);
10906
+ const event = sessionRepresentative(data.projection, {});
10907
+ const result = { event, notice: data.notice };
10908
+ try {
10909
+ const sources = [...fingerprints.values()];
10910
+ if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources) || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath3(transcriptPath) !== canonical) return result;
10911
+ const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity2, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
10912
+ if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
10913
+ await mkdir2(cacheRoot, { recursive: true, mode: 448 });
10914
+ const temporary = `${cachePath}.${randomUUID3()}.tmp`;
10915
+ try {
10916
+ await writeFile2(temporary, entry, { flag: "wx", mode: 384 });
10917
+ await rename2(temporary, cachePath);
10918
+ } finally {
10919
+ await unlink2(temporary).catch(() => {
10920
+ });
10921
+ }
10922
+ } catch {
10923
+ }
10924
+ return result;
10620
10925
  }
10621
10926
 
10622
10927
  // src/history/local.ts
10623
10928
  function rootsFor(options) {
10624
10929
  const env = options.env ?? process.env;
10625
- const home = options.home ?? env.HOME ?? homedir();
10930
+ const home = options.home ?? env.HOME ?? homedir2();
10626
10931
  return {
10627
- pi: options.roots?.pi !== void 0 ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join5(env.PI_CODING_AGENT_DIR ?? join5(home, ".pi", "agent"), "sessions"),
10628
- claude: options.roots?.claude !== void 0 ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join5(env.CLAUDE_CONFIG_DIR ?? join5(home, ".claude"), "projects"),
10629
- codex: options.roots?.codex !== void 0 ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join5(env.CODEX_HOME ?? join5(home, ".codex"), "sessions")
10932
+ pi: options.roots?.pi !== void 0 ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join6(env.PI_CODING_AGENT_DIR ?? join6(home, ".pi", "agent"), "sessions"),
10933
+ claude: options.roots?.claude !== void 0 ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join6(env.CLAUDE_CONFIG_DIR ?? join6(home, ".claude"), "projects"),
10934
+ codex: options.roots?.codex !== void 0 ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join6(env.CODEX_HOME ?? join6(home, ".codex"), "sessions")
10630
10935
  };
10631
10936
  }
10632
10937
  async function filesAt(root, depth) {
@@ -10639,36 +10944,13 @@ async function filesAt(root, depth) {
10639
10944
  }
10640
10945
  const paths = [];
10641
10946
  for (const entry of entries) {
10642
- const path = join5(root, entry.name);
10947
+ const path = join6(root, entry.name);
10643
10948
  if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
10644
10949
  else if (entry.isFile() && depth === 0) paths.push(path);
10645
10950
  }
10646
10951
  return paths;
10647
10952
  }
10648
- var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10649
- copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
10650
- does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
10651
- not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
10652
- FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
10653
- the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
10654
- function escapeRegExp(value) {
10655
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10656
- }
10657
- function mayMatch(text, queries, codex) {
10658
- if (codex && text.includes('"history_base"')) return true;
10659
- const unescaped = text.includes("\\u") ? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))) : text;
10660
- return queries.some((query) => {
10661
- const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
10662
- return tokens === null || tokens.every((token) => {
10663
- const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
10664
- return parts.every((part) => {
10665
- const literal = new RegExp(escapeRegExp(part), "iu");
10666
- return literal.test(unescaped) || unescaped !== text && literal.test(text) || literal.test(PRESENTATION);
10667
- });
10668
- });
10669
- });
10670
- }
10671
- async function localSessions(harness, root) {
10953
+ async function localSessions(harness, root, cacheRoot, prefilters) {
10672
10954
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
10673
10955
  const sessions = [];
10674
10956
  for (const path of paths) {
@@ -10677,7 +10959,7 @@ async function localSessions(harness, root) {
10677
10959
  if (!id2) continue;
10678
10960
  let modifiedAt;
10679
10961
  try {
10680
- modifiedAt = (await stat2(path)).mtimeMs;
10962
+ modifiedAt = (await stat4(path)).mtimeMs;
10681
10963
  } catch (error) {
10682
10964
  if (error.code === "ENOENT") continue;
10683
10965
  throw error;
@@ -10686,13 +10968,31 @@ async function localSessions(harness, root) {
10686
10968
  harness,
10687
10969
  id: id2,
10688
10970
  modifiedAt,
10971
+ async loadRepresentative() {
10972
+ return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
10973
+ if (harness === "codex") {
10974
+ const readBytes = createCodexTranscriptReader();
10975
+ const history = await readCodexHistory({ threadId: id2, transcriptPath: path }, async (source, remaining) => {
10976
+ await track(source);
10977
+ return readBytes(source, remaining);
10978
+ });
10979
+ return { data: { projection: history.projection }, lineageSources: history.lineageSources };
10980
+ }
10981
+ const data = await this.load();
10982
+ if (!data) throw new Error("Session returned no history");
10983
+ return { data };
10984
+ });
10985
+ },
10689
10986
  async load(queries) {
10690
- if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
10691
- const text = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile4(path, "utf8");
10692
- if (queries?.length && !mayMatch(text, queries, harness === "codex")) return void 0;
10987
+ if (queries?.length) {
10988
+ let prefilter = prefilters.get(queries);
10989
+ if (!prefilter) prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
10990
+ if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return void 0;
10991
+ }
10693
10992
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
10993
+ const text = await readFile4(path, "utf8");
10694
10994
  if (harness === "pi") return { projection: piHistoryFromJsonl(text, id2) };
10695
- const projection = claudeHistoryFromJsonl(text, { sessionId: id2, headUuid: offlineClaudeHead(text) });
10995
+ const projection = offlineClaudeHistoryFromJsonl(text, id2);
10696
10996
  const missing = projection.missingAncestors;
10697
10997
  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.
10698
10998
 
@@ -10707,17 +11007,20 @@ function localHistoryCorpus(options) {
10707
11007
  currentHarness: options.current.harness,
10708
11008
  async sessions(onlyHarness) {
10709
11009
  const roots = rootsFor(options);
11010
+ const env = options.env ?? process.env;
11011
+ const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir2(), env);
10710
11012
  const discovered = [];
11013
+ const prefilters = /* @__PURE__ */ new WeakMap();
10711
11014
  for (const harness of ["pi", "claude", "codex"]) {
10712
11015
  if (onlyHarness !== void 0 && onlyHarness !== harness) continue;
10713
11016
  const root = roots[harness];
10714
- if (root != null) discovered.push(...await localSessions(harness, root));
11017
+ if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
10715
11018
  }
10716
11019
  if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
10717
11020
  discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
10718
11021
  const unique = /* @__PURE__ */ new Map();
10719
11022
  for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
10720
- const current = { ...options.current, modifiedAt: Date.now() };
11023
+ const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
10721
11024
  if (onlyHarness === void 0 || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
10722
11025
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
10723
11026
  }