notesoup 0.59.1 → 0.60.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 (79) hide show
  1. package/README.md +3 -17
  2. package/dist/plugins/claude/src/helper.js +3 -4
  3. package/dist/plugins/codex/src/mcp.js +1 -2
  4. package/dist/plugins/dsh/tools.js +1 -2
  5. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  6. package/dist/plugins/pi/notes/tools.js +2 -3
  7. package/dist/src/history/claude.d.ts +3 -1
  8. package/dist/src/history/claude.js +40 -4
  9. package/dist/src/history/history.d.ts +10 -11
  10. package/dist/src/history/history.js +8 -19
  11. package/dist/src/history/prefilter.d.ts +1 -1
  12. package/dist/src/history/prefilter.js +14 -9
  13. package/dist/src/history/query.d.ts +3 -14
  14. package/dist/src/history/query.js +73 -85
  15. package/dist/src/index.d.ts +1 -1
  16. package/dist/src/index.js +1 -1
  17. package/dist/src/notes/address.js +3 -3
  18. package/dist/src/notes/store.d.ts +2 -4
  19. package/dist/src/notes/store.js +1 -2
  20. package/dist/src/tools/history.d.ts +4 -6
  21. package/dist/src/tools/history.js +69 -29
  22. package/dist/src/tools/notes.d.ts +18 -78
  23. package/dist/src/tools/notes.js +39 -50
  24. package/dist/src/tools/schema.d.ts +0 -1
  25. package/dist/src/tools/schema.js +0 -1
  26. package/dist/test/claude-history.test.js +27 -6
  27. package/dist/test/claude-mod.test.js +19 -8
  28. package/dist/test/codex-history.test.js +1 -1
  29. package/dist/test/codex-plugin.test.js +1 -2
  30. package/dist/test/dependencies.test.js +2 -2
  31. package/dist/test/dsh.test.js +2 -2
  32. package/dist/test/history-corpus.test.js +21 -36
  33. package/dist/test/history-prefilter.test.js +5 -0
  34. package/dist/test/history-summary-cache.test.js +3 -3
  35. package/dist/test/history.integration.test.js +53 -106
  36. package/dist/test/host-neutral.test.js +1 -1
  37. package/dist/test/note-policy.test.js +5 -5
  38. package/dist/test/notes-cwd.test.js +5 -5
  39. package/dist/test/notes-query-namespaces.test.js +2 -6
  40. package/dist/test/notes.integration.test.js +30 -35
  41. package/dist/test/notes.test.js +12 -14
  42. package/dist/test/project-namespace.test.js +3 -3
  43. package/docs/architecture.md +3 -3
  44. package/docs/claude-code-mod.md +5 -3
  45. package/docs/codex.md +1 -1
  46. package/docs/dsh.md +2 -2
  47. package/docs/history-sessions.md +9 -10
  48. package/docs/notes-library.md +3 -3
  49. package/docs/tool-results.md +12 -6
  50. package/package.json +1 -1
  51. package/plugins/claude/dist/claude/helper.js +214 -173
  52. package/plugins/claude/hooks/register.ts +8 -6
  53. package/plugins/claude/skills/memory/SKILL.md +6 -6
  54. package/plugins/claude/src/helper.ts +3 -4
  55. package/plugins/codex/README.md +1 -1
  56. package/plugins/codex/dist/codex/notesoup.js +176 -160
  57. package/plugins/codex/src/mcp.ts +1 -2
  58. package/plugins/dsh/tools.ts +1 -2
  59. package/plugins/paseo/README.md +16 -0
  60. package/plugins/paseo/client/brain-empty-card.tsx +5 -3
  61. package/plugins/paseo/client/markdown-core.tsx +189 -0
  62. package/plugins/paseo/client/markdown.tsx +38 -135
  63. package/plugins/paseo/client/notes-op-card.tsx +15 -12
  64. package/plugins/paseo/client/paper-card.tsx +1 -3
  65. package/plugins/paseo/client/sticky-card.tsx +2 -1
  66. package/plugins/paseo/client/typography.ts +24 -0
  67. package/plugins/paseo/test/markdown-core.test.ts +75 -0
  68. package/plugins/pi/notes/tools.ts +2 -3
  69. package/skills/memory/SKILL.md +6 -6
  70. package/src/history/claude.ts +31 -4
  71. package/src/history/history.ts +11 -16
  72. package/src/history/prefilter.ts +13 -9
  73. package/src/history/query.ts +67 -99
  74. package/src/index.ts +1 -1
  75. package/src/notes/address.ts +2 -2
  76. package/src/notes/store.ts +3 -6
  77. package/src/tools/history.ts +60 -29
  78. package/src/tools/notes.ts +39 -54
  79. package/src/tools/schema.ts +0 -1
@@ -7972,6 +7972,7 @@ var HistoryFoldedRowSchema = typebox_exports.Object({
7972
7972
  var HistoryPageItemSchema = typebox_exports.Object({
7973
7973
  session: typebox_exports.Optional(typebox_exports.String()),
7974
7974
  folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
7975
+ context: typebox_exports.Optional(typebox_exports.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
7975
7976
  seq: typebox_exports.Integer({ minimum: 1 }),
7976
7977
  role: HistoryRoleSchema,
7977
7978
  created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
@@ -8001,20 +8002,17 @@ function visibleItem(event, maxChars, matchOffset) {
8001
8002
  function allItems(projection) {
8002
8003
  return projection.windows.flatMap((current) => current.items);
8003
8004
  }
8004
- function inSelection(event, params) {
8005
- if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
8006
- if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
8007
- if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
8008
- if (event.createdAt === void 0) return false;
8009
- const at = Date.parse(event.createdAt);
8010
- return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
8005
+ function compareBound(event, bound) {
8006
+ return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
8007
+ }
8008
+ function matchesFilter(event, { after, before, roles }) {
8009
+ return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0) && (!roles || roles.includes(event.role));
8011
8010
  }
8012
8011
  function filteredItems(projection, params) {
8013
- return allItems(projection).filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role))).sort((a, b) => a.seq - b.seq);
8012
+ return allItems(projection).filter((event) => matchesFilter(event, params)).sort((a, b) => a.seq - b.seq);
8014
8013
  }
8015
8014
 
8016
8015
  // src/tools/schema.ts
8017
- var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
8018
8016
  var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
8019
8017
  function paramProblem(schema, params) {
8020
8018
  const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
@@ -8122,8 +8120,8 @@ function globToRegExp(pattern) {
8122
8120
  return new RegExp(`${source}$`);
8123
8121
  }
8124
8122
  function assertGlobPattern(value) {
8125
- if (value === void 0 || value === null || value === "") return void 0;
8126
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
8123
+ if (value === void 0) return void 0;
8124
+ if (typeof value !== "string" || !value) throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a non-empty string; omit it for the current notebooks.`);
8127
8125
  if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
8128
8126
  return value;
8129
8127
  }
@@ -8977,8 +8975,7 @@ function createNotesStore(input) {
8977
8975
  }));
8978
8976
  }
8979
8977
  async function* scan(options, status) {
8980
- const glob = assertGlobPattern(options.glob);
8981
- const pattern = glob === "@default" ? void 0 : glob;
8978
+ const pattern = assertGlobPattern(options.glob);
8982
8979
  const normalized = normalizePattern(pattern, identity2);
8983
8980
  const matcher = normalized === void 0 ? void 0 : globToRegExp(normalized);
8984
8981
  const namespaces = await namespacesForPattern(pattern, identity2, status);
@@ -9188,7 +9185,7 @@ function withWarnings(text, data) {
9188
9185
  var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
9189
9186
  var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Only the crumpled balls." }));
9190
9187
  var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many pages at most." }));
9191
- var GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf \xB7 `MAP.md` that page in every notebook \xB7 `**` everything \xB7 `@sessions/*/**` every session.");
9188
+ var GLOB_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf \xB7 `MAP.md` that page in every notebook \xB7 `**` everything \xB7 `@sessions/*/**` every session." }));
9192
9189
  var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
9193
9190
  var ADDRESS_PARAMETER = typebox_exports.String({ description: "Which drawer the page sits in. `plan.md` \u2014 this session's desk, cleared when it ends. `@project/` this project's shelf \xB7 `@human/` your human's file \xB7 `@self/` your own notebook \xB7 `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` \u2014 someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
9194
9191
  function failureOf(error) {
@@ -9278,11 +9275,6 @@ var MatchSchema = typebox_exports.Object({
9278
9275
  text: typebox_exports.String(),
9279
9276
  offset_chars: typebox_exports.Integer()
9280
9277
  }, { additionalProperties: false });
9281
- var SearchedFileSchema = typebox_exports.Object({
9282
- ...ListedFileSchema.properties,
9283
- matches: typebox_exports.Array(MatchSchema),
9284
- more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
9285
- }, { additionalProperties: false });
9286
9278
  var SnapshotSchema = {
9287
9279
  more: typebox_exports.Integer({ description: "How many more were left out." }),
9288
9280
  namespaces_unavailable: typebox_exports.Array(typebox_exports.String(), { description: "Unreadable notebooks or notes." })
@@ -9307,11 +9299,11 @@ var NotesReadDataSchema = typebox_exports.Object({
9307
9299
  ...TextWindowSchema.properties
9308
9300
  }, { additionalProperties: false });
9309
9301
  var NotesListDataSchema = typebox_exports.Object({
9310
- files: typebox_exports.Array(ListedFileSchema),
9311
- ...SnapshotSchema
9312
- }, { additionalProperties: false });
9313
- var NotesSearchDataSchema = typebox_exports.Object({
9314
- files: typebox_exports.Array(SearchedFileSchema),
9302
+ files: typebox_exports.Array(typebox_exports.Object({
9303
+ ...ListedFileSchema.properties,
9304
+ matches: typebox_exports.Optional(typebox_exports.Array(MatchSchema)),
9305
+ more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
9306
+ }, { additionalProperties: false })),
9315
9307
  ...SnapshotSchema
9316
9308
  }, { additionalProperties: false });
9317
9309
  function snapshot(rows, limit, status, renderData, shrink) {
@@ -9427,41 +9419,24 @@ var notesRead = {
9427
9419
  },
9428
9420
  render: (result) => renderOutcome(result, renderReadData)
9429
9421
  };
9430
- var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
9422
+ var notesListParameters = typebox_exports.Object({
9423
+ glob: GLOB_PARAMETER,
9424
+ query: typebox_exports.Optional(searchQuery()),
9425
+ max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per note at most; requires a query." })),
9426
+ crumpled: CRUMPLED_LIST_PARAMETER,
9427
+ limit: FILE_LIMIT_PARAMETER,
9428
+ cwd: CWD_PARAMETER
9429
+ }, { additionalProperties: false });
9431
9430
  function renderListData(data) {
9432
9431
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9433
9432
  for (const file of data.files) {
9434
- lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at}${file.last_accessed === void 0 ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
9435
- lines.push(...file.warnings.map((warning) => ` ${warning}`));
9436
- }
9437
- if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9438
- for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
9439
- return lines.join("\n");
9440
- }
9441
- var notesList = {
9442
- name: "notes_list",
9443
- label: "Notes list",
9444
- description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9445
- parameters: notesListParameters,
9446
- outputSchema: resultSchema(NotesListDataSchema),
9447
- async execute(params, context2) {
9448
- try {
9449
- const identity2 = notesIdentityForCall(context2, params.cwd);
9450
- const { rows, status } = await createNotesStore(identity2).listWithStatus({ glob: params.glob ?? void 0, crumpled: params.crumpled });
9451
- return snapshot(rows.map((row) => listedFile(row, identity2)), params.limit, status, renderListData);
9452
- } catch (error) {
9453
- return failureOf(error);
9454
- }
9455
- },
9456
- render: (result) => renderOutcome(result, renderListData)
9457
- };
9458
- var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
9459
- function renderSearchData(data) {
9460
- const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9461
- for (const file of data.files) {
9462
- lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
9433
+ const fields = [`- ${renderIdentity(file)}`, renderPolicy(file), `updated ${file.updated_at}`];
9434
+ if (file.last_accessed !== void 0) fields.push(`accessed ${file.last_accessed}`);
9435
+ if (file.crumpled_at !== void 0) fields.push(`crumpled ${file.crumpled_at}`);
9436
+ if (file.matches) fields.push(`${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
9437
+ lines.push(fields.join(" | "));
9463
9438
  lines.push(...file.warnings.map((warning) => ` ${warning}`));
9464
- for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9439
+ for (const match of file.matches ?? []) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9465
9440
  }
9466
9441
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9467
9442
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
@@ -9485,26 +9460,34 @@ function fitSearchFile(file, fits) {
9485
9460
  const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
9486
9461
  return withText(prefixFit(first.text, (text) => fits(withText(text))));
9487
9462
  }
9488
- var notesSearch = {
9489
- name: "notes_search",
9490
- label: "Notes search",
9491
- description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9492
- parameters: notesSearchParameters,
9493
- outputSchema: resultSchema(NotesSearchDataSchema),
9463
+ var notesList = {
9464
+ name: "notes_list",
9465
+ label: "Notes list",
9466
+ description: "List or search notes, newest pages on top. A query matches literal text (ignoring case) and returns hit lines and read offsets. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9467
+ parameters: notesListParameters,
9468
+ outputSchema: resultSchema(NotesListDataSchema),
9494
9469
  async execute(params, context2) {
9495
9470
  try {
9471
+ const queries = searchQueries(params.query);
9472
+ const { glob, crumpled, limit } = params;
9473
+ if (!queries.length && params.max_matches_per_file !== void 0) return failure("invalid_params", "`max_matches_per_file` requires a non-empty `query`.");
9496
9474
  const identity2 = notesIdentityForCall(context2, params.cwd);
9497
- const { rows, status } = await createNotesStore(identity2).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? void 0, crumpled: params.crumpled });
9475
+ const store = createNotesStore(identity2);
9476
+ if (!queries.length) {
9477
+ const { rows: rows2, status: status2 } = await store.listWithStatus({ glob, crumpled });
9478
+ return snapshot(rows2.map((row) => listedFile(row, identity2)), limit, status2, renderListData);
9479
+ }
9480
+ const { rows, status } = await store.searchWithStatus(queries, { glob, crumpled });
9498
9481
  const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => keepMatches({
9499
9482
  ...listedFile(row, identity2),
9500
9483
  matches: row.matches.map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9501
9484
  }, params.max_matches_per_file));
9502
- return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
9485
+ return snapshot(files, limit, status, renderListData, fitSearchFile);
9503
9486
  } catch (error) {
9504
9487
  return failureOf(error);
9505
9488
  }
9506
9489
  },
9507
- render: (result) => renderOutcome(result, renderSearchData)
9490
+ render: (result) => renderOutcome(result, renderListData)
9508
9491
  };
9509
9492
 
9510
9493
  // src/history/query.ts
@@ -9516,23 +9499,6 @@ function markMultiPage(page) {
9516
9499
  multiPages.add(page);
9517
9500
  return page;
9518
9501
  }
9519
- var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
9520
- function timeBound(name, value) {
9521
- if (value === void 0) return success(void 0);
9522
- const match = ISO_8601.exec(value);
9523
- const at = match === null ? void 0 : Date.parse(match[1] === void 0 ? `${value}Z` : value);
9524
- return at === void 0 || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
9525
- }
9526
- function resolveTimeBounds(params) {
9527
- const since = timeBound("since", params.since);
9528
- if (!since.ok) return since;
9529
- const until = timeBound("until", params.until);
9530
- if (!until.ok) return until;
9531
- if (since.data !== void 0 && until.data !== void 0 && since.data >= until.data) {
9532
- return failure("invalid_time", "`since` must be earlier than `until`.");
9533
- }
9534
- return success({ ...since.data === void 0 ? {} : { sinceMs: since.data }, ...until.data === void 0 ? {} : { untilMs: until.data } });
9535
- }
9536
9502
  var HistoryPageSchema = typebox_exports.Object({
9537
9503
  notice: typebox_exports.Optional(typebox_exports.String()),
9538
9504
  items: typebox_exports.Array(HistoryPageItemSchema),
@@ -9565,22 +9531,29 @@ function foldedRun(events, session) {
9565
9531
  const tools = Object.fromEntries(entries);
9566
9532
  return { ...session === void 0 ? {} : { session }, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9567
9533
  }
9534
+ var visible = (event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "";
9535
+ function* queryHits(projection, params, session) {
9536
+ const { query, context: context2 } = params;
9537
+ const events = filteredItems(projection, context2 ? {} : params).filter(visible);
9538
+ for (const [index, event] of events.entries()) {
9539
+ if (context2 && !matchesFilter(event, params)) continue;
9540
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), query);
9541
+ if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context2 ? { events, index } : void 0 };
9542
+ }
9543
+ }
9568
9544
  function prepareSelection(projection, params) {
9569
- const folds = !params.roles && params.query === void 0;
9545
+ const { query, roles, session } = params;
9546
+ if (query) return { candidates: [...queryHits(projection, params, session)] };
9570
9547
  const candidates = [];
9571
9548
  let run = [];
9572
- for (const event of filteredItems(projection, params)) {
9573
- if (folds && (event.role === "tool" || event.role === "context")) {
9574
- run.push(event);
9575
- continue;
9549
+ for (const event of filteredItems(projection, params).filter(visible)) {
9550
+ if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
9551
+ else {
9552
+ candidates.push({ event, session, before: foldedRun(run, session) });
9553
+ run = [];
9576
9554
  }
9577
- if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
9578
- const matchOffset = params.query === void 0 ? void 0 : earliestMatchOffsetChars(eventDocument(event), params.query);
9579
- if (matchOffset !== void 0 && matchOffset < 0) continue;
9580
- candidates.push({ event, ...params.session === void 0 ? {} : { session: params.session }, matchOffset, before: foldedRun(run, params.session) });
9581
- run = [];
9582
9555
  }
9583
- return { candidates, session: params.session, tail: foldedRun(run, params.session) };
9556
+ return { candidates, tail: foldedRun(run, session) };
9584
9557
  }
9585
9558
  function pageData(prepared, start, end, maxChars, preview) {
9586
9559
  const { candidates, tail } = prepared;
@@ -9593,38 +9566,51 @@ function pageData(prepared, start, end, maxChars, preview) {
9593
9566
  const page = {
9594
9567
  items,
9595
9568
  ...end === candidates.length && tail ? { folded_after: tail } : {},
9596
- has_older: start > 0 && start < end || !!prepared.discarded && prepared.from !== "oldest",
9597
- has_newer: end < candidates.length && start < end || !!prepared.discarded && prepared.from === "oldest"
9569
+ has_older: start > 0 && start < end || !!prepared.discarded && !prepared.forward,
9570
+ has_newer: end < candidates.length && start < end || !!prepared.discarded && !!prepared.forward
9598
9571
  };
9599
9572
  return prepared.multi ? markMultiPage(page) : page;
9600
9573
  }
9601
- function resolveSelection(params) {
9602
- const bounds = resolveTimeBounds(params);
9603
- if (!bounds.ok) return bounds;
9604
- try {
9605
- const queries = searchQueries(params.query);
9606
- return success({ ...params, ...bounds.data, query: queries.length ? queries : void 0 });
9607
- } catch (error) {
9608
- if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9609
- throw error;
9610
- }
9611
- }
9612
9574
  function selectPage(projection, params, fits, maxChars) {
9613
- const scoped = resolveSelection(params);
9614
- if (!scoped.ok) return scoped;
9615
- return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
9616
- }
9617
- function corpusSelection(params) {
9618
- if (params.before_seq !== void 0 || params.after_seq !== void 0) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
9619
- return resolveSelection(params);
9575
+ return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
9620
9576
  }
9621
9577
  function sessionRepresentative(projection, scoped) {
9622
- const events = filteredItems(projection, scoped).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
9578
+ const events = filteredItems(projection, scoped).filter(visible);
9623
9579
  if (scoped.roles) return events.at(-1);
9624
9580
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9625
9581
  }
9626
- var eventTime = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
9627
- var compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
9582
+ function eventTime(timestamp) {
9583
+ const at = Date.parse(timestamp ?? "");
9584
+ return Number.isNaN(at) ? -Infinity : at;
9585
+ }
9586
+ var compareCorpus = (a, b) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
9587
+ function addContext(page, hits, radius, fits, maxChars) {
9588
+ const key = (session, seq) => `${session ?? ""}\0${seq}`;
9589
+ const seen = new Set(page.items.map((item) => key(item.session, item.seq)));
9590
+ const compare = (a, b) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session.localeCompare(b.session) : 0) || a.seq - b.seq;
9591
+ for (let distance = 1; distance <= radius; distance++) {
9592
+ let found = false;
9593
+ for (const { neighbors, session } of hits) {
9594
+ if (!neighbors) continue;
9595
+ for (const index of [neighbors.index - distance, neighbors.index + distance]) {
9596
+ const event = neighbors.events[index];
9597
+ if (!event) continue;
9598
+ found = true;
9599
+ const id2 = key(session, event.seq);
9600
+ if (seen.has(id2)) continue;
9601
+ const item = { ...visibleItem(event, maxChars), ...session === void 0 ? {} : { session }, context: true };
9602
+ const previous = page.items;
9603
+ page.items = [...previous, item].sort(compare);
9604
+ if (!fits(page)) {
9605
+ page.items = previous;
9606
+ return;
9607
+ }
9608
+ seen.add(id2);
9609
+ }
9610
+ }
9611
+ if (!found) return;
9612
+ }
9613
+ }
9628
9614
  var CorpusCollector = class {
9629
9615
  constructor(scoped) {
9630
9616
  this.scoped = scoped;
@@ -9643,7 +9629,7 @@ var CorpusCollector = class {
9643
9629
  }
9644
9630
  if (this.candidates.length === this.limit) {
9645
9631
  this.discarded = true;
9646
- if (this.scoped.from === "oldest") {
9632
+ if (this.scoped.after) {
9647
9633
  if (low === this.limit) return;
9648
9634
  this.candidates.pop();
9649
9635
  } else {
@@ -9663,22 +9649,16 @@ var CorpusCollector = class {
9663
9649
  /** Returns whether this session contributes an overview representative. */
9664
9650
  add(session, projection) {
9665
9651
  if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
9666
- for (const event of filteredItems(projection, this.scoped)) {
9667
- const document = eventDocument(event);
9668
- if ((event.role === "user" || event.role === "assistant") && document === "") continue;
9669
- const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
9670
- if (matchOffset >= 0) this.admit({ session, event, matchOffset });
9671
- }
9652
+ for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
9672
9653
  return true;
9673
9654
  }
9674
9655
  page(fits, maxChars, unvisited = false) {
9675
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
9656
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
9676
9657
  }
9677
9658
  };
9678
9659
  function selectPrepared(prepared, scoped, fits, maxChars) {
9679
9660
  const { candidates } = prepared;
9680
- const from = scoped.from ?? (scoped.after_seq !== void 0 ? "oldest" : "newest");
9681
- const newest = from === "newest";
9661
+ const newest = scoped.after === void 0;
9682
9662
  let start = newest ? candidates.length : 0;
9683
9663
  let end = start;
9684
9664
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -9700,6 +9680,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
9700
9680
  }
9701
9681
  const page = pageData(prepared, start, end, maxChars);
9702
9682
  if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
9683
+ if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
9703
9684
  return success(page);
9704
9685
  }
9705
9686
 
@@ -9790,7 +9771,7 @@ function toolHeader(item) {
9790
9771
  }
9791
9772
  function renderPageItem(item) {
9792
9773
  const tool = toolHeader(item);
9793
- const lines = tool === void 0 ? [header(item)] : [header(item), tool];
9774
+ const lines = [header(item) + (item.context ? " | search context" : ""), ...tool ? [tool] : []];
9794
9775
  if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
9795
9776
  lines.push(item.content);
9796
9777
  return lines.join("\n");
@@ -9799,7 +9780,7 @@ function renderFoldedRow(row) {
9799
9780
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
9800
9781
  const identity2 = row.session === void 0 ? {} : { session: row.session };
9801
9782
  const expand = `
9802
- \u2192 expand: ${JSON.stringify({ ...identity2, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
9783
+ \u2192 expand: ${JSON.stringify({ ...identity2, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
9803
9784
  return `${row.session === void 0 ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
9804
9785
  }
9805
9786
  function renderPage(page) {
@@ -9809,13 +9790,14 @@ function renderPage(page) {
9809
9790
  const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9810
9791
  return (page.notice ?? "") + body + (directions ? `
9811
9792
 
9812
- \u2192 more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
9793
+ \u2192 more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
9813
9794
  }
9814
- const first = page.items[0];
9815
- const last = page.items.at(-1);
9795
+ const hits = page.items.filter((item) => !item.context);
9796
+ const first = hits[0];
9797
+ const last = hits.at(-1);
9816
9798
  const cursors = [
9817
- page.has_older ? `\u2192 older: ${JSON.stringify({ ...first.session === void 0 ? {} : { session: first.session }, before_seq: first.seq })}` : "",
9818
- page.has_newer ? `\u2192 newer: ${JSON.stringify({ ...last.session === void 0 ? {} : { session: last.session }, after_seq: last.seq })}` : ""
9799
+ page.has_older ? `\u2192 older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
9800
+ page.has_newer ? `\u2192 newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : ""
9819
9801
  ].filter((line) => line !== "");
9820
9802
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}
9821
9803
 
@@ -9823,28 +9805,54 @@ ${cursors.join(" | ")}`);
9823
9805
  }
9824
9806
  function renderRead(data) {
9825
9807
  const tool = toolHeader(data);
9826
- 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 })})`;
9808
+ const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...data.session === void 0 ? {} : { session: data.session }, after: Math.max(0, data.seq - 10), before: data.seq + 10 })})`;
9827
9809
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9828
9810
  }
9829
9811
  var plainText = (text) => text;
9830
9812
  function pageOutcome(result) {
9831
9813
  if (!("pageTooLarge" in result)) return result;
9832
9814
  const { count, multi } = result.pageTooLarge;
9833
- const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
9815
+ const narrow = multi ? "narrow the session pattern, query, roles or time bounds (`after`/`before`), or read one session/seq with `history_read`" : "narrow with `after`/`before`, pass `roles` to skip folding, or `history_read` one seq";
9834
9816
  return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
9835
9817
  }
9818
+ var boundParameter = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Number()], { description: `${description} Use a seq (number or digits) or ISO 8601 time (UTC without offset); wildcards take only times.` }));
9836
9819
  var historyListParameters = typebox_exports.Object({
9837
9820
  session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
9838
- query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
9839
9821
  roles: historyRoles(),
9840
- before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Only entries before this seq." })),
9841
- after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
9842
- since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
9843
- until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
9844
- from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
9845
- limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
9822
+ query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
9823
+ after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
9824
+ before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
9825
+ context: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events on each side of a hit in its own session; requires a query." })),
9826
+ limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "How many events or hits per page; folds and search context don't count." })),
9846
9827
  max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." }))
9847
9828
  }, { additionalProperties: false });
9829
+ var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
9830
+ function parseBound(name, value) {
9831
+ if (value === void 0) return success(void 0);
9832
+ if (typeof value === "number" || /^\d+$/.test(value)) {
9833
+ const seq = Number(value);
9834
+ if (Number.isSafeInteger(seq) && seq >= 0) return success({ seq });
9835
+ } else if (typeof value === "string") {
9836
+ const match = ISO_8601.exec(value);
9837
+ const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
9838
+ if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10))) return success({ at });
9839
+ }
9840
+ return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
9841
+ }
9842
+ function parseSelection(params) {
9843
+ const after = parseBound("after", params.after);
9844
+ if (!after.ok) return after;
9845
+ const before = parseBound("before", params.before);
9846
+ if (!before.ok) return before;
9847
+ try {
9848
+ const query = searchQueries(params.query);
9849
+ if (!query.length && params.context !== void 0) return failure("invalid_params", "`context` requires a non-empty `query`.");
9850
+ return success({ after: after.data, before: before.data, query: query.length ? query : void 0, roles: params.roles, context: params.context, limit: params.limit });
9851
+ } catch (error) {
9852
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9853
+ throw error;
9854
+ }
9855
+ }
9848
9856
  var historyList = {
9849
9857
  name: "history_list",
9850
9858
  label: "History list items",
@@ -9852,32 +9860,34 @@ var historyList = {
9852
9860
  parameters: historyListParameters,
9853
9861
  outputSchema: resultSchema(HistoryPageSchema),
9854
9862
  async execute(params, context2, wrapText = plainText) {
9863
+ const selection = parseSelection(params);
9864
+ if (!selection.ok) return selection;
9865
+ const scoped = selection.data;
9855
9866
  const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
9856
9867
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
9857
- if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), params, fits, maxChars));
9868
+ if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), scoped, fits, maxChars));
9858
9869
  const selector = parseSessionSelector(params.session);
9859
9870
  if (!selector.ok) return selector;
9860
9871
  const corpus = "corpus" in context2 ? context2.corpus : void 0;
9861
9872
  if (selector.data.wildcard) {
9862
- const scoped = corpusSelection(params);
9863
- if (!scoped.ok) return scoped;
9873
+ const { after, before, query, roles } = scoped;
9874
+ if (after && "seq" in after || before && "seq" in before) return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
9864
9875
  if (corpus === void 0) return failure("unknown_session", "This host supplied no cross-session history corpus.");
9865
9876
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
9866
- const queries = Array.isArray(scoped.data.query) ? scoped.data.query : void 0;
9867
- if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9868
- const representative = !queries && scoped.data.roles === void 0 && scoped.data.since === void 0 && scoped.data.until === void 0;
9869
- const collector = new CorpusCollector(scoped.data);
9877
+ if (!query) sessions.sort((a, b) => (after ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9878
+ const representative = !query && !roles && !after && !before;
9879
+ const collector = new CorpusCollector(scoped);
9870
9880
  let qualifying = 0;
9871
9881
  const notices = [];
9872
9882
  let unvisited = false;
9873
9883
  for (const [index, session] of sessions.entries()) {
9874
- const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
9884
+ const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
9875
9885
  if (!result3.ok || !result3.data) continue;
9876
9886
  const added = "projection" in result3.data ? collector.add(sessionIdentity(session), result3.data.projection) : collector.addRepresentative(sessionIdentity(session), result3.data.event);
9877
9887
  if (!added) continue;
9878
9888
  qualifying++;
9879
9889
  if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
9880
- if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
9890
+ if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
9881
9891
  unvisited = index + 1 < sessions.length;
9882
9892
  break;
9883
9893
  }
@@ -9891,7 +9901,7 @@ var historyList = {
9891
9901
  const loaded = await loadHistorySession(target.data);
9892
9902
  if (!loaded.ok) return loaded;
9893
9903
  const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
9894
- const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
9904
+ const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
9895
9905
  return result.ok ? success({ ...result.data, ...notice }) : result;
9896
9906
  },
9897
9907
  render: (result) => renderOutcome(result, renderPage)
@@ -9955,7 +9965,7 @@ var historyRead = {
9955
9965
  };
9956
9966
 
9957
9967
  // src/history/local.ts
9958
- import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
9968
+ import { readdir as readdir4, readFile as readFile4, stat as stat5 } from "node:fs/promises";
9959
9969
  import { homedir as homedir2 } from "node:os";
9960
9970
  import { join as join6 } from "node:path";
9961
9971
 
@@ -10124,8 +10134,14 @@ function piHistoryFromJsonl(text, sessionId) {
10124
10134
  }
10125
10135
 
10126
10136
  // src/history/claude.ts
10127
- import { readFile as readFile2 } from "node:fs/promises";
10137
+ import { readFile as readFile2, stat } from "node:fs/promises";
10138
+ import { setTimeout as sleep } from "node:timers/promises";
10128
10139
  import { isDeepStrictEqual } from "node:util";
10140
+ var UnpersistedClaudeHead = class extends Error {
10141
+ constructor() {
10142
+ super("Claude history active head is not persisted yet; retry after the transcript write");
10143
+ }
10144
+ };
10129
10145
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
10130
10146
  var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
10131
10147
  function object(value) {
@@ -10271,7 +10287,7 @@ function claudeHistoryFromRows(rows, source) {
10271
10287
  return version.position;
10272
10288
  }
10273
10289
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
10274
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
10290
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
10275
10291
  const selected = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), visiting = /* @__PURE__ */ new Set();
10276
10292
  const stack = [{ uuid: source.headUuid, historical: false }];
10277
10293
  while (stack.length > 0) {
@@ -10380,13 +10396,37 @@ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10380
10396
  const rows = rowsOf(text);
10381
10397
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10382
10398
  }
10383
- async function readClaudeHistory(source) {
10399
+ async function readClaudeHistory(source, { waitForHead = false } = {}) {
10384
10400
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10385
- return claudeHistoryFromJsonl(await readFile2(source.transcriptPath, "utf8"), source);
10401
+ const snapshot2 = { ...source };
10402
+ const read = async () => claudeHistoryFromJsonl(await readFile2(snapshot2.transcriptPath, "utf8"), snapshot2);
10403
+ if (!waitForHead || !snapshot2.headUuid) return read();
10404
+ const revision = async () => {
10405
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot2.transcriptPath, { bigint: true });
10406
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
10407
+ };
10408
+ let seen = await revision();
10409
+ try {
10410
+ return await read();
10411
+ } catch (error) {
10412
+ if (!(error instanceof UnpersistedClaudeHead)) throw error;
10413
+ for (const delay of [50, 100, 200, 300, 350]) {
10414
+ await sleep(delay);
10415
+ const current = await revision();
10416
+ if (current === seen) continue;
10417
+ seen = current;
10418
+ try {
10419
+ return await read();
10420
+ } catch (retry) {
10421
+ if (!(retry instanceof UnpersistedClaudeHead)) throw retry;
10422
+ }
10423
+ }
10424
+ throw error;
10425
+ }
10386
10426
  }
10387
10427
 
10388
10428
  // src/history/codex-transcript.ts
10389
- import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "node:fs/promises";
10429
+ import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
10390
10430
  import { basename as basename2, dirname as dirname3, join as join4, relative, sep as sep2 } from "node:path";
10391
10431
  import * as zlib from "node:zlib";
10392
10432
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -10548,7 +10588,7 @@ function createCodexTranscriptReader() {
10548
10588
  let pending = cache.get(canonical);
10549
10589
  if (!pending) {
10550
10590
  pending = (async () => {
10551
- const info = await stat(canonical);
10591
+ const info = await stat2(canonical);
10552
10592
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10553
10593
  const stored = await readFile3(canonical);
10554
10594
  if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
@@ -10852,7 +10892,7 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10852
10892
 
10853
10893
  // src/history/prefilter.ts
10854
10894
  import { createReadStream } from "node:fs";
10855
- import { stat as stat2 } from "node:fs/promises";
10895
+ import { stat as stat3 } from "node:fs/promises";
10856
10896
  import { pipeline } from "node:stream/promises";
10857
10897
  import { StringDecoder } from "node:string_decoder";
10858
10898
  import * as zlib2 from "node:zlib";
@@ -10873,7 +10913,7 @@ function createHistoryPrefilter(queries) {
10873
10913
  }).filter((literal) => !literal.test(PRESENTATION));
10874
10914
  }));
10875
10915
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10876
- return async (chunks, codex = false) => {
10916
+ return async (chunks, codex = false, stopOnHit = false) => {
10877
10917
  const decoder = new StringDecoder("utf8");
10878
10918
  const seen = alternatives.map((tokens) => tokens.map(() => false));
10879
10919
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -10901,17 +10941,19 @@ function createHistoryPrefilter(queries) {
10901
10941
  rawTail = raw.slice(-overlap);
10902
10942
  normalizedTail = normalized.slice(-overlap);
10903
10943
  };
10904
- for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
10944
+ for await (const chunk of chunks) {
10945
+ if (!possible) scan(decoder.write(chunk));
10946
+ if (possible && stopOnHit) return true;
10947
+ }
10905
10948
  if (!possible) scan(decoder.end(), true);
10906
10949
  return possible;
10907
10950
  };
10908
10951
  }
10909
10952
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10910
- if (codex) {
10911
- const info = await stat2(path);
10912
- if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10913
- }
10914
- const compressed = codex && path.endsWith(".jsonl.zst");
10953
+ if (!codex) return prefilter(createReadStream(path), false, true);
10954
+ const info = await stat3(path);
10955
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10956
+ const compressed = path.endsWith(".jsonl.zst");
10915
10957
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10916
10958
  const input = createReadStream(path);
10917
10959
  const consume = async (chunks) => {
@@ -10930,7 +10972,7 @@ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = co
10930
10972
 
10931
10973
  // src/history/summary-cache.ts
10932
10974
  import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10933
- import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10975
+ import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10934
10976
  import { homedir } from "node:os";
10935
10977
  import { join as join5 } from "node:path";
10936
10978
  var VERSION = "strict-representative-v1";
@@ -10979,7 +11021,7 @@ function historySummaryCacheRoot(home = homedir(), env = process.env, platform =
10979
11021
  return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
10980
11022
  }
10981
11023
  async function fingerprint(path) {
10982
- const info = await stat3(path, { bigint: true });
11024
+ const info = await stat4(path, { bigint: true });
10983
11025
  if (!info.isFile()) throw new Error("Not a regular transcript file");
10984
11026
  return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
10985
11027
  }
@@ -11084,7 +11126,7 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11084
11126
  if (!id2) continue;
11085
11127
  let modifiedAt;
11086
11128
  try {
11087
- modifiedAt = (await stat4(path)).mtimeMs;
11129
+ modifiedAt = (await stat5(path)).mtimeMs;
11088
11130
  } catch (error) {
11089
11131
  if (error.code === "ENOENT") continue;
11090
11132
  throw error;
@@ -11549,8 +11591,7 @@ var OPERATIONS = {
11549
11591
  notes_write: boundOperation(notesWrite),
11550
11592
  notes_update: boundOperation(notesUpdate),
11551
11593
  notes_read: boundOperation(notesRead),
11552
- notes_list: boundOperation(notesList),
11553
- notes_search: boundOperation(notesSearch)
11594
+ notes_list: boundOperation(notesList)
11554
11595
  };
11555
11596
  var HISTORY_OPERATIONS = {
11556
11597
  history_list: boundOperation(historyList),
@@ -11589,8 +11630,8 @@ async function dispatch(request, historyOptions = {}) {
11589
11630
  const id2 = identity(value.identity);
11590
11631
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
11591
11632
  const tool = value.tool;
11633
+ const current = () => readClaudeHistory(historySource(value.history, id2.sessionId), { waitForHead: true });
11592
11634
  if (value.params.session !== void 0) {
11593
- const current = () => readClaudeHistory(historySource(value.history, id2.sessionId));
11594
11635
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id2.sessionId, async load() {
11595
11636
  const projection2 = await current();
11596
11637
  const notice2 = claudeHistoryGapNotice(projection2.missingAncestors);
@@ -11598,7 +11639,7 @@ async function dispatch(request, historyOptions = {}) {
11598
11639
  } } });
11599
11640
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
11600
11641
  }
11601
- const projection = await readClaudeHistory(historySource(value.history, id2.sessionId));
11642
+ const projection = await current();
11602
11643
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
11603
11644
  const wrapText = (text) => notice + text;
11604
11645
  const params = value.params;