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
@@ -24422,13 +24422,13 @@ function Default(...args) {
24422
24422
  }
24423
24423
 
24424
24424
  // node_modules/typebox/build/value/pipeline/pipeline.mjs
24425
- function Pipeline(pipeline) {
24425
+ function Pipeline(pipeline2) {
24426
24426
  return (...args) => {
24427
24427
  const [context2, type, value] = arguments_exports.Match(args, {
24428
24428
  3: (context3, type2, value2) => [context3, type2, value2],
24429
24429
  2: (type2, value2) => [{}, type2, value2]
24430
24430
  });
24431
- return pipeline.reduce((result, func) => func(context2, type, result), value);
24431
+ return pipeline2.reduce((result, func) => func(context2, type, result), value);
24432
24432
  };
24433
24433
  }
24434
24434
 
@@ -25655,7 +25655,7 @@ function createNotesStore(input) {
25655
25655
  const [first, second] = [fromPath, path].sort();
25656
25656
  return withPathQueue(first, () => withPathQueue(second, mutate));
25657
25657
  }
25658
- async function rename3(fromAddress, toAddress) {
25658
+ async function rename4(fromAddress, toAddress) {
25659
25659
  const { meta: meta2, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
25660
25660
  return { meta: meta2, replacedCrumpledTarget };
25661
25661
  }
@@ -25755,7 +25755,7 @@ function createNotesStore(input) {
25755
25755
  function searchWithStatus(queries, options = {}) {
25756
25756
  return searchRows(queries, options, { namespacesUnavailable: [] });
25757
25757
  }
25758
- return { write, read, update, rename: rename3, forget, list, search, listWithStatus, searchWithStatus };
25758
+ return { write, read, update, rename: rename4, forget, list, search, listWithStatus, searchWithStatus };
25759
25759
  }
25760
25760
 
25761
25761
  // src/tools/output.ts
@@ -25958,8 +25958,16 @@ function nestedCallSummary(event) {
25958
25958
  const nested = event.execution?.nestedCalls;
25959
25959
  return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
25960
25960
  }
25961
+ var HistoryFoldedRowSchema = typebox_exports.Object({
25962
+ session: typebox_exports.Optional(typebox_exports.String()),
25963
+ first_seq: typebox_exports.Integer({ minimum: 1 }),
25964
+ last_seq: typebox_exports.Integer({ minimum: 1 }),
25965
+ count: typebox_exports.Integer({ minimum: 1 }),
25966
+ tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
25967
+ }, { additionalProperties: false });
25961
25968
  var HistoryPageItemSchema = typebox_exports.Object({
25962
25969
  session: typebox_exports.Optional(typebox_exports.String()),
25970
+ folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
25963
25971
  seq: typebox_exports.Integer({ minimum: 1 }),
25964
25972
  role: HistoryRoleSchema,
25965
25973
  created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
@@ -25968,14 +25976,6 @@ var HistoryPageItemSchema = typebox_exports.Object({
25968
25976
  truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
25969
25977
  offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
25970
25978
  }, { additionalProperties: false });
25971
- var HistoryFoldedRowSchema = typebox_exports.Object({
25972
- session: typebox_exports.Optional(typebox_exports.String()),
25973
- folded: typebox_exports.Literal(true),
25974
- first_seq: typebox_exports.Integer({ minimum: 1 }),
25975
- last_seq: typebox_exports.Integer({ minimum: 1 }),
25976
- count: typebox_exports.Integer({ minimum: 1 }),
25977
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
25978
- }, { additionalProperties: false });
25979
25979
  var MAX_FOLD_TOOL_NAMES = 20;
25980
25980
  var MAX_FOLD_TOOL_NAME_CHARS = 120;
25981
25981
  function visibleItem(event, maxChars, matchOffset) {
@@ -26360,6 +26360,14 @@ var notesSearch = {
26360
26360
  };
26361
26361
 
26362
26362
  // src/history/query.ts
26363
+ var multiPages = /* @__PURE__ */ new WeakSet();
26364
+ function isMultiPage(page) {
26365
+ return multiPages.has(page);
26366
+ }
26367
+ function markMultiPage(page) {
26368
+ multiPages.add(page);
26369
+ return page;
26370
+ }
26363
26371
  var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
26364
26372
  function timeBound(name, value) {
26365
26373
  if (value === void 0) return success(void 0);
@@ -26377,20 +26385,12 @@ function resolveTimeBounds(params) {
26377
26385
  }
26378
26386
  return success({ ...since.data === void 0 ? {} : { sinceMs: since.data }, ...until.data === void 0 ? {} : { untilMs: until.data } });
26379
26387
  }
26380
- var HistoryOlderSchema = typebox_exports.Object({
26381
- session: typebox_exports.Optional(typebox_exports.String()),
26382
- before_seq: typebox_exports.Integer({ minimum: 1 })
26383
- }, { additionalProperties: false });
26384
- var HistoryNewerSchema = typebox_exports.Object({
26385
- session: typebox_exports.Optional(typebox_exports.String()),
26386
- after_seq: typebox_exports.Integer({ minimum: 1 }),
26387
- from: typebox_exports.Literal("oldest")
26388
- }, { additionalProperties: false });
26389
26388
  var HistoryPageSchema = typebox_exports.Object({
26390
26389
  notice: typebox_exports.Optional(typebox_exports.String()),
26391
- items: typebox_exports.Array(typebox_exports.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
26392
- page_older: typebox_exports.Union([HistoryOlderSchema, typebox_exports.Null()], { description: "Args to merge into `history_list` for older events." }),
26393
- page_newer: typebox_exports.Union([HistoryNewerSchema, typebox_exports.Null()], { description: "Args to merge into `history_list` for newer events." })
26390
+ items: typebox_exports.Array(HistoryPageItemSchema),
26391
+ folded_after: typebox_exports.Optional(HistoryFoldedRowSchema),
26392
+ has_older: typebox_exports.Boolean(),
26393
+ has_newer: typebox_exports.Boolean()
26394
26394
  }, { additionalProperties: false });
26395
26395
  function truncateHistoryItem(item, fits) {
26396
26396
  if (fits(item)) return item;
@@ -26415,7 +26415,7 @@ function foldedRun(events, session) {
26415
26415
  }
26416
26416
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
26417
26417
  const tools2 = Object.fromEntries(entries);
26418
- return { ...session === void 0 ? {} : { session }, folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools: tools2 };
26418
+ return { ...session === void 0 ? {} : { session }, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools: tools2 };
26419
26419
  }
26420
26420
  function prepareSelection(projection, params) {
26421
26421
  const folds = !params.roles && params.query === void 0;
@@ -26436,19 +26436,19 @@ function prepareSelection(projection, params) {
26436
26436
  }
26437
26437
  function pageData(prepared, start, end, maxChars, preview) {
26438
26438
  const { candidates, tail } = prepared;
26439
- const identity = prepared.session === void 0 ? {} : { session: prepared.session };
26440
26439
  const items = [];
26441
26440
  for (let index = start; index < end; index++) {
26442
26441
  const candidate = candidates[index];
26443
- if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
26444
- items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } }));
26442
+ const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } });
26443
+ items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
26445
26444
  }
26446
- if (end === candidates.length && tail) items.push(tail);
26447
- return {
26445
+ const page = {
26448
26446
  items,
26449
- page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start].event.seq } : null,
26450
- page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1].event.seq, from: "oldest" } : null
26447
+ ...end === candidates.length && tail ? { folded_after: tail } : {},
26448
+ has_older: start > 0 && start < end || !!prepared.discarded && prepared.from !== "oldest",
26449
+ has_newer: end < candidates.length && start < end || !!prepared.discarded && prepared.from === "oldest"
26451
26450
  };
26451
+ return prepared.multi ? markMultiPage(page) : page;
26452
26452
  }
26453
26453
  function resolveSelection(params) {
26454
26454
  const bounds = resolveTimeBounds(params);
@@ -26475,19 +26475,62 @@ function sessionRepresentative(projection, scoped) {
26475
26475
  if (scoped.roles) return events.at(-1);
26476
26476
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
26477
26477
  }
26478
- function selectCorpusPage(sessions, scoped, fits, maxChars) {
26479
- const candidates = sessions.flatMap(({ session, projection }) => {
26480
- if (scoped.query !== void 0) return prepareSelection(projection, { ...scoped, session }).candidates;
26481
- const event = sessionRepresentative(projection, scoped);
26482
- return event === void 0 ? [] : [{ session, event }];
26483
- });
26484
- const time3 = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
26485
- candidates.sort((a, b) => time3(a.event) - time3(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq);
26486
- return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
26487
- }
26478
+ var eventTime = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
26479
+ var compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
26480
+ var CorpusCollector = class {
26481
+ constructor(scoped) {
26482
+ this.scoped = scoped;
26483
+ this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
26484
+ }
26485
+ scoped;
26486
+ candidates = [];
26487
+ limit;
26488
+ discarded = false;
26489
+ admit(candidate) {
26490
+ let low = 0, high = this.candidates.length;
26491
+ while (low < high) {
26492
+ const mid = low + high >>> 1;
26493
+ if (compareCorpus(this.candidates[mid], candidate) <= 0) low = mid + 1;
26494
+ else high = mid;
26495
+ }
26496
+ if (this.candidates.length === this.limit) {
26497
+ this.discarded = true;
26498
+ if (this.scoped.from === "oldest") {
26499
+ if (low === this.limit) return;
26500
+ this.candidates.pop();
26501
+ } else {
26502
+ if (low === 0) return;
26503
+ this.candidates.shift();
26504
+ low--;
26505
+ }
26506
+ }
26507
+ this.candidates.splice(low, 0, candidate);
26508
+ }
26509
+ /** Admit an already selected strict overview event without selecting it a second time. */
26510
+ addRepresentative(session, event) {
26511
+ if (!event) return false;
26512
+ this.admit({ session, event });
26513
+ return true;
26514
+ }
26515
+ /** Returns whether this session contributes an overview representative. */
26516
+ add(session, projection) {
26517
+ if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
26518
+ for (const event of filteredItems(projection, this.scoped, false)) {
26519
+ const document = eventDocument(event);
26520
+ if ((event.role === "user" || event.role === "assistant") && document === "") continue;
26521
+ const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
26522
+ if (matchOffset >= 0) this.admit({ session, event, matchOffset });
26523
+ }
26524
+ return true;
26525
+ }
26526
+ page(fits, maxChars, unvisited = false) {
26527
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
26528
+ }
26529
+ };
26488
26530
  function selectPrepared(prepared, scoped, fits, maxChars) {
26489
26531
  const { candidates } = prepared;
26490
- const newest = scoped.from !== "oldest";
26532
+ const from = scoped.from ?? (scoped.after_seq !== void 0 ? "oldest" : "newest");
26533
+ const newest = from === "newest";
26491
26534
  let start = newest ? candidates.length : 0;
26492
26535
  let end = start;
26493
26536
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -26550,13 +26593,27 @@ async function resolveSession(corpus, selector) {
26550
26593
  if (matches.length > 1) return failure2("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.`);
26551
26594
  return success(matches[0]);
26552
26595
  }
26596
+ async function loadHistoryRepresentative(session) {
26597
+ if (session.loadRepresentative) {
26598
+ try {
26599
+ return success(await session.loadRepresentative());
26600
+ } catch (error2) {
26601
+ return unavailableSession(session, error2);
26602
+ }
26603
+ }
26604
+ const result = await loadHistorySession(session);
26605
+ return result.ok ? success({ event: sessionRepresentative(result.data.projection, {}), notice: result.data.notice }) : result;
26606
+ }
26607
+ function unavailableSession(session, error2) {
26608
+ return failure2("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error2 instanceof Error ? error2.message : String(error2)}`);
26609
+ }
26553
26610
  async function loadHistorySession(session, queries) {
26554
26611
  try {
26555
26612
  const data = await session.load(queries);
26556
26613
  if (data === void 0 && !queries?.length) throw new Error("Session returned no history");
26557
26614
  return success(data);
26558
26615
  } catch (error2) {
26559
- return failure2("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error2 instanceof Error ? error2.message : String(error2)}`);
26616
+ return unavailableSession(session, error2);
26560
26617
  }
26561
26618
  }
26562
26619
  function currentHistory(context2) {
@@ -26597,15 +26654,23 @@ function renderFoldedRow(row) {
26597
26654
  const tools2 = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
26598
26655
  const identity = row.session === void 0 ? {} : { session: row.session };
26599
26656
  const expand = `
26600
- \u2192 expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
26657
+ \u2192 expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
26601
26658
  return `${row.session === void 0 ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools2 ? ` | ${tools2}` : ""}${expand}`;
26602
26659
  }
26603
26660
  function renderPage(page) {
26604
- if (page.items.length === 0) return `${page.notice ?? ""}No events match these filters.`;
26605
- const body = page.items.map((item) => "folded" in item ? renderFoldedRow(item) : renderPageItem(item)).join("\n\n");
26661
+ if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
26662
+ 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");
26663
+ if (isMultiPage(page)) {
26664
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
26665
+ return (page.notice ?? "") + body + (directions ? `
26666
+
26667
+ \u2192 more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
26668
+ }
26669
+ const first = page.items[0];
26670
+ const last = page.items.at(-1);
26606
26671
  const cursors = [
26607
- page.page_older === null ? "" : `\u2192 older: ${JSON.stringify(page.page_older)}`,
26608
- page.page_newer === null ? "" : `\u2192 newer: ${JSON.stringify(page.page_newer)}`
26672
+ page.has_older ? `\u2192 older: ${JSON.stringify({ ...first.session === void 0 ? {} : { session: first.session }, before_seq: first.seq })}` : "",
26673
+ page.has_newer ? `\u2192 newer: ${JSON.stringify({ ...last.session === void 0 ? {} : { session: last.session }, after_seq: last.seq })}` : ""
26609
26674
  ].filter((line) => line !== "");
26610
26675
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}
26611
26676
 
@@ -26613,8 +26678,7 @@ ${cursors.join(" | ")}`);
26613
26678
  }
26614
26679
  function renderRead(data) {
26615
26680
  const tool = toolHeader(data);
26616
- const afterSeq = data.seq - 10;
26617
- 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 })})`;
26681
+ 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 })})`;
26618
26682
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
26619
26683
  }
26620
26684
  var plainText = (text2) => text2;
@@ -26624,11 +26688,11 @@ var historyListParameters = typebox_exports.Object({
26624
26688
  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.")),
26625
26689
  roles: historyRoles(),
26626
26690
  before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
26627
- after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
26691
+ after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
26628
26692
  since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
26629
26693
  until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
26630
- 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." })),
26631
- limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
26694
+ 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." })),
26695
+ limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
26632
26696
  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.` }))
26633
26697
  }, { additionalProperties: false });
26634
26698
  var historyList = {
@@ -26651,19 +26715,26 @@ var historyList = {
26651
26715
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
26652
26716
  const queries = Array.isArray(scoped.data.query) ? scoped.data.query : void 0;
26653
26717
  if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
26654
- const loaded2 = [];
26718
+ const representative = !queries && scoped.data.roles === void 0 && scoped.data.since === void 0 && scoped.data.until === void 0;
26719
+ const collector = new CorpusCollector(scoped.data);
26720
+ let qualifying = 0;
26655
26721
  const notices = [];
26656
- for (const session of sessions) {
26657
- const result3 = await loadHistorySession(session, queries);
26722
+ let unvisited = false;
26723
+ for (const [index, session] of sessions.entries()) {
26724
+ const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
26658
26725
  if (!result3.ok || !result3.data) continue;
26659
- if (!queries && !sessionRepresentative(result3.data.projection, scoped.data)) continue;
26660
- loaded2.push({ session: sessionIdentity(session), projection: result3.data.projection });
26726
+ const added = "projection" in result3.data ? collector.add(sessionIdentity(session), result3.data.projection) : collector.addRepresentative(sessionIdentity(session), result3.data.event);
26727
+ if (!added) continue;
26728
+ qualifying++;
26661
26729
  if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
26662
- if (!queries && loaded2.length >= Math.max(1, params.limit ?? 20)) break;
26730
+ if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
26731
+ unvisited = index + 1 < sessions.length;
26732
+ break;
26733
+ }
26663
26734
  }
26664
26735
  const notice2 = notices.length ? { notice: notices.join("") } : {};
26665
- const result2 = selectCorpusPage(loaded2, scoped.data, (page) => fits({ ...page, ...notice2 }), maxChars);
26666
- return result2.ok ? success({ ...result2.data, ...notice2 }) : result2;
26736
+ const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
26737
+ return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
26667
26738
  }
26668
26739
  const target = await resolveSession(corpus, selector.data);
26669
26740
  if (!target.ok) return target;
@@ -26861,7 +26932,7 @@ var UUID_RE = new RegExp(`^${UUID}$`);
26861
26932
  var FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
26862
26933
  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"]);
26863
26934
  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"]);
26864
- var MAX_BYTES = 128 * 1024 * 1024;
26935
+ var CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
26865
26936
  var MAX_SEGMENTS = 64;
26866
26937
  var MAX_DIRECTORY_ENTRIES = 1e5;
26867
26938
  function nativeObject(value, field) {
@@ -26995,26 +27066,54 @@ async function referencedPath(home, rolloutId) {
26995
27066
  if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
26996
27067
  return matches[0];
26997
27068
  }
26998
- async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
26999
- const info = await stat(path);
27000
- if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
27001
- const bytes = await readFile3(path);
27002
- if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
27003
- const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
27004
- if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
27005
- return decoded;
27069
+ async function resolveLineageSource(home, rolloutId) {
27070
+ const path = await realpath2(await referencedPath(home, rolloutId));
27071
+ if (![join5(home, "sessions"), join5(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
27072
+ return path;
27073
+ }
27074
+ async function validateCodexLineageSources(sources) {
27075
+ try {
27076
+ for (const source of sources) if (await resolveLineageSource(source.home, source.rolloutId) !== source.path) return false;
27077
+ return true;
27078
+ } catch {
27079
+ return false;
27080
+ }
27081
+ }
27082
+ function createCodexTranscriptReader() {
27083
+ const cache = /* @__PURE__ */ new Map();
27084
+ return async (path, remaining = CODEX_TRANSCRIPT_MAX_BYTES) => {
27085
+ const canonical = await realpath2(path);
27086
+ let pending = cache.get(canonical);
27087
+ if (!pending) {
27088
+ pending = (async () => {
27089
+ const info = await stat(canonical);
27090
+ if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
27091
+ const stored = await readFile3(canonical);
27092
+ if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
27093
+ if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
27094
+ const bytes2 = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
27095
+ return { bytes: bytes2, storedSize: Math.max(info.size, stored.length) };
27096
+ })();
27097
+ cache.set(canonical, pending);
27098
+ }
27099
+ const { bytes, storedSize } = await pending;
27100
+ if (storedSize > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
27101
+ if (bytes.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
27102
+ return bytes;
27103
+ };
27006
27104
  }
27007
- async function readCodexTranscript(source) {
27105
+ async function readCodexTranscript(source, readBytes = createCodexTranscriptReader()) {
27008
27106
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
27009
27107
  id(source.threadId, "requested threadId");
27010
27108
  try {
27011
27109
  let path = await realpath2(source.transcriptPath), cutoff, home;
27012
- let remaining = MAX_BYTES;
27110
+ let remaining = CODEX_TRANSCRIPT_MAX_BYTES;
27013
27111
  const segments = [], seen = /* @__PURE__ */ new Set();
27112
+ const lineageSources = [];
27014
27113
  while (true) {
27015
27114
  if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
27016
27115
  seen.add(path);
27017
- const bytes = await readCodexTranscriptBytes(path, remaining);
27116
+ const bytes = await readBytes(path, remaining);
27018
27117
  remaining -= bytes.length;
27019
27118
  const segment = segmentFromBytes(bytes, cutoff);
27020
27119
  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)`);
@@ -27027,8 +27126,8 @@ async function readCodexTranscript(source) {
27027
27126
  if (!base) break;
27028
27127
  if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
27029
27128
  home ??= storageHome(path);
27030
- path = await realpath2(await referencedPath(home, base.thread_id));
27031
- if (![join5(home, "sessions"), join5(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
27129
+ path = await resolveLineageSource(home, base.thread_id);
27130
+ lineageSources.push({ home, rolloutId: base.thread_id, path });
27032
27131
  cutoff = base;
27033
27132
  }
27034
27133
  for (let index = 0; index < segments.length; index++) {
@@ -27078,7 +27177,7 @@ async function readCodexTranscript(source) {
27078
27177
  }
27079
27178
  Object.assign(state, { currentWindowId: window, currentWindowNumber: number3, firstWindowId: first, previousWindowId: previousWindow });
27080
27179
  if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
27081
- return { state, records, highestSeq: lastSeq };
27180
+ return { state, records, highestSeq: lastSeq, dependencies: [...seen], lineageSources };
27082
27181
  } catch (error2) {
27083
27182
  throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error2 instanceof Error ? error2.message : String(error2)}`, { cause: error2 });
27084
27183
  }
@@ -27190,8 +27289,8 @@ function standaloneTool(record2, item) {
27190
27289
  const name = `${nativeString(item.server, "MCP server")}/${nativeString(item.tool, "MCP tool")}`;
27191
27290
  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" };
27192
27291
  }
27193
- async function readCodexHistory(source) {
27194
- const { state, records, highestSeq } = await readCodexTranscript(source);
27292
+ async function readCodexHistory(source, readBytes) {
27293
+ const { state, records, highestSeq, dependencies, lineageSources } = await readCodexTranscript(source, readBytes);
27195
27294
  const facts = /* @__PURE__ */ new Map(), callsSeen = /* @__PURE__ */ new Set(), responseIdsSeen = /* @__PURE__ */ new Set();
27196
27295
  const windows = /* @__PURE__ */ new Map(), branchSeqs = /* @__PURE__ */ new Set();
27197
27296
  const addWindow = (nativeId, createdAt) => {
@@ -27286,13 +27385,13 @@ replacement_history is an inference checkpoint, not new conversation events.`);
27286
27385
  }
27287
27386
  if (item) addWindow(record2.windowId).items.push({ ...item, windowId: `codex:${source.threadId}:${record2.windowId}` });
27288
27387
  }
27289
- return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
27388
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs), dependencies, lineageSources };
27290
27389
  }
27291
27390
 
27292
27391
  // src/history/local.ts
27293
- import { readdir as readdir4, readFile as readFile4, stat as stat2 } from "node:fs/promises";
27294
- import { homedir as homedir2 } from "node:os";
27295
- import { join as join6 } from "node:path";
27392
+ import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
27393
+ import { homedir as homedir3 } from "node:os";
27394
+ import { join as join7 } from "node:path";
27296
27395
 
27297
27396
  // src/history/pi.ts
27298
27397
  function mapRole(role) {
@@ -27551,10 +27650,10 @@ function bootOrdinal(row, retained) {
27551
27650
  const ordinal = Number(suffix);
27552
27651
  return Number.isSafeInteger(ordinal) ? ordinal : void 0;
27553
27652
  }
27554
- function claudeHistoryFromJsonl(text2, source) {
27653
+ function claudeHistoryFromRows(rows, source) {
27555
27654
  const nodes = /* @__PURE__ */ new Map();
27556
27655
  let nextSeq = 1;
27557
- for (const row of rowsOf(text2)) {
27656
+ for (const row of rows) {
27558
27657
  if (!MESSAGE_TYPES.has(row.type)) continue;
27559
27658
  const uuid2 = requiredString(row.uuid, "uuid");
27560
27659
  parent(row);
@@ -27673,9 +27772,9 @@ function claudeHistoryFromJsonl(text2, source) {
27673
27772
  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);
27674
27773
  return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : void 0 };
27675
27774
  }
27676
- function offlineClaudeHead(text2) {
27775
+ function offlineClaudeHeadFromRows(rows) {
27677
27776
  const latest = /* @__PURE__ */ new Map();
27678
- for (const row of rowsOf(text2)) {
27777
+ for (const row of rows) {
27679
27778
  if (!MESSAGE_TYPES.has(row.type)) continue;
27680
27779
  const uuid2 = requiredString(row.uuid, "uuid");
27681
27780
  latest.delete(uuid2);
@@ -27707,15 +27806,218 @@ function offlineClaudeHead(text2) {
27707
27806
  const candidates = nonAttachments.length ? nonAttachments : leaves;
27708
27807
  return candidates.at(-1);
27709
27808
  }
27809
+ function offlineClaudeHistoryFromJsonl(text2, sessionId) {
27810
+ const rows = rowsOf(text2);
27811
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
27812
+ }
27813
+
27814
+ // src/history/prefilter.ts
27815
+ import { createReadStream } from "node:fs";
27816
+ import { stat as stat2 } from "node:fs/promises";
27817
+ import { pipeline } from "node:stream/promises";
27818
+ import { StringDecoder } from "node:string_decoder";
27819
+ import * as zlib2 from "node:zlib";
27820
+ var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
27821
+ copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
27822
+ does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
27823
+ not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
27824
+ FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
27825
+ the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
27826
+ var HISTORY_BASE = '"history_base"';
27827
+ function createHistoryPrefilter(queries) {
27828
+ let overlap = HISTORY_BASE.length;
27829
+ const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
27830
+ const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
27831
+ return parts.map((part) => {
27832
+ overlap = Math.max(overlap, part.length);
27833
+ return new RegExp(part, "iu");
27834
+ }).filter((literal2) => !literal2.test(PRESENTATION));
27835
+ }));
27836
+ const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
27837
+ return async (chunks, codex = false) => {
27838
+ const decoder = new StringDecoder("utf8");
27839
+ const seen = alternatives.map((tokens) => tokens.map(() => false));
27840
+ let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
27841
+ const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
27842
+ const scan = (chunk, final = false) => {
27843
+ const raw = rawTail + chunk, source = pending + chunk;
27844
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
27845
+ pending = "";
27846
+ const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
27847
+ if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
27848
+ const literal2 = hex === void 0 ? "\\" : `\\u${hex}`;
27849
+ if (!final && offset + match.length === source.length) {
27850
+ pending = literal2;
27851
+ return "";
27852
+ }
27853
+ return literal2;
27854
+ }) : chunk;
27855
+ const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
27856
+ if (codex && raw.includes(HISTORY_BASE)) possible = true;
27857
+ else possible = alternatives.some((tokens, index) => {
27858
+ const bits = seen[index];
27859
+ for (let token = 0; token < tokens.length; token++) bits[token] ||= tokens[token].test(raw) || normalized !== raw && tokens[token].test(normalized);
27860
+ return bits.every(Boolean);
27861
+ });
27862
+ rawTail = raw.slice(-overlap);
27863
+ normalizedTail = normalized.slice(-overlap);
27864
+ };
27865
+ for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
27866
+ if (!possible) scan(decoder.end(), true);
27867
+ return possible;
27868
+ };
27869
+ }
27870
+ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
27871
+ if (codex) {
27872
+ const info = await stat2(path);
27873
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
27874
+ }
27875
+ const compressed = codex && path.endsWith(".jsonl.zst");
27876
+ if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
27877
+ const input = createReadStream(path);
27878
+ const consume = async (chunks) => {
27879
+ let size = 0;
27880
+ async function* bounded() {
27881
+ for await (const chunk of chunks) {
27882
+ size += chunk.length;
27883
+ if (size > maxBytes) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
27884
+ yield chunk;
27885
+ }
27886
+ }
27887
+ return prefilter(bounded(), codex);
27888
+ };
27889
+ return compressed ? pipeline(input, zlib2.createZstdDecompress(), consume) : pipeline(input, consume);
27890
+ }
27891
+
27892
+ // src/history/summary-cache.ts
27893
+ import { createHash, randomUUID as randomUUID3 } from "node:crypto";
27894
+ import { mkdir as mkdir3, open as open2, realpath as realpath3, rename as rename3, stat as stat3, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
27895
+ import { homedir as homedir2 } from "node:os";
27896
+ import { join as join6 } from "node:path";
27897
+ var VERSION = "strict-representative-v1";
27898
+ var MAX_ENTRY_BYTES = 8 * 1024 * 1024;
27899
+ var FingerprintSchema = typebox_exports.Object({
27900
+ path: typebox_exports.String(),
27901
+ dev: typebox_exports.String(),
27902
+ ino: typebox_exports.String(),
27903
+ size: typebox_exports.String(),
27904
+ mtimeNs: typebox_exports.String(),
27905
+ ctimeNs: typebox_exports.String()
27906
+ }, { additionalProperties: false });
27907
+ var EventSchema = typebox_exports.Object({
27908
+ seq: typebox_exports.Integer({ minimum: 1 }),
27909
+ windowId: typebox_exports.String(),
27910
+ role: HistoryRoleSchema,
27911
+ createdAt: typebox_exports.Optional(typebox_exports.String()),
27912
+ text: typebox_exports.String(),
27913
+ execution: typebox_exports.Optional(typebox_exports.Object({
27914
+ name: typebox_exports.String(),
27915
+ status: ToolCallStatusSchema,
27916
+ arguments: typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())),
27917
+ outputTruncated: typebox_exports.Optional(typebox_exports.Boolean()),
27918
+ fullOutputPath: typebox_exports.Optional(typebox_exports.String()),
27919
+ nestedCalls: typebox_exports.Optional(typebox_exports.Object({ complete: typebox_exports.Boolean(), calls: typebox_exports.Array(typebox_exports.Object({
27920
+ id: typebox_exports.String(),
27921
+ name: typebox_exports.String(),
27922
+ status: ToolCallStatusSchema,
27923
+ arguments: typebox_exports.Optional(typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())),
27924
+ argumentsBytes: typebox_exports.Optional(typebox_exports.Number()),
27925
+ durationMs: typebox_exports.Optional(typebox_exports.Number()),
27926
+ error: typebox_exports.Optional(typebox_exports.String())
27927
+ }, { additionalProperties: false })) }, { additionalProperties: false }))
27928
+ }, { additionalProperties: false }))
27929
+ }, { additionalProperties: false });
27930
+ var EntrySchema = typebox_exports.Object({
27931
+ version: typebox_exports.Literal(VERSION),
27932
+ path: typebox_exports.String(),
27933
+ session: typebox_exports.String(),
27934
+ event: typebox_exports.Union([EventSchema, typebox_exports.Null()]),
27935
+ notice: typebox_exports.Optional(typebox_exports.String()),
27936
+ fingerprints: typebox_exports.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
27937
+ lineageSources: typebox_exports.Array(typebox_exports.Object({ home: typebox_exports.String(), rolloutId: typebox_exports.String(), path: typebox_exports.String() }, { additionalProperties: false }), { maxItems: 63 })
27938
+ }, { additionalProperties: false });
27939
+ function historySummaryCacheRoot(home = homedir2(), env = process.env, platform = process.platform) {
27940
+ return platform === "darwin" ? join6(home, "Library/Caches/notesoup/history") : join6(env.XDG_CACHE_HOME || join6(home, ".cache"), "notesoup/history");
27941
+ }
27942
+ async function fingerprint(path) {
27943
+ const info = await stat3(path, { bigint: true });
27944
+ if (!info.isFile()) throw new Error("Not a regular transcript file");
27945
+ return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
27946
+ }
27947
+ async function unchanged(sources) {
27948
+ for (const source of sources) if (JSON.stringify(await fingerprint(source.path)) !== JSON.stringify(source)) return false;
27949
+ return true;
27950
+ }
27951
+ function completeDependencies(path, harness, sources, lineage) {
27952
+ if (harness !== "codex" && lineage.length !== 0) return false;
27953
+ const expected = [path, ...lineage.map((source) => source.path)];
27954
+ return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
27955
+ }
27956
+ async function readEntry(path) {
27957
+ const file = await open2(path, "r");
27958
+ try {
27959
+ const info = await file.stat();
27960
+ if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return void 0;
27961
+ const buffer = Buffer.alloc(info.size + 1);
27962
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
27963
+ if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return void 0;
27964
+ return JSON.parse(buffer.toString("utf8", 0, bytesRead));
27965
+ } finally {
27966
+ await file.close();
27967
+ }
27968
+ }
27969
+ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
27970
+ let canonical, cachePath;
27971
+ const identity = sessionIdentity(session);
27972
+ try {
27973
+ canonical = await realpath3(transcriptPath);
27974
+ cachePath = join6(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
27975
+ const entry = await readEntry(cachePath);
27976
+ if (Check2(EntrySchema, entry) && entry.path === canonical && entry.session === identity && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources) && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints) && await realpath3(transcriptPath) === canonical) {
27977
+ return { event: entry.event === null ? void 0 : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
27978
+ }
27979
+ } catch {
27980
+ }
27981
+ const fingerprints = /* @__PURE__ */ new Map();
27982
+ let stable = canonical !== void 0;
27983
+ const track = async (path) => {
27984
+ try {
27985
+ if (!fingerprints.has(path)) fingerprints.set(path, await fingerprint(path));
27986
+ } catch {
27987
+ stable = false;
27988
+ }
27989
+ };
27990
+ if (canonical) await track(canonical);
27991
+ const { data, lineageSources = [] } = await load(track);
27992
+ const event = sessionRepresentative(data.projection, {});
27993
+ const result = { event, notice: data.notice };
27994
+ try {
27995
+ const sources = [...fingerprints.values()];
27996
+ if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources) || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath3(transcriptPath) !== canonical) return result;
27997
+ const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
27998
+ if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
27999
+ await mkdir3(cacheRoot, { recursive: true, mode: 448 });
28000
+ const temporary = `${cachePath}.${randomUUID3()}.tmp`;
28001
+ try {
28002
+ await writeFile3(temporary, entry, { flag: "wx", mode: 384 });
28003
+ await rename3(temporary, cachePath);
28004
+ } finally {
28005
+ await unlink2(temporary).catch(() => {
28006
+ });
28007
+ }
28008
+ } catch {
28009
+ }
28010
+ return result;
28011
+ }
27710
28012
 
27711
28013
  // src/history/local.ts
27712
28014
  function rootsFor(options) {
27713
28015
  const env = options.env ?? process.env;
27714
- const home = options.home ?? env.HOME ?? homedir2();
28016
+ const home = options.home ?? env.HOME ?? homedir3();
27715
28017
  return {
27716
- 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"),
27717
- claude: options.roots?.claude !== void 0 ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join6(env.CLAUDE_CONFIG_DIR ?? join6(home, ".claude"), "projects"),
27718
- codex: options.roots?.codex !== void 0 ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join6(env.CODEX_HOME ?? join6(home, ".codex"), "sessions")
28018
+ pi: options.roots?.pi !== void 0 ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join7(env.PI_CODING_AGENT_DIR ?? join7(home, ".pi", "agent"), "sessions"),
28019
+ claude: options.roots?.claude !== void 0 ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join7(env.CLAUDE_CONFIG_DIR ?? join7(home, ".claude"), "projects"),
28020
+ codex: options.roots?.codex !== void 0 ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join7(env.CODEX_HOME ?? join7(home, ".codex"), "sessions")
27719
28021
  };
27720
28022
  }
27721
28023
  async function filesAt(root, depth) {
@@ -27728,36 +28030,13 @@ async function filesAt(root, depth) {
27728
28030
  }
27729
28031
  const paths = [];
27730
28032
  for (const entry of entries) {
27731
- const path = join6(root, entry.name);
28033
+ const path = join7(root, entry.name);
27732
28034
  if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
27733
28035
  else if (entry.isFile() && depth === 0) paths.push(path);
27734
28036
  }
27735
28037
  return paths;
27736
28038
  }
27737
- var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
27738
- copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
27739
- does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
27740
- not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
27741
- FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
27742
- the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
27743
- function escapeRegExp(value) {
27744
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27745
- }
27746
- function mayMatch(text2, queries, codex) {
27747
- if (codex && text2.includes('"history_base"')) return true;
27748
- const unescaped = text2.includes("\\u") ? text2.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))) : text2;
27749
- return queries.some((query) => {
27750
- const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
27751
- return tokens === null || tokens.every((token) => {
27752
- const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
27753
- return parts.every((part) => {
27754
- const literal2 = new RegExp(escapeRegExp(part), "iu");
27755
- return literal2.test(unescaped) || unescaped !== text2 && literal2.test(text2) || literal2.test(PRESENTATION);
27756
- });
27757
- });
27758
- });
27759
- }
27760
- async function localSessions(harness, root) {
28039
+ async function localSessions(harness, root, cacheRoot, prefilters) {
27761
28040
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
27762
28041
  const sessions = [];
27763
28042
  for (const path of paths) {
@@ -27766,7 +28045,7 @@ async function localSessions(harness, root) {
27766
28045
  if (!id2) continue;
27767
28046
  let modifiedAt;
27768
28047
  try {
27769
- modifiedAt = (await stat2(path)).mtimeMs;
28048
+ modifiedAt = (await stat4(path)).mtimeMs;
27770
28049
  } catch (error2) {
27771
28050
  if (error2.code === "ENOENT") continue;
27772
28051
  throw error2;
@@ -27775,13 +28054,31 @@ async function localSessions(harness, root) {
27775
28054
  harness,
27776
28055
  id: id2,
27777
28056
  modifiedAt,
28057
+ async loadRepresentative() {
28058
+ return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
28059
+ if (harness === "codex") {
28060
+ const readBytes = createCodexTranscriptReader();
28061
+ const history = await readCodexHistory({ threadId: id2, transcriptPath: path }, async (source, remaining) => {
28062
+ await track(source);
28063
+ return readBytes(source, remaining);
28064
+ });
28065
+ return { data: { projection: history.projection }, lineageSources: history.lineageSources };
28066
+ }
28067
+ const data = await this.load();
28068
+ if (!data) throw new Error("Session returned no history");
28069
+ return { data };
28070
+ });
28071
+ },
27778
28072
  async load(queries) {
27779
- if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
27780
- const text2 = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile4(path, "utf8");
27781
- if (queries?.length && !mayMatch(text2, queries, harness === "codex")) return void 0;
28073
+ if (queries?.length) {
28074
+ let prefilter = prefilters.get(queries);
28075
+ if (!prefilter) prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
28076
+ if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return void 0;
28077
+ }
27782
28078
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
28079
+ const text2 = await readFile4(path, "utf8");
27783
28080
  if (harness === "pi") return { projection: piHistoryFromJsonl(text2, id2) };
27784
- const projection = claudeHistoryFromJsonl(text2, { sessionId: id2, headUuid: offlineClaudeHead(text2) });
28081
+ const projection = offlineClaudeHistoryFromJsonl(text2, id2);
27785
28082
  const missing = projection.missingAncestors;
27786
28083
  return { projection, ...missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid2) => JSON.stringify(uuid2.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.
27787
28084
 
@@ -27796,17 +28093,20 @@ function localHistoryCorpus(options) {
27796
28093
  currentHarness: options.current.harness,
27797
28094
  async sessions(onlyHarness) {
27798
28095
  const roots = rootsFor(options);
28096
+ const env = options.env ?? process.env;
28097
+ const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir3(), env);
27799
28098
  const discovered = [];
28099
+ const prefilters = /* @__PURE__ */ new WeakMap();
27800
28100
  for (const harness of ["pi", "claude", "codex"]) {
27801
28101
  if (onlyHarness !== void 0 && onlyHarness !== harness) continue;
27802
28102
  const root = roots[harness];
27803
- if (root != null) discovered.push(...await localSessions(harness, root));
28103
+ if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
27804
28104
  }
27805
28105
  if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
27806
28106
  discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
27807
28107
  const unique = /* @__PURE__ */ new Map();
27808
28108
  for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
27809
- const current = { ...options.current, modifiedAt: Date.now() };
28109
+ const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
27810
28110
  if (onlyHarness === void 0 || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
27811
28111
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
27812
28112
  }