notesoup 0.60.1 → 0.62.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 (200) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -10
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +2 -1
  10. package/dist/plugins/codex/src/hooks.js +1 -0
  11. package/dist/plugins/codex/src/identity.d.ts +6 -1
  12. package/dist/plugins/codex/src/identity.js +13 -1
  13. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  14. package/dist/plugins/codex/src/mcp.js +26 -88
  15. package/dist/plugins/codex/src/text.js +3 -3
  16. package/dist/plugins/dsh/tools.js +8 -4
  17. package/dist/plugins/mcp/operations.d.ts +15 -0
  18. package/dist/plugins/mcp/operations.js +43 -0
  19. package/dist/plugins/mcp/server.d.ts +14 -0
  20. package/dist/plugins/mcp/server.js +13 -0
  21. package/dist/plugins/pi/budget.d.ts +1 -1
  22. package/dist/plugins/pi/budget.js +3 -2
  23. package/dist/plugins/pi/entries.d.ts +1 -0
  24. package/dist/plugins/pi/entries.js +1 -0
  25. package/dist/plugins/pi/history-tools.js +2 -1
  26. package/dist/plugins/pi/history.js +18 -1
  27. package/dist/plugins/pi/notes/tools.js +7 -3
  28. package/dist/plugins/pi/render.d.ts +7 -1
  29. package/dist/plugins/pi/render.js +2 -2
  30. package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
  31. package/dist/plugins/pi/reset/lifecycle.js +8 -9
  32. package/dist/plugins/pi/runtime.js +102 -61
  33. package/dist/plugins/pi/tool-result.js +7 -7
  34. package/dist/plugins/pi/window.d.ts +33 -3
  35. package/dist/plugins/pi/window.js +209 -9
  36. package/dist/src/boot/render.d.ts +5 -0
  37. package/dist/src/boot/render.js +60 -28
  38. package/dist/src/boot/text.d.ts +3 -3
  39. package/dist/src/boot/text.js +27 -26
  40. package/dist/src/budget/text.d.ts +2 -2
  41. package/dist/src/budget/text.js +13 -13
  42. package/dist/src/history/claude.d.ts +2 -0
  43. package/dist/src/history/claude.js +46 -0
  44. package/dist/src/history/codex-transcript.js +7 -5
  45. package/dist/src/history/codex.js +3 -0
  46. package/dist/src/history/corpus.d.ts +28 -1
  47. package/dist/src/history/corpus.js +40 -0
  48. package/dist/src/history/history.d.ts +37 -46
  49. package/dist/src/history/history.js +21 -40
  50. package/dist/src/history/local.js +67 -32
  51. package/dist/src/history/pi.d.ts +2 -1
  52. package/dist/src/history/pi.js +122 -48
  53. package/dist/src/history/prefilter.js +76 -19
  54. package/dist/src/history/query.d.ts +28 -49
  55. package/dist/src/history/query.js +83 -68
  56. package/dist/src/history/summary-cache.d.ts +8 -1
  57. package/dist/src/history/summary-cache.js +138 -12
  58. package/dist/src/index.d.ts +1 -1
  59. package/dist/src/index.js +1 -1
  60. package/dist/src/notes/frontmatter.d.ts +4 -0
  61. package/dist/src/notes/frontmatter.js +15 -1
  62. package/dist/src/notes/index.d.ts +1 -1
  63. package/dist/src/notes/index.js +1 -1
  64. package/dist/src/notes/policy.d.ts +15 -1
  65. package/dist/src/notes/policy.js +47 -6
  66. package/dist/src/notes/store.d.ts +14 -0
  67. package/dist/src/notes/store.js +33 -12
  68. package/dist/src/text-match.d.ts +10 -1
  69. package/dist/src/text-match.js +42 -3
  70. package/dist/src/tools/dream.d.ts +22 -91
  71. package/dist/src/tools/dream.js +30 -27
  72. package/dist/src/tools/history.d.ts +33 -26
  73. package/dist/src/tools/history.js +257 -163
  74. package/dist/src/tools/notes.d.ts +58 -160
  75. package/dist/src/tools/notes.js +151 -99
  76. package/dist/src/tools/output.d.ts +2 -1
  77. package/dist/src/tools/output.js +2 -1
  78. package/dist/src/tools/result.d.ts +4 -7
  79. package/dist/src/tools/result.js +8 -9
  80. package/dist/src/tools/schema.d.ts +4 -1
  81. package/dist/src/tools/schema.js +25 -1
  82. package/dist/test/agent-loop.test.js +198 -16
  83. package/dist/test/antigravity-live.test.d.ts +1 -0
  84. package/dist/test/antigravity-live.test.js +142 -0
  85. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  86. package/dist/test/antigravity-plugin.test.js +101 -0
  87. package/dist/test/boot.integration.test.js +133 -14
  88. package/dist/test/claude-history.test.js +14 -13
  89. package/dist/test/claude-mod.test.js +9 -6
  90. package/dist/test/codex-history.test.js +15 -3
  91. package/dist/test/codex-plugin.test.js +76 -38
  92. package/dist/test/dependencies.test.js +7 -3
  93. package/dist/test/dream-skill.test.js +3 -3
  94. package/dist/test/dream-tools.test.js +101 -56
  95. package/dist/test/dsh.test.js +34 -19
  96. package/dist/test/helpers/dependency-graph.js +2 -2
  97. package/dist/test/helpers/extension.d.ts +65 -2
  98. package/dist/test/helpers/extension.js +72 -3
  99. package/dist/test/history-corpus.test.js +79 -77
  100. package/dist/test/history-summary-cache.test.js +97 -9
  101. package/dist/test/history.integration.test.js +234 -168
  102. package/dist/test/host-neutral.test.js +69 -19
  103. package/dist/test/marker.test.js +1 -1
  104. package/dist/test/note-policy.test.js +189 -56
  105. package/dist/test/notes.integration.test.js +212 -94
  106. package/dist/test/notes.test.js +184 -113
  107. package/dist/test/pi-render.test.js +20 -12
  108. package/dist/test/project-namespace.test.js +3 -2
  109. package/dist/test/reset-lifecycle.test.js +2 -2
  110. package/docs/antigravity.md +44 -0
  111. package/docs/architecture.md +6 -4
  112. package/docs/claude-code-mod.md +2 -2
  113. package/docs/codex.md +36 -38
  114. package/docs/dsh.md +4 -4
  115. package/docs/history-sessions.md +28 -50
  116. package/docs/notes-library.md +6 -6
  117. package/docs/reset-lifecycle.md +1 -1
  118. package/docs/skills.md +3 -3
  119. package/docs/tool-results.md +47 -28
  120. package/package.json +3 -2
  121. package/playbook.md +3 -3
  122. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  123. package/plugins/antigravity/hooks.json +7 -0
  124. package/plugins/antigravity/mcp_config.json +8 -0
  125. package/plugins/antigravity/plugin.json +6 -0
  126. package/plugins/antigravity/src/cli.ts +22 -0
  127. package/plugins/antigravity/src/hooks.ts +51 -0
  128. package/plugins/antigravity/src/identity.ts +127 -0
  129. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  130. package/plugins/claude/dist/claude/helper.js +1129 -549
  131. package/plugins/claude/hooks/register.ts +2 -2
  132. package/plugins/claude/playbook.md +3 -3
  133. package/plugins/claude/skills/dream/SKILL.md +2 -2
  134. package/plugins/claude/skills/notesoup/SKILL.md +92 -0
  135. package/plugins/claude/src/helper.ts +2 -1
  136. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  137. package/plugins/codex/.mcp.json +11 -0
  138. package/plugins/codex/README.md +5 -21
  139. package/plugins/codex/dist/codex/notesoup.js +18494 -17905
  140. package/plugins/codex/src/hooks.ts +1 -0
  141. package/plugins/codex/src/identity.ts +14 -1
  142. package/plugins/codex/src/mcp.ts +28 -98
  143. package/plugins/codex/src/text.ts +3 -3
  144. package/plugins/dsh/tools.ts +8 -4
  145. package/plugins/mcp/operations.ts +50 -0
  146. package/plugins/mcp/server.ts +23 -0
  147. package/plugins/paseo/README.md +5 -10
  148. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  149. package/plugins/paseo/client/markdown.tsx +50 -38
  150. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  151. package/plugins/paseo/client/paper-card.tsx +6 -5
  152. package/plugins/paseo/client/paper-palette.ts +2 -9
  153. package/plugins/paseo/client/sticky-card.tsx +2 -2
  154. package/plugins/paseo/client/tool-result.ts +7 -14
  155. package/plugins/paseo/package-lock.json +3406 -0
  156. package/plugins/paseo/package.json +1 -0
  157. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  158. package/plugins/pi/budget.ts +3 -3
  159. package/plugins/pi/entries.ts +1 -0
  160. package/plugins/pi/history-tools.ts +2 -1
  161. package/plugins/pi/history.ts +30 -1
  162. package/plugins/pi/notes/tools.ts +7 -3
  163. package/plugins/pi/render.ts +6 -6
  164. package/plugins/pi/reset/lifecycle.ts +9 -10
  165. package/plugins/pi/runtime.ts +96 -60
  166. package/plugins/pi/tool-result.ts +8 -8
  167. package/plugins/pi/window.ts +198 -9
  168. package/skills/dream/SKILL.md +2 -2
  169. package/skills/notesoup/SKILL.md +92 -0
  170. package/src/boot/render.ts +59 -25
  171. package/src/boot/text.ts +30 -27
  172. package/src/budget/text.ts +13 -13
  173. package/src/history/claude.ts +41 -0
  174. package/src/history/codex-transcript.ts +6 -4
  175. package/src/history/codex.ts +2 -0
  176. package/src/history/corpus.ts +51 -2
  177. package/src/history/history.ts +35 -44
  178. package/src/history/local.ts +67 -27
  179. package/src/history/pi.ts +113 -35
  180. package/src/history/prefilter.ts +73 -15
  181. package/src/history/query.ts +93 -73
  182. package/src/history/summary-cache.ts +142 -17
  183. package/src/index.ts +1 -1
  184. package/src/notes/frontmatter.ts +16 -1
  185. package/src/notes/index.ts +1 -1
  186. package/src/notes/policy.ts +45 -6
  187. package/src/notes/store.ts +30 -15
  188. package/src/text-match.ts +46 -4
  189. package/src/tools/dream.ts +29 -31
  190. package/src/tools/history.ts +249 -142
  191. package/src/tools/notes.ts +150 -112
  192. package/src/tools/output.ts +2 -1
  193. package/src/tools/result.ts +12 -11
  194. package/src/tools/schema.ts +24 -1
  195. package/plugins/claude/skills/memory/SKILL.md +0 -69
  196. package/plugins/codex/mcp.json +0 -10
  197. package/plugins/codex/plugin.json +0 -6
  198. package/plugins/paseo/client/markdown-core.tsx +0 -189
  199. package/plugins/paseo/client/typography.ts +0 -24
  200. package/skills/memory/SKILL.md +0 -69
@@ -7849,9 +7849,84 @@ __export(typebox_exports, {
7849
7849
  With: () => With2
7850
7850
  });
7851
7851
 
7852
+ // src/text-match.ts
7853
+ var InvalidQueryError = class extends Error {
7854
+ constructor(message) {
7855
+ super(message);
7856
+ this.name = "InvalidQueryError";
7857
+ }
7858
+ };
7859
+ function searchQueries(query) {
7860
+ const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
7861
+ if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
7862
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
7863
+ return candidates.filter((candidate) => candidate !== "");
7864
+ }
7865
+ function prefixFit(text, fits) {
7866
+ if (fits(text)) return text;
7867
+ const chars = Array.from(text);
7868
+ let low = 0;
7869
+ let high = chars.length;
7870
+ while (low < high) {
7871
+ const mid = Math.ceil((low + high) / 2);
7872
+ if (fits(chars.slice(0, mid).join(""))) low = mid;
7873
+ else high = mid - 1;
7874
+ }
7875
+ return chars.slice(0, low).join("");
7876
+ }
7877
+ function compileSearchQueries(queries) {
7878
+ return queries.map((query) => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu"));
7879
+ }
7880
+ function codePointCount(text, utf16End = text.length) {
7881
+ let count = utf16End;
7882
+ for (let i = 0; i < utf16End - 1; i++) {
7883
+ const code = text.charCodeAt(i);
7884
+ if (code >= 55296 && code <= 56319) {
7885
+ const next = text.charCodeAt(i + 1);
7886
+ if (next >= 56320 && next <= 57343) {
7887
+ count--;
7888
+ i++;
7889
+ }
7890
+ }
7891
+ }
7892
+ return count;
7893
+ }
7894
+ function sliceCodePoints(text, start, limit) {
7895
+ const len = text.length;
7896
+ let utf16Start = 0;
7897
+ let cp = 0;
7898
+ while (cp < start && utf16Start < len) {
7899
+ const code = text.charCodeAt(utf16Start);
7900
+ utf16Start += code >= 55296 && code <= 56319 && utf16Start + 1 < len && text.charCodeAt(utf16Start + 1) >= 56320 && text.charCodeAt(utf16Start + 1) <= 57343 ? 2 : 1;
7901
+ cp++;
7902
+ }
7903
+ let utf16End = utf16Start;
7904
+ let taken = 0;
7905
+ while (taken < limit && utf16End < len) {
7906
+ const code = text.charCodeAt(utf16End);
7907
+ utf16End += code >= 55296 && code <= 56319 && utf16End + 1 < len && text.charCodeAt(utf16End + 1) >= 56320 && text.charCodeAt(utf16End + 1) <= 57343 ? 2 : 1;
7908
+ taken++;
7909
+ }
7910
+ const truncated2 = start > 0 || utf16End < len;
7911
+ return { text: truncated2 ? text.slice(utf16Start, utf16End) : text, truncated: truncated2 };
7912
+ }
7913
+ function earliestMatchOffsetChars(text, queries) {
7914
+ let earliest = -1;
7915
+ for (const query of queries) {
7916
+ const pattern = typeof query === "string" ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu") : query;
7917
+ const index = pattern.exec(text)?.index ?? -1;
7918
+ if (index < 0) continue;
7919
+ if (earliest < 0 || index < earliest) earliest = index;
7920
+ }
7921
+ return earliest < 0 ? -1 : codePointCount(text, earliest);
7922
+ }
7923
+
7852
7924
  // src/history/history.ts
7853
- var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
7854
- var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
7925
+ function stringEnum(values, options = {}) {
7926
+ return typebox_exports.Unsafe({ ...typebox_exports.Enum([...values], options), type: "string" });
7927
+ }
7928
+ var HistoryRoleSchema = stringEnum(["user", "assistant", "tool", "context"]);
7929
+ var ToolCallStatusSchema = stringEnum(["ok", "error", "unfinished"]);
7855
7930
  function isTextContent(part) {
7856
7931
  return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
7857
7932
  }
@@ -7893,7 +7968,7 @@ function eventDocument(event) {
7893
7968
  function toolEvent(item, result) {
7894
7969
  const run = result ?? item;
7895
7970
  const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
7896
- const truncated = run.outputTruncated === true;
7971
+ const truncated2 = run.outputTruncated === true;
7897
7972
  return {
7898
7973
  seq: item.seq,
7899
7974
  windowId: item.windowId,
@@ -7905,7 +7980,7 @@ function toolEvent(item, result) {
7905
7980
  status,
7906
7981
  // A call records its arguments; a bare result records none, and gets none invented.
7907
7982
  ...item.arguments === void 0 ? {} : { arguments: item.arguments },
7908
- ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
7983
+ ...truncated2 ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
7909
7984
  ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
7910
7985
  }
7911
7986
  };
@@ -7938,16 +8013,6 @@ function projectHistory(rawWindows, highestSeq, branchSeqs) {
7938
8013
  }));
7939
8014
  return { windows, highestSeq, branchSeqs, pairedResults };
7940
8015
  }
7941
- var NestedCallSummarySchema = typebox_exports.Object({
7942
- call_count: typebox_exports.Integer({ minimum: 0 }),
7943
- complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
7944
- }, { additionalProperties: false });
7945
- var ToolSummarySchema = typebox_exports.Object({
7946
- tool: typebox_exports.Optional(typebox_exports.String()),
7947
- tool_status: typebox_exports.Optional(ToolCallStatusSchema),
7948
- output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
7949
- full_output_path: typebox_exports.Optional(typebox_exports.String())
7950
- }, { additionalProperties: false });
7951
8016
  function toolSummary(event) {
7952
8017
  const execution = event.execution;
7953
8018
  if (!execution) return {};
@@ -7962,58 +8027,46 @@ function nestedCallSummary(event) {
7962
8027
  const nested = event.execution?.nestedCalls;
7963
8028
  return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
7964
8029
  }
7965
- var HistoryFoldedRowSchema = typebox_exports.Object({
7966
- session: typebox_exports.Optional(typebox_exports.String()),
7967
- first_seq: typebox_exports.Integer({ minimum: 1 }),
7968
- last_seq: typebox_exports.Integer({ minimum: 1 }),
7969
- count: typebox_exports.Integer({ minimum: 1 }),
7970
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
7971
- }, { additionalProperties: false });
7972
- var HistoryPageItemSchema = typebox_exports.Object({
7973
- session: typebox_exports.Optional(typebox_exports.String()),
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." })),
7976
- seq: typebox_exports.Integer({ minimum: 1 }),
7977
- role: HistoryRoleSchema,
7978
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
7979
- ...ToolSummarySchema.properties,
7980
- content: typebox_exports.String(),
7981
- truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
7982
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
7983
- }, { additionalProperties: false });
7984
8030
  var MAX_FOLD_TOOL_NAMES = 20;
7985
8031
  var MAX_FOLD_TOOL_NAME_CHARS = 120;
7986
8032
  function visibleItem(event, maxChars, matchOffset) {
7987
8033
  const document = eventDocument(event);
7988
- const chars = Array.from(document);
7989
8034
  const start = matchOffset ?? 0;
7990
8035
  const limit = Math.max(0, maxChars);
7991
- const truncated = start > 0 || start + limit < chars.length;
8036
+ const { text: content, truncated: truncated2 } = sliceCodePoints(document, start, limit);
7992
8037
  return {
7993
8038
  seq: event.seq,
7994
8039
  role: event.role,
7995
8040
  created_at: event.createdAt ?? null,
7996
8041
  ...toolSummary(event),
7997
- content: truncated ? chars.slice(start, start + limit).join("") : document,
7998
- truncated,
8042
+ content,
8043
+ truncated: truncated2,
7999
8044
  ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
8000
8045
  };
8001
8046
  }
8002
8047
  function allItems(projection) {
8003
8048
  return projection.windows.flatMap((current) => current.items);
8004
8049
  }
8050
+ var timestamps = /* @__PURE__ */ new WeakMap();
8051
+ function eventTimestampMs(event) {
8052
+ const cached = timestamps.get(event);
8053
+ if (cached !== void 0) return cached;
8054
+ const parsed = event.createdAt ? Date.parse(event.createdAt) : NaN;
8055
+ timestamps.set(event, parsed);
8056
+ return parsed;
8057
+ }
8005
8058
  function compareBound(event, bound) {
8006
- return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
8059
+ return "seq" in bound ? event.seq - bound.seq : eventTimestampMs(event) - bound.at;
8007
8060
  }
8008
- function matchesFilter(event, { after, before, roles }) {
8009
- return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0) && (!roles || roles.includes(event.role));
8061
+ function matchesFilter(event, { after, before, since, until, roles }) {
8062
+ return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0) && (since === void 0 || eventTimestampMs(event) > since) && (until === void 0 || eventTimestampMs(event) < until) && (!roles || roles.includes(event.role));
8010
8063
  }
8011
8064
  function filteredItems(projection, params) {
8012
8065
  return allItems(projection).filter((event) => matchesFilter(event, params)).sort((a, b) => a.seq - b.seq);
8013
8066
  }
8014
8067
 
8015
8068
  // src/tools/schema.ts
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." }));
8069
+ var historyRoles = (foldsWithoutRoles = false) => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "Filter by event role." + (foldsWithoutRoles ? " Omit to fold tool and context runs." : "") }));
8017
8070
  function paramProblem(schema, params) {
8018
8071
  const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
8019
8072
  if (!first) return "unrecognized shape";
@@ -8022,6 +8075,24 @@ function paramProblem(schema, params) {
8022
8075
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
8023
8076
  }
8024
8077
  var searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
8078
+ function parseIsoTimestamp(value) {
8079
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:?\d{2})?)?$/.exec(value);
8080
+ if (!match) return void 0;
8081
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
8082
+ const hour = Number(match[4] ?? 0), minute = Number(match[5] ?? 0), second = Number(match[6] ?? 0);
8083
+ if (hour > 23 || minute > 59 || second > 59) return void 0;
8084
+ const check = /* @__PURE__ */ new Date(0);
8085
+ check.setUTCFullYear(year, month - 1, day);
8086
+ if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) return void 0;
8087
+ if (match[8]) {
8088
+ const at = Date.parse(value);
8089
+ return Number.isFinite(at) ? at : void 0;
8090
+ }
8091
+ const ms = match[7] ? Number(match[7].slice(0, 3).padEnd(3, "0")) : 0;
8092
+ const local = new Date(year, month - 1, day, hour, minute, second, ms);
8093
+ local.setFullYear(year, month - 1, day);
8094
+ return Number.isFinite(local.getTime()) ? local.getTime() : void 0;
8095
+ }
8025
8096
 
8026
8097
  // src/notes/errors.ts
8027
8098
  var NoteError = class extends Error {
@@ -8163,15 +8234,19 @@ function addressFor(identity2, scope, path, who) {
8163
8234
  }
8164
8235
 
8165
8236
  // src/notes/policy.ts
8166
- var DEFAULT_NOTE_BUDGET = 4096;
8237
+ var DEFAULT_NOTE_BUDGET = 8192;
8238
+ var DEFAULT_CHEATSHEET_BUDGET = 4096;
8167
8239
  var MAX_PINNED_NOTES = 5;
8168
- var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
8240
+ var WARNING_OPEN_TAG = "<notesoup:warning>";
8241
+ var WARNING_CLOSE_TAG = "</notesoup:warning>";
8242
+ var MAX_DESCRIPTION_CHARS = 160;
8243
+ var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"];
8169
8244
  function validateNotePolicy(fields) {
8170
8245
  for (const key of ["pinned", "readonly"]) {
8171
8246
  if (fields[key] !== void 0 && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
8172
8247
  }
8173
8248
  if (fields.budget !== void 0 && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
8174
- throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
8249
+ throw new NoteError("invalid_policy", "budget must be a positive integer.");
8175
8250
  }
8176
8251
  }
8177
8252
  function effectiveNotePolicy(fields, path) {
@@ -8179,7 +8254,7 @@ function effectiveNotePolicy(fields, path) {
8179
8254
  const defaultPage = DEFAULT_PINNED_PAGES.some((page) => page === path);
8180
8255
  return {
8181
8256
  pinned: fields.pinned ?? defaultPage,
8182
- budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
8257
+ budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
8183
8258
  readonly: fields.readonly ?? false
8184
8259
  };
8185
8260
  }
@@ -8187,9 +8262,39 @@ function pinnedPageOrder(path) {
8187
8262
  const index = DEFAULT_PINNED_PAGES.findIndex((page) => page === path);
8188
8263
  return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
8189
8264
  }
8265
+ function truncateToUtf8Bytes(text, maxBytes) {
8266
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return { text, shownChars: 0, totalChars: 0, truncated: false };
8267
+ const chars = Array.from(text);
8268
+ let bytes = 0;
8269
+ let shown2 = 0;
8270
+ for (const char of chars) {
8271
+ const size = Buffer.byteLength(char, "utf8");
8272
+ if (bytes + size > maxBytes) break;
8273
+ bytes += size;
8274
+ shown2++;
8275
+ }
8276
+ return { text: chars.slice(0, shown2).join(""), shownChars: shown2, totalChars: chars.length, truncated: true };
8277
+ }
8278
+ function renderWarnings(warnings) {
8279
+ if (warnings.length === 0) return "";
8280
+ if (warnings.length === 1) return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
8281
+ return `${WARNING_OPEN_TAG}
8282
+ ${warnings.join("\n")}
8283
+ ${WARNING_CLOSE_TAG}`;
8284
+ }
8190
8285
  function noteBudgetWarnings(body, policy) {
8191
- const count = Array.from(body).length;
8192
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} \u2014 boil it down.`] : [];
8286
+ const bytes = Buffer.byteLength(body, "utf8");
8287
+ if (bytes <= policy.budget) return [];
8288
+ const action = policy.pinned ? "boot truncates it to budget \u2014 trim, split, or unpin." : "trim or split it.";
8289
+ return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
8290
+ }
8291
+ function noteDescriptionWarnings(description) {
8292
+ if (description === void 0) return [];
8293
+ const count = Array.from(description).length;
8294
+ return count > MAX_DESCRIPTION_CHARS ? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`] : [];
8295
+ }
8296
+ function noteWarnings(body, policy, description) {
8297
+ return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
8193
8298
  }
8194
8299
  function assertNoteUnlocked(fields, unlock) {
8195
8300
  if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
@@ -8205,7 +8310,11 @@ function applyNotePolicy(target, fields) {
8205
8310
  var SCOPES = ["session", "project", "human", "agent", "model"];
8206
8311
  var ORIGINS = ["user", "self", "external"];
8207
8312
  var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
8208
- var KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
8313
+ var KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
8314
+ function collapseDescription(value) {
8315
+ const collapsed = value.replace(/\s+/g, " ").trim();
8316
+ return collapsed.length === 0 ? void 0 : collapsed;
8317
+ }
8209
8318
  var pad2 = (value) => String(value).padStart(2, "0");
8210
8319
  function localIso(epochMs) {
8211
8320
  const date = new Date(epochMs);
@@ -8281,6 +8390,11 @@ function parseNote(raw, now = Date.now()) {
8281
8390
  meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
8282
8391
  for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
8283
8392
  meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
8393
+ if (meta.description !== void 0) {
8394
+ const description = typeof meta.description === "string" ? collapseDescription(meta.description) : void 0;
8395
+ if (description === void 0) delete meta.description;
8396
+ else meta.description = description;
8397
+ }
8284
8398
  return { meta, body };
8285
8399
  }
8286
8400
  function yamlScalar(value) {
@@ -8331,42 +8445,6 @@ import { randomUUID as randomUUID2 } from "node:crypto";
8331
8445
  import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
8332
8446
  import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
8333
8447
 
8334
- // src/text-match.ts
8335
- var InvalidQueryError = class extends Error {
8336
- constructor(message) {
8337
- super(message);
8338
- this.name = "InvalidQueryError";
8339
- }
8340
- };
8341
- function searchQueries(query) {
8342
- const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
8343
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
8344
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8345
- return candidates.filter((candidate) => candidate !== "");
8346
- }
8347
- function prefixFit(text, fits) {
8348
- if (fits(text)) return text;
8349
- const chars = Array.from(text);
8350
- let low = 0;
8351
- let high = chars.length;
8352
- while (low < high) {
8353
- const mid = Math.ceil((low + high) / 2);
8354
- if (fits(chars.slice(0, mid).join(""))) low = mid;
8355
- else high = mid - 1;
8356
- }
8357
- return chars.slice(0, low).join("");
8358
- }
8359
- function earliestMatchOffsetChars(text, queries) {
8360
- let earliest = -1;
8361
- for (const query of queries) {
8362
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8363
- const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
8364
- if (index < 0) continue;
8365
- if (earliest < 0 || index < earliest) earliest = index;
8366
- }
8367
- return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
8368
- }
8369
-
8370
8448
  // src/notes/identity.ts
8371
8449
  import { resolve } from "node:path";
8372
8450
  function requireString(field, value) {
@@ -8610,6 +8688,9 @@ function projectKey(cwd, home) {
8610
8688
  }
8611
8689
 
8612
8690
  // src/notes/store.ts
8691
+ function compareNoteRows(a, b) {
8692
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
8693
+ }
8613
8694
  var lastWriteStamp = 0;
8614
8695
  function writeStamp() {
8615
8696
  const now = Date.now();
@@ -8809,6 +8890,7 @@ function createNotesStore(input) {
8809
8890
  async function write(address, content, options = {}) {
8810
8891
  const stableOptions = { ...options };
8811
8892
  validateNotePolicy(stableOptions);
8893
+ const description = stableOptions.description === void 0 ? void 0 : collapseDescription(stableOptions.description);
8812
8894
  const destination = assertAddress(address);
8813
8895
  assertWritablePath(destination.path);
8814
8896
  const scope = destination.scope;
@@ -8836,6 +8918,9 @@ function createNotesStore(input) {
8836
8918
  };
8837
8919
  meta.scope = scope;
8838
8920
  applyNotePolicy(meta, stableOptions);
8921
+ if (description === void 0) {
8922
+ if (stableOptions.description !== void 0) delete meta.description;
8923
+ } else meta.description = description;
8839
8924
  if (origin !== void 0) meta.origin = origin;
8840
8925
  delete meta.crumpledAt;
8841
8926
  meta.updatedAt = now;
@@ -8843,7 +8928,7 @@ function createNotesStore(input) {
8843
8928
  assertSerializedSize(serialized);
8844
8929
  await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
8845
8930
  await atomicWrite(path, serialized);
8846
- return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
8931
+ return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
8847
8932
  }));
8848
8933
  }
8849
8934
  async function read(address) {
@@ -8865,14 +8950,15 @@ function createNotesStore(input) {
8865
8950
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
8866
8951
  const stableOptions = { ...options };
8867
8952
  validateNotePolicy(stableOptions);
8953
+ const description = stableOptions.description === void 0 ? void 0 : collapseDescription(stableOptions.description);
8868
8954
  const from = assertAddress(address);
8869
8955
  const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
8870
8956
  assertWritablePath(destination.path);
8871
8957
  const scope = destination.scope;
8872
8958
  assertWritableNamespace(from.scope, from.who, identity2);
8873
8959
  assertWritableNamespace(scope, destination.who, identity2);
8874
- if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0 && stableOptions.pinned === void 0 && stableOptions.budget === void 0 && stableOptions.readonly === void 0) {
8875
- throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
8960
+ if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.description === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0 && stableOptions.pinned === void 0 && stableOptions.budget === void 0 && stableOptions.readonly === void 0) {
8961
+ throw new NoteError("nothing_to_do", "Nothing to change: provide edits, a description, policy, an origin, a crumpled state, or a new address.");
8876
8962
  }
8877
8963
  const fromPath = physicalPath(from.scope, from.path, identity2, from.who);
8878
8964
  const path = physicalPath(scope, destination.path, identity2, destination.who);
@@ -8896,6 +8982,9 @@ function createNotesStore(input) {
8896
8982
  if (moved && targetRaw !== void 0) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
8897
8983
  const beforeMeta = { ...meta };
8898
8984
  applyNotePolicy(meta, stableOptions);
8985
+ if (description === void 0) {
8986
+ if (stableOptions.description !== void 0) delete meta.description;
8987
+ } else meta.description = description;
8899
8988
  meta.scope = scope;
8900
8989
  if (from.scope !== "session" && scope === "session") meta.project = identity2.projectKey;
8901
8990
  if (from.scope === "session" && scope !== "session") delete meta.project;
@@ -8906,13 +8995,15 @@ function createNotesStore(input) {
8906
8995
  const newText = operation?.newText;
8907
8996
  if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
8908
8997
  if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
8998
+ if (operation.replaceAll !== void 0 && typeof operation.replaceAll !== "boolean") throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
8999
+ const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
8909
9000
  const lines = matchLineNumbers(next, oldText);
8910
9001
  if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
8911
- if (lines.length > 1 && !stableOptions.replaceAll) {
9002
+ if (lines.length > 1 && !replaceAll) {
8912
9003
  throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
8913
9004
  }
8914
9005
  if (oldText !== newText) applied++;
8915
- if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
9006
+ if (replaceAll) next = next.split(oldText).join(newText);
8916
9007
  else {
8917
9008
  const matchIndex = next.indexOf(oldText);
8918
9009
  next = next.substring(0, matchIndex) + newText + next.substring(matchIndex + oldText.length);
@@ -8924,10 +9015,11 @@ function createNotesStore(input) {
8924
9015
  const bodyChanged = body !== next;
8925
9016
  const originChanged = beforeMeta.origin !== meta.origin;
8926
9017
  const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
8927
- if (bodyChanged || originChanged || policyChanged || moved) meta.updatedAt = writeStamp();
9018
+ const descriptionChanged = beforeMeta.description !== meta.description;
9019
+ if (bodyChanged || originChanged || policyChanged || descriptionChanged || moved) meta.updatedAt = writeStamp();
8928
9020
  const serialized = serializeNote(meta, next);
8929
9021
  assertSerializedSize(serialized);
8930
- const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
9022
+ const metadataChanged = originChanged || policyChanged || descriptionChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
8931
9023
  let change;
8932
9024
  if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
8933
9025
  else if (bodyChanged) change = { kind: "body", before: body, after: next };
@@ -8942,7 +9034,7 @@ function createNotesStore(input) {
8942
9034
  );
8943
9035
  await atomicWrite(sameFile ? sourceReal : path, serialized);
8944
9036
  if (moved) await rm(fromPath, { force: true });
8945
- return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
9037
+ return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
8946
9038
  };
8947
9039
  return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
8948
9040
  }
@@ -9010,7 +9102,7 @@ function createNotesStore(input) {
9010
9102
  for await (const row of scan(stableOptions, status)) {
9011
9103
  rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
9012
9104
  }
9013
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
9105
+ rows.sort(compareNoteRows);
9014
9106
  return { rows, status: status ?? { namespacesUnavailable: [] } };
9015
9107
  }
9016
9108
  function listWithStatus(options = {}) {
@@ -9025,7 +9117,7 @@ function createNotesStore(input) {
9025
9117
  const rows = [];
9026
9118
  for await (const note of scan(stableOptions, status)) {
9027
9119
  const { address, path, scope, meta, body } = note;
9028
- const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
9120
+ const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
9029
9121
  if (stableQueries.length === 0) {
9030
9122
  rows.push({ address, path, scope, meta, warnings, matches: [] });
9031
9123
  continue;
@@ -9055,7 +9147,8 @@ var TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
9055
9147
  var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
9056
9148
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
9057
9149
  var MAX_READ_WINDOW_CHARS = 5e4;
9058
- var HISTORY_PREVIEW_CHARS = 1200;
9150
+ var HISTORY_PREVIEW_CHARS = 2500;
9151
+ var HISTORY_READ_WINDOW_CHARS = 8e3;
9059
9152
 
9060
9153
  // src/result.ts
9061
9154
  var OperationErrorSchema = typebox_exports.Object({
@@ -9088,8 +9181,11 @@ function renderOutcome(result, renderData) {
9088
9181
  function structuredBytes(value) {
9089
9182
  return Buffer.byteLength(JSON.stringify(value), "utf8");
9090
9183
  }
9184
+ function fitsText(text) {
9185
+ return Buffer.byteLength(text, "utf8") <= TOOL_OUTPUT_MAX_BYTES;
9186
+ }
9091
9187
  function fitsResult(result, render) {
9092
- return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
9188
+ return fitsText(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
9093
9189
  }
9094
9190
  var TextWindowSchema = typebox_exports.Object({
9095
9191
  text: typebox_exports.String(),
@@ -9097,10 +9193,10 @@ var TextWindowSchema = typebox_exports.Object({
9097
9193
  next_offset_chars: typebox_exports.Union([typebox_exports.Integer({ minimum: 0 }), typebox_exports.Null()], { description: "Pass as `offset_chars` to continue; null at the end." })
9098
9194
  }, { additionalProperties: false });
9099
9195
  var TextWindowRequestSchema = {
9100
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
9196
+ offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Character offset to start reading (negative counts from the end)." })),
9101
9197
  max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." }))
9102
9198
  };
9103
- function readTextWindow(text, offset, limit, makeData, render) {
9199
+ function readTextWindow(text, offset, limit, makeData, render, fitsOutcome = (result) => fitsText(render(result))) {
9104
9200
  const chars = Array.from(text);
9105
9201
  const requested = offset ?? 0;
9106
9202
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
@@ -9114,7 +9210,7 @@ function readTextWindow(text, offset, limit, makeData, render) {
9114
9210
  next_offset_chars: end < chars.length ? end : null
9115
9211
  };
9116
9212
  };
9117
- const fits = (delivered2) => fitsResult(success(makeData(window(delivered2))), render);
9213
+ const fits = (delivered2) => fitsOutcome(success(makeData(window(delivered2))));
9118
9214
  if (fits(range)) return success(makeData(window(range)));
9119
9215
  const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
9120
9216
  if (delivered === 0) return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
@@ -9124,7 +9220,7 @@ function renderTextWindow(window) {
9124
9220
  const next = window.next_offset_chars;
9125
9221
  return next === null ? window.text : `${window.text}
9126
9222
 
9127
- [truncated; continue at offset_chars=${next}]`;
9223
+ [truncated at ${next}/${window.total_chars} chars; continue at offset_chars=${next}]`;
9128
9224
  }
9129
9225
 
9130
9226
  // src/tools/notes-context.ts
@@ -9150,14 +9246,14 @@ function notesIdentityForCall(context2, cwd) {
9150
9246
  }
9151
9247
 
9152
9248
  // src/tools/notes.ts
9153
- var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("self"), typebox_exports.Literal("external")];
9154
- var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
9155
- description: "Whose handwriting: user, self, or external. Leave it out to keep what's there."
9249
+ var ORIGIN_VALUES = ["user", "self", "external"];
9250
+ var ORIGIN = typebox_exports.Optional(stringEnum(ORIGIN_VALUES, {
9251
+ description: "Author tag. Omit to keep existing."
9156
9252
  }));
9253
+ var DESCRIPTION_PARAMETER = typebox_exports.Optional(typebox_exports.String({ description: "One-line summary for the boot index (empty string clears it)." }));
9157
9254
  var POLICY_PARAMETERS = {
9158
- pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
9159
- budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
9160
- readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off \u2014 same call is fine." }))
9255
+ pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject at wake-up (truncated to byte budget if oversized)." })),
9256
+ readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock against edits, moves, and deletion." }))
9161
9257
  };
9162
9258
  var PolicySchema = {
9163
9259
  pinned: typebox_exports.Boolean(),
@@ -9171,32 +9267,43 @@ function policyAt(meta, address) {
9171
9267
  function renderPolicy(policy) {
9172
9268
  return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
9173
9269
  }
9270
+ function renderSparsePolicy(policy, address) {
9271
+ const defaults = effectiveNotePolicy({}, noteFileName(assertAddress(address).path));
9272
+ const tokens = [];
9273
+ if (policy.pinned) tokens.push("pinned");
9274
+ else if (defaults.pinned) tokens.push("pinned false");
9275
+ if (policy.budget !== defaults.budget) tokens.push(`budget ${policy.budget}`);
9276
+ if (policy.readonly) tokens.push("readonly");
9277
+ return tokens.join(" | ");
9278
+ }
9174
9279
  function withWarnings(text, data) {
9175
- return [text, ...data.warnings].join("\n");
9280
+ return data.warnings.length === 0 ? text : `${text}
9281
+ ${renderWarnings(data.warnings)}`;
9176
9282
  }
9177
- 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." }));
9178
- var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Only the crumpled balls." }));
9179
- var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many pages at most." }));
9180
- 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." }));
9283
+ var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Crumple (`true`) or restore (`false`) the note." }));
9284
+ var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "List crumpled notes instead of live ones." }));
9285
+ var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Maximum notes to return." }));
9286
+ var GLOB_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Address glob. Omit for current notebooks; `**` for all; `@projects/*/**` or `@sessions/*/**` for named notebooks." }));
9181
9287
  var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
9182
- 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." });
9288
+ var ADDRESS_PARAMETER = typebox_exports.String({ description: "Note address (per boot protocol). Never pass `@` addresses to filesystem tools." });
9183
9289
  function failureOf(error) {
9184
9290
  if (error instanceof NoteError) return failure(error.code, error.message);
9185
9291
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9186
9292
  if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
9187
9293
  throw error;
9188
9294
  }
9189
- var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly"]);
9295
+ var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly", "description"]);
9190
9296
  var MAX_METADATA_ENTRY_BYTES = 1024;
9191
9297
  var MAX_METADATA_VERBATIM_BYTES = 2048;
9192
9298
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9193
9299
  var NoteMetadataSchema = typebox_exports.Object({
9194
9300
  ...PolicySchema,
9195
- origin: typebox_exports.Union([...ORIGIN_VALUES]),
9301
+ origin: stringEnum(ORIGIN_VALUES),
9196
9302
  created_at: typebox_exports.String(),
9197
9303
  updated_at: typebox_exports.String(),
9198
9304
  crumpled_at: typebox_exports.Optional(typebox_exports.String()),
9199
9305
  project: typebox_exports.Optional(typebox_exports.String()),
9306
+ description: typebox_exports.Optional(typebox_exports.String()),
9200
9307
  extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
9201
9308
  }, { additionalProperties: false });
9202
9309
  function noteMetadata(meta, address) {
@@ -9223,6 +9330,7 @@ function noteMetadata(meta, address) {
9223
9330
  updated_at: localIso(meta.updatedAt),
9224
9331
  ...typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {},
9225
9332
  ...typeof meta.project === "string" ? { project: meta.project } : {},
9333
+ ...typeof meta.description === "string" ? { description: meta.description } : {},
9226
9334
  extra
9227
9335
  };
9228
9336
  }
@@ -9233,7 +9341,8 @@ function renderMetadata(metadata) {
9233
9341
  `created ${metadata.created_at}`,
9234
9342
  `updated ${metadata.updated_at}`,
9235
9343
  ...metadata.crumpled_at === void 0 ? [] : [`crumpled ${metadata.crumpled_at}`],
9236
- ...metadata.project === void 0 ? [] : [`project ${metadata.project}`]
9344
+ ...metadata.project === void 0 ? [] : [`project ${metadata.project}`],
9345
+ ...metadata.description === void 0 ? [] : [`description ${metadata.description}`]
9237
9346
  ];
9238
9347
  const extra = Object.keys(metadata.extra);
9239
9348
  if (extra.length > 0) fields.push(`extra ${JSON.stringify(metadata.extra)}`);
@@ -9255,54 +9364,17 @@ var NoteIdentitySchema = {
9255
9364
  project_key: typebox_exports.Optional(typebox_exports.String()),
9256
9365
  ...ProjectReceiptSchema
9257
9366
  };
9258
- var ListedFileSchema = typebox_exports.Object({
9259
- ...NoteIdentitySchema,
9260
- ...PolicySchema,
9261
- ...WarningsSchema,
9262
- updated_at: typebox_exports.String(),
9263
- crumpled_at: typebox_exports.Optional(typebox_exports.String())
9264
- }, { additionalProperties: false });
9265
- var MatchSchema = typebox_exports.Object({
9266
- line: typebox_exports.Integer(),
9267
- text: typebox_exports.String(),
9268
- offset_chars: typebox_exports.Integer()
9269
- }, { additionalProperties: false });
9270
- var SnapshotSchema = {
9271
- more: typebox_exports.Integer({ description: "How many more were left out." }),
9272
- namespaces_unavailable: typebox_exports.Array(typebox_exports.String(), { description: "Unreadable notebooks or notes." })
9273
- };
9274
- var NotesWriteDataSchema = typebox_exports.Object({
9275
- ...NoteIdentitySchema,
9276
- ...PolicySchema,
9277
- ...WarningsSchema,
9278
- outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
9279
- }, { additionalProperties: false });
9280
- var NotesUpdateDataSchema = typebox_exports.Object({
9281
- ...NoteIdentitySchema,
9282
- ...PolicySchema,
9283
- ...WarningsSchema,
9284
- change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
9285
- rename_from: typebox_exports.Optional(typebox_exports.String())
9286
- }, { additionalProperties: false });
9287
9367
  var NotesReadDataSchema = typebox_exports.Object({
9288
9368
  ...NoteIdentitySchema,
9289
9369
  metadata: NoteMetadataSchema,
9290
9370
  ...WarningsSchema,
9291
9371
  ...TextWindowSchema.properties
9292
9372
  }, { additionalProperties: false });
9293
- var NotesListDataSchema = typebox_exports.Object({
9294
- files: typebox_exports.Array(typebox_exports.Object({
9295
- ...ListedFileSchema.properties,
9296
- matches: typebox_exports.Optional(typebox_exports.Array(MatchSchema)),
9297
- more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
9298
- }, { additionalProperties: false })),
9299
- ...SnapshotSchema
9300
- }, { additionalProperties: false });
9301
9373
  function snapshot(rows, limit, status, renderData, shrink) {
9302
9374
  const files = [];
9303
9375
  const data = (selected) => ({ files: selected, more: rows.length - selected.length, namespaces_unavailable: status.namespacesUnavailable });
9304
9376
  const render = (outcome2) => renderOutcome(outcome2, renderData);
9305
- const fits = (item) => fitsResult(success(data([...files, item])), render);
9377
+ const fits = (item) => fitsText(render(success(data([...files, item]))));
9306
9378
  for (const item of rows.slice(0, limit)) {
9307
9379
  if (fits(item)) {
9308
9380
  files.push(item);
@@ -9316,27 +9388,28 @@ function snapshot(rows, limit, status, renderData, shrink) {
9316
9388
  break;
9317
9389
  }
9318
9390
  const outcome = success(data(files));
9319
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
9391
+ return fitsText(render(outcome)) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
9320
9392
  }
9321
9393
  function listedFile(row, identity2) {
9322
9394
  const policy = policyAt(row.meta, row.address);
9323
- return { ...noteIdentity(identity2, row.address), ...policy, warnings: row.warnings ?? (row.body === void 0 ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9395
+ const warnings = row.warnings ?? (row.body === void 0 ? noteDescriptionWarnings(row.meta.description) : noteWarnings(row.body, policy, row.meta.description));
9396
+ return { ...noteIdentity(identity2, row.address), ...policy, warnings, updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt }, ...typeof row.meta.description === "string" ? { description: row.meta.description } : {} };
9324
9397
  }
9325
- var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9398
+ var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "Full markdown body." }), origin: ORIGIN, description: DESCRIPTION_PARAMETER, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9326
9399
  function renderWriteData(data) {
9327
- return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
9400
+ const sparse = renderSparsePolicy(data, data.address);
9401
+ return withWarnings(`${data.outcome} ${renderIdentity(data)}${sparse === "" ? "" : ` | ${sparse}`}`, data);
9328
9402
  }
9329
9403
  var notesWrite = {
9330
9404
  name: "notes_write",
9331
9405
  label: "Notes write",
9332
- description: "Take a fresh page and write it \u2014 or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
9406
+ description: "Create or overwrite a note. Set `description` (one line) so boot indexes it.",
9333
9407
  parameters: notesWriteParameters,
9334
- outputSchema: resultSchema(NotesWriteDataSchema),
9335
9408
  executionMode: "sequential",
9336
9409
  async execute(params, context2) {
9337
9410
  try {
9338
9411
  const identity2 = notesIdentityForCall(context2, params.cwd);
9339
- const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
9412
+ const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, description: params.description, pinned: params.pinned, readonly: params.readonly });
9340
9413
  return success({ ...noteIdentity(identity2, params.address), outcome, ...policyAt(meta, params.address), warnings });
9341
9414
  } catch (error) {
9342
9415
  return failureOf(error);
@@ -9346,31 +9419,37 @@ var notesWrite = {
9346
9419
  };
9347
9420
  var notesUpdateParameters = typebox_exports.Object({
9348
9421
  address: ADDRESS_PARAMETER,
9349
- edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String({ description: "The passage as it stands on the page." }), newText: typebox_exports.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage \u2014 same case, found once \u2014 and `newText` is what goes in its place." })),
9422
+ edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
9423
+ oldText: typebox_exports.String({ description: "Exact text to replace." }),
9424
+ newText: typebox_exports.String({ description: "Replacement text." }),
9425
+ replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Replace every occurrence (overrides top-level `replace_all`)." }))
9426
+ }, { additionalProperties: false }), { description: "Sequential exact text replacements." })),
9350
9427
  origin: ORIGIN,
9428
+ description: DESCRIPTION_PARAMETER,
9351
9429
  ...POLICY_PARAMETERS,
9352
9430
  crumpled: CRUMPLED_PARAMETER,
9353
- replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
9354
- rename_to: typebox_exports.Optional(typebox_exports.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
9431
+ replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Replace every occurrence in edits that omit `replace_all`." })),
9432
+ rename_to: typebox_exports.Optional(typebox_exports.String({ description: "Move note to this address." })),
9355
9433
  cwd: CWD_PARAMETER
9356
9434
  }, { additionalProperties: false });
9357
9435
  function renderUpdateData(data) {
9358
9436
  const receipt = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
9359
- return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
9437
+ const sparse = renderSparsePolicy(data, data.address);
9438
+ return withWarnings(`${receipt}${sparse === "" ? "" : ` | ${sparse}`}`, data);
9360
9439
  }
9361
9440
  var notesUpdate = {
9362
9441
  name: "notes_update",
9363
9442
  label: "Notes update",
9364
- description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
9443
+ description: "Edit an existing note's text or metadata, move it (`rename_to`), or crumple/restore it (`crumpled`).",
9365
9444
  parameters: notesUpdateParameters,
9366
- outputSchema: resultSchema(NotesUpdateDataSchema),
9367
9445
  executionMode: "sequential",
9368
9446
  async execute(params, context2, onChange) {
9369
9447
  try {
9370
9448
  const identity2 = notesIdentityForCall(context2, params.cwd);
9371
9449
  const store = createNotesStore(identity2);
9372
9450
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
9373
- const { change, moved, meta, warnings } = await store.update(params.address, params.edits, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9451
+ const edits = params.edits?.map((edit) => ({ oldText: edit.oldText, newText: edit.newText, ...edit.replace_all === void 0 ? {} : { replaceAll: edit.replace_all } }));
9452
+ const { change, moved, meta, warnings } = await store.update(params.address, edits, { origin: params.origin, description: params.description, pinned: params.pinned, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9374
9453
  onChange?.(change);
9375
9454
  const from = noteIdentity(identity2, params.address).address;
9376
9455
  const to = noteIdentity(identity2, renameTo ?? params.address);
@@ -9391,7 +9470,7 @@ ${renderTextWindow(data)}`;
9391
9470
  var notesRead = {
9392
9471
  name: "notes_read",
9393
9472
  label: "Notes read",
9394
- description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
9473
+ description: "Read a note (supports windowed reads via `offset_chars` and `max_chars`).",
9395
9474
  parameters: notesReadParameters,
9396
9475
  outputSchema: resultSchema(NotesReadDataSchema),
9397
9476
  async execute(params, context2) {
@@ -9403,8 +9482,9 @@ var notesRead = {
9403
9482
  const totalChars = Array.from(note.body).length;
9404
9483
  if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
9405
9484
  const metadata = noteMetadata(note.meta, resolved.address);
9406
- const warnings = noteBudgetWarnings(note.body, metadata);
9407
- return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
9485
+ const warnings = noteWarnings(note.body, metadata, metadata.description);
9486
+ const render = (result) => renderOutcome(result, renderReadData);
9487
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), render, (result) => fitsResult(result, render));
9408
9488
  } catch (error) {
9409
9489
  return failureOf(error);
9410
9490
  }
@@ -9413,91 +9493,115 @@ var notesRead = {
9413
9493
  };
9414
9494
  var notesListParameters = typebox_exports.Object({
9415
9495
  glob: GLOB_PARAMETER,
9416
- query: typebox_exports.Optional(searchQuery()),
9417
- max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per note at most; requires a query." })),
9496
+ query: typebox_exports.Optional(searchQuery("Case-insensitive literal text, or a list (any match). Omit to list.")),
9497
+ max_matches_per_note: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Maximum matching lines shown per note." })),
9418
9498
  crumpled: CRUMPLED_LIST_PARAMETER,
9419
9499
  limit: FILE_LIMIT_PARAMETER,
9500
+ cursor: typebox_exports.Optional(typebox_exports.String({ description: "Cursor from an `\u2192 older` footer (`<updated_at> <address>`)." })),
9420
9501
  cwd: CWD_PARAMETER
9421
9502
  }, { additionalProperties: false });
9422
- function renderListData(data) {
9503
+ function moreMatches(more, tail) {
9504
+ return `${more} more matching ${more === 1 ? "note" : "notes"}${tail}`;
9505
+ }
9506
+ function renderListData(data, renderMore = (more) => moreMatches(more, " omitted; narrow with glob"), options = {}) {
9423
9507
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9424
9508
  for (const file of data.files) {
9425
- const fields = [`- ${renderIdentity(file)}`, renderPolicy(file), `updated ${file.updated_at}`];
9509
+ const identity2 = file.address.startsWith("@project/") || options.omitNamedProjectContext ? renderIdentity({ address: file.address }) : renderIdentity(file);
9510
+ const sparse = renderSparsePolicy(file, file.address);
9511
+ const fields = [`- ${identity2}${file.description === void 0 ? "" : ` \u2014 ${file.description}`}`, ...sparse === "" ? [] : [sparse], `updated ${file.updated_at}`];
9426
9512
  if (file.last_accessed !== void 0) fields.push(`accessed ${file.last_accessed}`);
9427
9513
  if (file.crumpled_at !== void 0) fields.push(`crumpled ${file.crumpled_at}`);
9428
9514
  if (file.matches) fields.push(`${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
9429
9515
  lines.push(fields.join(" | "));
9430
- lines.push(...file.warnings.map((warning) => ` ${warning}`));
9516
+ lines.push(...file.warnings.map((warning) => ` ${renderWarnings([warning])}`));
9431
9517
  for (const match of file.matches ?? []) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9432
9518
  }
9433
- if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9519
+ if (data.more > 0) lines.push(renderMore(data.more, data.files));
9434
9520
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
9435
9521
  return lines.join("\n");
9436
9522
  }
9437
- function keepMatches(file, count = file.matches.length) {
9438
- const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
9439
- return { ...file, matches: file.matches.slice(0, count), ...more ? { more_matches: more } : {} };
9523
+ function keepMatches(file, count = file.matches?.length ?? 0) {
9524
+ const matches = file.matches ?? [];
9525
+ const more = (file.more_matches ?? 0) + Math.max(0, matches.length - count);
9526
+ return { ...file, matches: matches.slice(0, count), ...more ? { more_matches: more } : {} };
9440
9527
  }
9441
9528
  var MATCH_SHORTENED_MARKER = " [truncated]";
9442
9529
  function fitSearchFile(file, fits) {
9530
+ const matches = file.matches ?? [];
9443
9531
  let low = 0;
9444
- let high = file.matches.length;
9532
+ let high = matches.length;
9445
9533
  while (low < high) {
9446
9534
  const mid = Math.ceil((low + high) / 2);
9447
9535
  if (fits(keepMatches(file, mid))) low = mid;
9448
9536
  else high = mid - 1;
9449
9537
  }
9450
- if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
9451
- const first = file.matches[0];
9538
+ if (low > 0 || matches.length === 0) return keepMatches(file, low);
9539
+ const first = matches[0];
9452
9540
  const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
9453
9541
  return withText(prefixFit(first.text, (text) => fits(withText(text))));
9454
9542
  }
9543
+ function parseCursor(raw, identity2) {
9544
+ if (raw === void 0 || raw === "") return success(void 0);
9545
+ const space = raw.indexOf(" ");
9546
+ if (space <= 0 || space === raw.length - 1) return failure("invalid_params", "`cursor` must be `<updated_at> <address>`.");
9547
+ const atMs = parseIsoTimestamp(raw.slice(0, space));
9548
+ if (atMs === void 0) return failure("invalid_params", "`cursor` starts with an invalid ISO 8601 timestamp.");
9549
+ try {
9550
+ return success({ atMs, address: noteIdentity(identity2, raw.slice(space + 1)).address });
9551
+ } catch {
9552
+ return failure("invalid_params", "`cursor` ends with an invalid note address.");
9553
+ }
9554
+ }
9555
+ function olderThan(file, cursor) {
9556
+ const atMs = parseIsoTimestamp(file.updated_at);
9557
+ return atMs < cursor.atMs || atMs === cursor.atMs && file.address.localeCompare(cursor.address) > 0;
9558
+ }
9559
+ function renderOlderPage(more, files, params, searching) {
9560
+ const last = files[files.length - 1];
9561
+ if (last === void 0) return moreMatches(more, " omitted; narrow glob");
9562
+ const next = {};
9563
+ if (params.glob !== void 0) next.glob = params.glob;
9564
+ if (searching) next.query = params.query;
9565
+ if (params.max_matches_per_note !== void 0) next.max_matches_per_note = params.max_matches_per_note;
9566
+ if (params.crumpled !== void 0) next.crumpled = params.crumpled;
9567
+ if (params.limit !== void 0) next.limit = params.limit;
9568
+ if (params.cwd !== void 0) next.cwd = params.cwd;
9569
+ next.cursor = `${last.updated_at} ${last.address}`;
9570
+ return moreMatches(more, ` | \u2192 older: ${JSON.stringify(next)}`);
9571
+ }
9455
9572
  var notesList = {
9456
9573
  name: "notes_list",
9457
9574
  label: "Notes list",
9458
- 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`.",
9575
+ description: "List or search notes, newest first. Literal case-insensitive `query` returns matching lines and `offset_chars`.",
9459
9576
  parameters: notesListParameters,
9460
- outputSchema: resultSchema(NotesListDataSchema),
9461
9577
  async execute(params, context2) {
9462
9578
  try {
9463
9579
  const queries = searchQueries(params.query);
9464
9580
  const { glob, crumpled, limit } = params;
9465
- if (!queries.length && params.max_matches_per_file !== void 0) return failure("invalid_params", "`max_matches_per_file` requires a non-empty `query`.");
9581
+ if (!queries.length && params.max_matches_per_note !== void 0) return failure("invalid_params", "`max_matches_per_note` requires a non-empty `query`.");
9466
9582
  const identity2 = notesIdentityForCall(context2, params.cwd);
9583
+ const cursor = parseCursor(params.cursor, identity2);
9584
+ if (!cursor.ok) return cursor;
9467
9585
  const store = createNotesStore(identity2);
9468
- if (!queries.length) {
9469
- const { rows: rows2, status: status2 } = await store.listWithStatus({ glob, crumpled });
9470
- return snapshot(rows2.map((row) => listedFile(row, identity2)), limit, status2, renderListData);
9471
- }
9472
- const { rows, status } = await store.searchWithStatus(queries, { glob, crumpled });
9473
- const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => keepMatches({
9586
+ const result = queries.length ? await store.searchWithStatus(queries, { glob, crumpled }) : await store.listWithStatus({ glob, crumpled });
9587
+ const rows = result.rows;
9588
+ rows.sort(compareNoteRows);
9589
+ const files = rows.map((row) => "matches" in row ? keepMatches({
9474
9590
  ...listedFile(row, identity2),
9475
9591
  matches: row.matches.map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9476
- }, params.max_matches_per_file));
9477
- return snapshot(files, limit, status, renderListData, fitSearchFile);
9592
+ }, params.max_matches_per_note) : listedFile(row, identity2));
9593
+ const page = files.filter((file) => cursor.data === void 0 || olderThan(file, cursor.data));
9594
+ const outcome = snapshot(page, limit, result.status, (data) => renderListData(data, (more, shown2) => renderOlderPage(more, shown2, params, queries.length > 0)), queries.length ? fitSearchFile : void 0);
9595
+ if (!outcome.ok || outcome.data.more === 0) return outcome;
9596
+ return success({ ...outcome.data, older: renderOlderPage(outcome.data.more, outcome.data.files, params, queries.length > 0) });
9478
9597
  } catch (error) {
9479
9598
  return failureOf(error);
9480
9599
  }
9481
9600
  },
9482
- render: (result) => renderOutcome(result, renderListData)
9601
+ render: (result) => renderOutcome(result, (data) => renderListData(data, (more) => data.older ?? moreMatches(more, " omitted; narrow with glob")))
9483
9602
  };
9484
9603
 
9485
9604
  // src/history/query.ts
9486
- var multiPages = /* @__PURE__ */ new WeakSet();
9487
- function isMultiPage(page) {
9488
- return multiPages.has(page);
9489
- }
9490
- function markMultiPage(page) {
9491
- multiPages.add(page);
9492
- return page;
9493
- }
9494
- var HistoryPageSchema = typebox_exports.Object({
9495
- notice: typebox_exports.Optional(typebox_exports.String()),
9496
- items: typebox_exports.Array(HistoryPageItemSchema),
9497
- folded_after: typebox_exports.Optional(HistoryFoldedRowSchema),
9498
- has_older: typebox_exports.Boolean(),
9499
- has_newer: typebox_exports.Boolean()
9500
- }, { additionalProperties: false });
9501
9605
  function truncateHistoryItem(item, fits) {
9502
9606
  if (fits(item)) return item;
9503
9607
  const shrinkContent = (base) => ({
@@ -9511,7 +9615,7 @@ function truncateHistoryItem(item, fits) {
9511
9615
  const { tool: _dropped, ...withoutName } = item;
9512
9616
  return fits(withoutName) ? withoutName : shrinkContent(withoutName);
9513
9617
  }
9514
- function foldedRun(events, session) {
9618
+ function foldedRun(events) {
9515
9619
  if (events.length === 0) return void 0;
9516
9620
  const counts = /* @__PURE__ */ new Map();
9517
9621
  for (const event of events) {
@@ -9521,31 +9625,30 @@ function foldedRun(events, session) {
9521
9625
  }
9522
9626
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
9523
9627
  const tools = Object.fromEntries(entries);
9524
- return { ...session === void 0 ? {} : { session }, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9628
+ return { first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9525
9629
  }
9526
9630
  var visible = (event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "";
9527
- function* queryHits(projection, params, session) {
9528
- const { query, context: context2 } = params;
9631
+ function* queryHits(projection, params, patterns, session) {
9632
+ const { context: context2 } = params;
9529
9633
  const events = filteredItems(projection, context2 ? {} : params).filter(visible);
9530
9634
  for (const [index, event] of events.entries()) {
9531
9635
  if (context2 && !matchesFilter(event, params)) continue;
9532
- const matchOffset = earliestMatchOffsetChars(eventDocument(event), query);
9636
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), patterns);
9533
9637
  if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context2 ? { events, index } : void 0 };
9534
9638
  }
9535
9639
  }
9536
9640
  function prepareSelection(projection, params) {
9537
- const { query, roles, session } = params;
9538
- if (query) return { candidates: [...queryHits(projection, params, session)] };
9641
+ const { roles } = params;
9539
9642
  const candidates = [];
9540
9643
  let run = [];
9541
9644
  for (const event of filteredItems(projection, params).filter(visible)) {
9542
9645
  if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
9543
9646
  else {
9544
- candidates.push({ event, session, before: foldedRun(run, session) });
9647
+ candidates.push({ event, before: foldedRun(run) });
9545
9648
  run = [];
9546
9649
  }
9547
9650
  }
9548
- return { candidates, tail: foldedRun(run, session) };
9651
+ return { candidates, tail: foldedRun(run) };
9549
9652
  }
9550
9653
  function pageData(prepared, start, end, maxChars, preview) {
9551
9654
  const { candidates, tail } = prepared;
@@ -9555,31 +9658,54 @@ function pageData(prepared, start, end, maxChars, preview) {
9555
9658
  const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } });
9556
9659
  items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
9557
9660
  }
9558
- const page = {
9661
+ return {
9559
9662
  items,
9560
9663
  ...end === candidates.length && tail ? { folded_after: tail } : {},
9561
9664
  has_older: start > 0 && start < end || !!prepared.discarded && !prepared.forward,
9562
9665
  has_newer: end < candidates.length && start < end || !!prepared.discarded && !!prepared.forward
9563
9666
  };
9564
- return prepared.multi ? markMultiPage(page) : page;
9565
9667
  }
9566
9668
  function selectPage(projection, params, fits, maxChars) {
9567
9669
  return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
9568
9670
  }
9671
+ function summarizeProjection(projection) {
9672
+ const events = filteredItems(projection, {}).filter(visible);
9673
+ let firstUser;
9674
+ let lastAssistant;
9675
+ const latestByRole = {};
9676
+ let minCreatedAt = Infinity;
9677
+ let maxCreatedAt = -Infinity;
9678
+ let hasUntimed = false;
9679
+ for (const event of events) {
9680
+ if (firstUser === void 0 && event.role === "user") firstUser = event;
9681
+ if (event.role === "assistant") lastAssistant = event;
9682
+ latestByRole[event.role] = event;
9683
+ const at = eventTimestampMs(event);
9684
+ if (Number.isNaN(at)) hasUntimed = true;
9685
+ else {
9686
+ if (at < minCreatedAt) minCreatedAt = at;
9687
+ if (at > maxCreatedAt) maxCreatedAt = at;
9688
+ }
9689
+ }
9690
+ return {
9691
+ event: firstUser ?? lastAssistant ?? events.at(-1),
9692
+ latestByRole,
9693
+ minCreatedAt: Number.isFinite(minCreatedAt) ? minCreatedAt : null,
9694
+ maxCreatedAt: Number.isFinite(maxCreatedAt) ? maxCreatedAt : null,
9695
+ hasUntimed
9696
+ };
9697
+ }
9569
9698
  function sessionRepresentative(projection, scoped) {
9570
9699
  const events = filteredItems(projection, scoped).filter(visible);
9571
9700
  if (scoped.roles) return events.at(-1);
9572
9701
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9573
9702
  }
9574
- function eventTime(timestamp) {
9575
- const at = Date.parse(timestamp ?? "");
9576
- return Number.isNaN(at) ? -Infinity : at;
9577
- }
9578
- var compareCorpus = (a, b) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
9703
+ var earliestIfUntimed = (at) => Number.isNaN(at) ? -Infinity : at;
9704
+ var compareCorpus = (a, b) => earliestIfUntimed(eventTimestampMs(a.event)) - earliestIfUntimed(eventTimestampMs(b.event)) || (a.session ?? "").localeCompare(b.session ?? "") || a.event.seq - b.event.seq;
9579
9705
  function addContext(page, hits, radius, fits, maxChars) {
9580
9706
  const key = (session, seq) => `${session ?? ""}\0${seq}`;
9581
9707
  const seen = new Set(page.items.map((item) => key(item.session, item.seq)));
9582
- const compare = (a, b) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session.localeCompare(b.session) : 0) || a.seq - b.seq;
9708
+ const compare = (a, b) => earliestIfUntimed(Date.parse(a.created_at ?? "")) - earliestIfUntimed(Date.parse(b.created_at ?? "")) || (a.session ?? "").localeCompare(b.session ?? "") || a.seq - b.seq;
9583
9709
  for (let distance = 1; distance <= radius; distance++) {
9584
9710
  let found = false;
9585
9711
  for (const { neighbors, session } of hits) {
@@ -9607,10 +9733,12 @@ var CorpusCollector = class {
9607
9733
  constructor(scoped) {
9608
9734
  this.scoped = scoped;
9609
9735
  this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
9736
+ this.compiledQuery = scoped.query?.length ? compileSearchQueries(scoped.query) : [];
9610
9737
  }
9611
9738
  scoped;
9612
9739
  candidates = [];
9613
9740
  limit;
9741
+ compiledQuery;
9614
9742
  discarded = false;
9615
9743
  admit(candidate) {
9616
9744
  let low = 0, high = this.candidates.length;
@@ -9632,48 +9760,49 @@ var CorpusCollector = class {
9632
9760
  }
9633
9761
  this.candidates.splice(low, 0, candidate);
9634
9762
  }
9635
- /** Admit an already selected strict overview event without selecting it a second time. */
9636
- addRepresentative(session, event) {
9763
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
9764
+ addRepresentative(session, source) {
9765
+ const event = source && "windows" in source ? sessionRepresentative(source, this.scoped) : source;
9637
9766
  if (!event) return false;
9638
- this.admit({ session, event });
9767
+ this.admit({ session: session || void 0, event });
9639
9768
  return true;
9640
9769
  }
9641
- /** Returns whether this session contributes an overview representative. */
9642
- add(session, projection) {
9643
- if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
9644
- for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
9645
- return true;
9770
+ /** Admit every query match from one session; an empty query matches nothing. */
9771
+ addMatches(session, projection) {
9772
+ if (this.compiledQuery.length === 0) return;
9773
+ for (const hit of queryHits(projection, this.scoped, this.compiledQuery, session || void 0)) this.admit(hit);
9646
9774
  }
9647
9775
  page(fits, maxChars, unvisited = false) {
9648
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
9776
+ const result = selectPrepared({ candidates: this.candidates, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
9777
+ if (result.ok && this.compiledQuery.length > 0 && this.scoped.context) {
9778
+ const count = result.data.items.length;
9779
+ const hits = this.scoped.after ? this.candidates.slice(0, count) : this.candidates.slice(this.candidates.length - count);
9780
+ addContext(result.data, hits, this.scoped.context, fits, maxChars);
9781
+ }
9782
+ return result;
9649
9783
  }
9650
9784
  };
9651
9785
  function selectPrepared(prepared, scoped, fits, maxChars) {
9652
9786
  const { candidates } = prepared;
9653
- const newest = scoped.after === void 0;
9654
- let start = newest ? candidates.length : 0;
9655
- let end = start;
9656
- const limit = Math.max(1, scoped.limit ?? 20);
9657
- for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
9658
- const nextStart = newest ? start - 1 : start;
9659
- const nextEnd = newest ? end : end + 1;
9660
- if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
9661
- start = nextStart;
9662
- end = nextEnd;
9663
- continue;
9787
+ const newest = scoped.after === void 0 && (scoped.before !== void 0 || scoped.since === void 0);
9788
+ const start = (count2) => newest ? candidates.length - count2 : 0;
9789
+ const pageFor = (count2, preview) => pageData(prepared, start(count2), start(count2) + count2, maxChars, preview);
9790
+ let count = Math.min(Math.max(1, scoped.limit ?? 20), candidates.length);
9791
+ if (count > 0 && !fits(pageFor(count))) {
9792
+ let low = 0, high = count - 1;
9793
+ while (low < high) {
9794
+ const mid = Math.ceil((low + high) / 2);
9795
+ if (fits(pageFor(mid))) low = mid;
9796
+ else high = mid - 1;
9664
9797
  }
9665
- if (start === end) {
9666
- start = nextStart;
9667
- end = nextEnd;
9668
- const candidate = candidates[start];
9669
- candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
9798
+ count = Math.max(1, low);
9799
+ if (low === 0) {
9800
+ const candidate = candidates[start(1)];
9801
+ candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageFor(1, preview)));
9670
9802
  }
9671
- break;
9672
9803
  }
9673
- const page = pageData(prepared, start, end, maxChars);
9674
- if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
9675
- if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
9676
- return success(page);
9804
+ const page = pageFor(count);
9805
+ return fits(page) ? success(page) : { ok: false, pageTooLarge: true };
9677
9806
  }
9678
9807
 
9679
9808
  // src/history/corpus.ts
@@ -9711,6 +9840,33 @@ async function resolveSession(corpus, selector) {
9711
9840
  if (matches.length > 1) return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
9712
9841
  return success(matches[0]);
9713
9842
  }
9843
+ function resolveSummaryForSelection(summary, scoped) {
9844
+ const afterAt = scoped.after && "at" in scoped.after ? scoped.after.at : void 0;
9845
+ const beforeAt = scoped.before && "at" in scoped.before ? scoped.before.at : void 0;
9846
+ if (afterAt !== void 0 || beforeAt !== void 0) {
9847
+ if (summary.maxCreatedAt === null || summary.minCreatedAt === null) return { kind: "empty" };
9848
+ if (afterAt !== void 0 && summary.maxCreatedAt <= afterAt) return { kind: "empty" };
9849
+ if (beforeAt !== void 0 && summary.minCreatedAt >= beforeAt) return { kind: "empty" };
9850
+ }
9851
+ if (scoped.query?.length) return { kind: "miss" };
9852
+ const fullyInsideBounds = afterAt === void 0 && beforeAt === void 0 || !summary.hasUntimed && summary.minCreatedAt !== null && summary.maxCreatedAt !== null && (afterAt === void 0 || summary.minCreatedAt > afterAt) && (beforeAt === void 0 || summary.maxCreatedAt < beforeAt);
9853
+ if (!fullyInsideBounds) return { kind: "miss" };
9854
+ if (!scoped.roles) return { kind: "hit", event: summary.event, notice: summary.notice };
9855
+ let best;
9856
+ for (const role of scoped.roles) {
9857
+ const candidate = summary.latestByRole[role];
9858
+ if (candidate && (!best || candidate.seq > best.seq)) best = candidate;
9859
+ }
9860
+ return { kind: "hit", event: best, notice: summary.notice };
9861
+ }
9862
+ async function loadHistorySummary(session) {
9863
+ if (!session.loadSummary) return failure("history_unavailable", `Session ${sessionIdentity(session)} has no summary loader`);
9864
+ try {
9865
+ return success(await session.loadSummary());
9866
+ } catch (error) {
9867
+ return unavailableSession(session, error);
9868
+ }
9869
+ }
9714
9870
  async function loadHistoryRepresentative(session) {
9715
9871
  if (session.loadRepresentative) {
9716
9872
  try {
@@ -9739,22 +9895,30 @@ function currentHistory(context2) {
9739
9895
  }
9740
9896
 
9741
9897
  // src/tools/history.ts
9742
- var HistoryReadDataSchema = typebox_exports.Object({
9743
- session: typebox_exports.Optional(typebox_exports.String()),
9744
- notice: typebox_exports.Optional(typebox_exports.String()),
9745
- seq: typebox_exports.Integer({ minimum: 1 }),
9746
- role: HistoryRoleSchema,
9747
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
9748
- ...ToolSummarySchema.properties,
9749
- nested_calls: typebox_exports.Optional(NestedCallSummarySchema),
9750
- ...TextWindowSchema.properties
9751
- }, { additionalProperties: false });
9898
+ var WILDCARD_CONCURRENCY = 12;
9899
+ async function loadOverviewSession(session, scoped) {
9900
+ if (session.loadSummary) {
9901
+ const summary = await loadHistorySummary(session);
9902
+ if (!summary.ok) return void 0;
9903
+ const resolved = resolveSummaryForSelection(summary.data, scoped);
9904
+ if (resolved.kind === "empty") return void 0;
9905
+ if (resolved.kind === "hit") return { event: resolved.event, notice: resolved.notice };
9906
+ if (summary.data.loaded) return summary.data.loaded;
9907
+ } else if (!scoped.roles && !scoped.after && !scoped.before && session.loadRepresentative) {
9908
+ const rep = await loadHistoryRepresentative(session);
9909
+ return rep.ok ? rep.data : void 0;
9910
+ }
9911
+ const loaded = await loadHistorySession(session);
9912
+ return loaded.ok ? loaded.data : void 0;
9913
+ }
9752
9914
  function header(item) {
9753
- return `${item.session === void 0 ? "" : `session ${item.session} | `}seq ${item.seq} | ${item.role}`;
9915
+ const atMs = item.created_at ? Date.parse(item.created_at) : NaN;
9916
+ const at = Number.isFinite(atMs) ? localIso(atMs) : void 0;
9917
+ return [item.session === void 0 ? void 0 : `session ${item.session}`, `seq ${item.seq}`, item.role, ...at === void 0 ? [] : [at]].filter(Boolean).join(" | ");
9754
9918
  }
9755
9919
  function toolHeader(item) {
9756
9920
  if (item.role !== "tool") return void 0;
9757
- const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
9921
+ const parts = [...item.tool ? [`tool ${item.tool}`] : [], `status ${item.tool_status}`];
9758
9922
  if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
9759
9923
  if (item.nested_calls) {
9760
9924
  parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
@@ -9763,163 +9927,243 @@ function toolHeader(item) {
9763
9927
  }
9764
9928
  function renderPageItem(item) {
9765
9929
  const tool = toolHeader(item);
9766
- const lines = [header(item) + (item.context ? " | search context" : ""), ...tool ? [tool] : []];
9767
- if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
9768
- lines.push(item.content);
9930
+ const offset = (item.offset_chars ?? 0) > 0 ? ` | offset_chars ${item.offset_chars}` : "";
9931
+ const lines = [header({ seq: item.seq, role: item.role, created_at: item.created_at }) + offset + (item.context ? " | search context" : ""), ...tool ? [tool] : []];
9932
+ lines.push(item.truncated ? item.content ? `${item.content} [truncated]` : "[truncated]" : item.content);
9769
9933
  return lines.join("\n");
9770
9934
  }
9771
- function renderFoldedRow(row) {
9935
+ function renderFoldedRow(row, session) {
9772
9936
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
9773
- const identity2 = row.session === void 0 ? {} : { session: row.session };
9774
- const expand = `
9775
- \u2192 expand: ${JSON.stringify({ ...identity2, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
9776
- return `${row.session === void 0 ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
9777
- }
9778
- function renderPage(page) {
9779
- if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
9780
- 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");
9781
- if (isMultiPage(page)) {
9782
- const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9783
- return (page.notice ?? "") + body + (directions ? `
9784
-
9785
- \u2192 more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
9786
- }
9787
- const hits = page.items.filter((item) => !item.context);
9788
- const first = hits[0];
9789
- const last = hits.at(-1);
9937
+ const expand = JSON.stringify({ session, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] });
9938
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}
9939
+ \u2192 expand: ${expand}`;
9940
+ }
9941
+ var sessionBanner = (session) => session === void 0 ? "" : `=== session ${session} ===
9942
+ `;
9943
+ var EMPTY_PAGE = "No events match these filters.";
9944
+ function renderTimelinePage(page) {
9945
+ const { session } = page.paging;
9946
+ const body = [...page.items.flatMap((item) => [...item.folded_before ? [renderFoldedRow(item.folded_before, session)] : [], renderPageItem(item)]), ...page.folded_after ? [renderFoldedRow(page.folded_after, session)] : []].join("\n\n");
9790
9947
  const cursors = [
9791
- page.has_older ? `\u2192 older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
9792
- page.has_newer ? `\u2192 newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : ""
9793
- ].filter((line) => line !== "");
9794
- return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}
9948
+ page.has_older ? `\u2192 older: ${JSON.stringify({ ...page.paging, before: page.items[0].seq })}` : "",
9949
+ page.has_newer ? `\u2192 newer: ${JSON.stringify({ ...page.paging, after: page.items.at(-1).seq })}` : ""
9950
+ ].filter(Boolean);
9951
+ return (page.notice ?? "") + sessionBanner(session) + (body || EMPTY_PAGE) + (cursors.length ? `
9952
+
9953
+ ${cursors.join(" | ")}` : "");
9954
+ }
9955
+ function renderCollectionPage(page, narrow) {
9956
+ const sessions = new Map(page.items.filter((item) => !item.context).map((item) => [item.session, []]));
9957
+ for (const item of page.items) sessions.get(item.session).push(item);
9958
+ const body = [...sessions].map(([session, items]) => sessionBanner(session) + items.sort((a, b) => a.seq - b.seq).map(renderPageItem).join("\n\n")).join("\n\n");
9959
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9960
+ return (page.notice ?? "") + (body || sessionBanner(page.session) + EMPTY_PAGE) + (directions ? `
9795
9961
 
9796
- ${cursors.join(" | ")}`);
9962
+ \u2192 more ${directions} results: ${narrow}` : "");
9797
9963
  }
9964
+ var renderOverviewPage = (page) => renderCollectionPage(page, "narrow with since/until, roles or the session pattern");
9965
+ var renderSearchPage = (page) => renderCollectionPage(page, "narrow with since/until, query, roles or the session pattern");
9798
9966
  function renderRead(data) {
9799
9967
  const tool = toolHeader(data);
9800
- 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 })})`;
9968
+ const neighborhood = `\u2192 history_list: ${JSON.stringify({ session: data.session, after: Math.max(0, data.seq - 10), before: data.seq + 10 })}`;
9801
9969
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9802
9970
  }
9803
9971
  var plainText = (text) => text;
9804
- function pageOutcome(result) {
9972
+ function pageOutcome(result, narrow) {
9805
9973
  if (!("pageTooLarge" in result)) return result;
9806
- const { count, multi } = result.pageTooLarge;
9807
- 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";
9808
- 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}.`);
9974
+ return failure("page_too_large", `These events exceed the ${TOOL_OUTPUT_LIMIT} limit; ${narrow}, or use history_read for one event.`);
9975
+ }
9976
+ async function loadNamedSession(context2, selector) {
9977
+ if (!("corpus" in context2)) return failure("unknown_session", "Other sessions are unavailable here.");
9978
+ const target = await resolveSession(context2.corpus, selector);
9979
+ if (!target.ok) return target;
9980
+ const loaded = await loadHistorySession(target.data);
9981
+ return loaded.ok ? success({ ...loaded.data, session: sessionIdentity(target.data) }) : loaded;
9982
+ }
9983
+ async function loadTimeline(context2, session, tool) {
9984
+ if (session === void 0) return success({ projection: await currentHistory(context2) });
9985
+ const selector = parseSessionSelector(session);
9986
+ if (!selector.ok) return selector;
9987
+ if (selector.data.wildcard) return failure("invalid_session", `${tool} needs one session ID or prefix. Use history_list or history_search for wildcards.`);
9988
+ return loadNamedSession(context2, selector.data);
9989
+ }
9990
+ var sessionParameter = (description) => typebox_exports.Optional(typebox_exports.String({ minLength: 1, description }));
9991
+ var limitParameter = (description) => typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description }));
9992
+ var previewParameter = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "Maximum characters per preview." }));
9993
+ var seqBound = (description) => typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description }));
9994
+ var timeBound = (description) => typebox_exports.Optional(typebox_exports.String({ description: `${description} ISO 8601 (local time if no offset).` }));
9995
+ function parseTimeBounds(params) {
9996
+ const since = params.since === void 0 ? void 0 : parseIsoTimestamp(params.since);
9997
+ const until = params.until === void 0 ? void 0 : parseIsoTimestamp(params.until);
9998
+ if (params.since !== void 0 && since === void 0) return failure("invalid_bounds", `since must be an ISO 8601 time; got ${JSON.stringify(params.since)}.`);
9999
+ if (params.until !== void 0 && until === void 0) return failure("invalid_bounds", `until must be an ISO 8601 time; got ${JSON.stringify(params.until)}.`);
10000
+ return success({ since, until });
9809
10001
  }
9810
- 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.` }));
9811
10002
  var historyListParameters = typebox_exports.Object({
9812
- 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." })),
10003
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`) for one event per session. Omit for current session."),
10004
+ roles: historyRoles(true),
10005
+ after: seqBound("Exclusive seq; page forward (0 starts at the beginning)."),
10006
+ before: seqBound("Exclusive seq; without `after`, takes newest events."),
10007
+ since: timeBound("Exclusive start time; oldest first."),
10008
+ until: timeBound("Exclusive end time; without `since`, newest first."),
10009
+ limit: limitParameter("Events or sessions per page."),
10010
+ max_chars_per_item: previewParameter
10011
+ }, { additionalProperties: false });
10012
+ var historyList = {
10013
+ name: "history_list",
10014
+ label: "Browse history",
10015
+ description: "Browse one session's timeline (oldest to newest), or pass a wildcard `session` to overview matching sessions.",
10016
+ parameters: historyListParameters,
10017
+ async execute(params, context2, wrapText = plainText) {
10018
+ const { after, before, roles, limit, max_chars_per_item } = params;
10019
+ const bounds = parseTimeBounds(params);
10020
+ if (!bounds.ok) return bounds;
10021
+ const { since, until } = bounds.data;
10022
+ const selector = params.session === void 0 ? void 0 : parseSessionSelector(params.session);
10023
+ if (selector && !selector.ok) return selector;
10024
+ if (selector?.ok && selector.data.wildcard) {
10025
+ if (after !== void 0 || before !== void 0) {
10026
+ return failure("invalid_bounds", "after and before are seq numbers for a single session; use since and until with wildcard sessions.");
10027
+ }
10028
+ const wild = selector.data;
10029
+ if (!("corpus" in context2)) return failure("unknown_session", "Other sessions are unavailable here.");
10030
+ const scoped = {
10031
+ after: since === void 0 ? void 0 : { at: since },
10032
+ before: until === void 0 ? void 0 : { at: until },
10033
+ roles,
10034
+ limit
10035
+ };
10036
+ const sessions = (await context2.corpus.sessions(wild.harness)).filter((s) => matchesSession(s, wild));
10037
+ sessions.sort((a, b) => (since !== void 0 ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
10038
+ const targetCount = Math.min(500, Math.max(1, limit ?? 20));
10039
+ const collector = new CorpusCollector(scoped);
10040
+ const notices = [];
10041
+ let qualifying = 0, offset = 0;
10042
+ while (offset < sessions.length && qualifying < targetCount) {
10043
+ const batchSize = Math.min(WILDCARD_CONCURRENCY, targetCount - qualifying, sessions.length - offset);
10044
+ const batch = sessions.slice(offset, offset + batchSize);
10045
+ const loadedBatch = await Promise.all(batch.map((s) => loadOverviewSession(s, scoped)));
10046
+ for (let i = 0; i < batch.length; i++) {
10047
+ const s = batch[i];
10048
+ const item = loadedBatch[i];
10049
+ if (!item) continue;
10050
+ const added = collector.addRepresentative(sessionIdentity(s), item.projection ?? item.event);
10051
+ if (!added) continue;
10052
+ qualifying++;
10053
+ if (item.notice) notices.push(`session ${sessionIdentity(s)}: ${item.notice}`);
10054
+ }
10055
+ offset += batch.length;
10056
+ }
10057
+ const unvisited = offset < sessions.length;
10058
+ const decorateOverview = (page) => ({ ...page, ...notices.length ? { notice: notices.join("") } : {} });
10059
+ const overview = pageOutcome(collector.page((page) => fitsText(wrapText(renderOverviewPage(decorateOverview(page)))), max_chars_per_item ?? HISTORY_PREVIEW_CHARS, unvisited), "narrow with since/until, roles or the session pattern");
10060
+ return overview.ok ? success(decorateOverview(overview.data)) : overview;
10061
+ }
10062
+ const loaded = await loadTimeline(context2, params.session, "history_list");
10063
+ if (!loaded.ok) return loaded;
10064
+ const { projection, session, notice } = loaded.data;
10065
+ const paging = { session, roles, since: params.since, until: params.until, limit, max_chars_per_item };
10066
+ const decorate = (page) => ({ ...page, paging, ...notice === void 0 ? {} : { notice } });
10067
+ const result = pageOutcome(selectPage(projection, {
10068
+ roles,
10069
+ limit,
10070
+ after: after === void 0 ? void 0 : { seq: after },
10071
+ before: before === void 0 ? void 0 : { seq: before },
10072
+ since,
10073
+ until
10074
+ }, (page) => fitsText(wrapText(renderTimelinePage(decorate(page)))), max_chars_per_item ?? HISTORY_PREVIEW_CHARS), "narrow with after/before, since/until or specify roles");
10075
+ return result.ok ? success(decorate(result.data)) : result;
10076
+ },
10077
+ render: (result) => renderOutcome(result, (page) => "paging" in page ? renderTimelinePage(page) : renderOverviewPage(page))
10078
+ };
10079
+ var historySearchParameters = typebox_exports.Object({
10080
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`). Omit for current session."),
10081
+ query: searchQuery("Case-insensitive literal text, or a list (any match)."),
10082
+ since: timeBound("Exclusive start time; oldest matches first."),
10083
+ until: timeBound("Exclusive end time; without `since`, newest matches first."),
9813
10084
  roles: historyRoles(),
9814
- query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
9815
- after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
9816
- before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
9817
- 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." })),
9818
- 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." })),
9819
- 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." }))
10085
+ context: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events shown on each side of a hit." })),
10086
+ limit: limitParameter("Hits per page."),
10087
+ max_chars_per_item: previewParameter
9820
10088
  }, { additionalProperties: false });
9821
- var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
9822
- function parseBound(name, value) {
9823
- if (value === void 0) return success(void 0);
9824
- if (typeof value === "number" || /^\d+$/.test(value)) {
9825
- const seq = Number(value);
9826
- if (Number.isSafeInteger(seq) && seq >= 0) return success({ seq });
9827
- } else if (typeof value === "string") {
9828
- const match = ISO_8601.exec(value);
9829
- const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
9830
- if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10))) return success({ at });
9831
- }
9832
- return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
9833
- }
9834
- function parseSelection(params) {
9835
- const after = parseBound("after", params.after);
9836
- if (!after.ok) return after;
9837
- const before = parseBound("before", params.before);
9838
- if (!before.ok) return before;
10089
+ function searchSelection(params) {
10090
+ const bounds = parseTimeBounds(params);
10091
+ if (!bounds.ok) return bounds;
10092
+ const { since, until } = bounds.data;
9839
10093
  try {
9840
10094
  const query = searchQueries(params.query);
9841
- if (!query.length && params.context !== void 0) return failure("invalid_params", "`context` requires a non-empty `query`.");
9842
- return success({ after: after.data, before: before.data, query: query.length ? query : void 0, roles: params.roles, context: params.context, limit: params.limit });
10095
+ return success({ after: since === void 0 ? void 0 : { at: since }, before: until === void 0 ? void 0 : { at: until }, query, roles: params.roles, context: params.context, limit: params.limit });
9843
10096
  } catch (error) {
9844
10097
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9845
10098
  throw error;
9846
10099
  }
9847
10100
  }
9848
- var historyList = {
9849
- name: "history_list",
9850
- label: "History list items",
9851
- description: "Flip back through the record, a page at a time. Another session: its ID. `*` pulls every recent session off the shelf; add `query` to search them.",
9852
- parameters: historyListParameters,
9853
- outputSchema: resultSchema(HistoryPageSchema),
10101
+ var historySearch = {
10102
+ name: "history_search",
10103
+ label: "Search history",
10104
+ description: "Search passages by literal text in one or more sessions, including tool arguments and output.",
10105
+ parameters: historySearchParameters,
9854
10106
  async execute(params, context2, wrapText = plainText) {
9855
- const selection = parseSelection(params);
10107
+ const selection = searchSelection(params);
9856
10108
  if (!selection.ok) return selection;
9857
10109
  const scoped = selection.data;
9858
- const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
9859
- const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
9860
- if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), scoped, fits, maxChars));
9861
- const selector = parseSessionSelector(params.session);
9862
- if (!selector.ok) return selector;
9863
- const corpus = "corpus" in context2 ? context2.corpus : void 0;
9864
- if (selector.data.wildcard) {
9865
- const { after, before, query, roles } = scoped;
9866
- if (after && "seq" in after || before && "seq" in before) return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
9867
- if (corpus === void 0) return failure("unknown_session", "This host supplied no cross-session history corpus.");
9868
- const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
9869
- if (!query) sessions.sort((a, b) => (after ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9870
- const representative = !query && !roles && !after && !before;
9871
- const collector = new CorpusCollector(scoped);
9872
- let qualifying = 0;
9873
- const notices = [];
9874
- let unvisited = false;
9875
- for (const [index, session] of sessions.entries()) {
9876
- const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
9877
- if (!result3.ok || !result3.data) continue;
9878
- const added = "projection" in result3.data ? collector.add(sessionIdentity(session), result3.data.projection) : collector.addRepresentative(sessionIdentity(session), result3.data.event);
9879
- if (!added) continue;
9880
- qualifying++;
9881
- if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
9882
- if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
9883
- unvisited = index + 1 < sessions.length;
9884
- break;
10110
+ const { after, before, query } = scoped;
10111
+ const collector = new CorpusCollector(scoped);
10112
+ const notices = [];
10113
+ let session;
10114
+ if (params.session === void 0) collector.addMatches("", await currentHistory(context2));
10115
+ else {
10116
+ const selector = parseSessionSelector(params.session);
10117
+ if (!selector.ok) return selector;
10118
+ const corpus = "corpus" in context2 ? context2.corpus : void 0;
10119
+ if (!selector.data.wildcard) {
10120
+ const loaded = await loadNamedSession(context2, selector.data);
10121
+ if (!loaded.ok) return loaded;
10122
+ session = loaded.data.session;
10123
+ collector.addMatches(session, loaded.data.projection);
10124
+ if (loaded.data.notice) notices.push(loaded.data.notice);
10125
+ } else {
10126
+ if (!corpus) return failure("unknown_session", "Other sessions are unavailable here.");
10127
+ if (query && query.length > 0) {
10128
+ const sessions = (await corpus.sessions(selector.data.harness)).filter((session2) => matchesSession(session2, selector.data));
10129
+ const hasTimeBounds = after !== void 0 || before !== void 0;
10130
+ const noticesByIndex = new Array(sessions.length);
10131
+ let next = 0;
10132
+ const workers = Math.min(WILDCARD_CONCURRENCY, sessions.length);
10133
+ await Promise.all(Array.from({ length: workers }, async () => {
10134
+ while (next < sessions.length) {
10135
+ const index = next++;
10136
+ const session2 = sessions[index];
10137
+ if (hasTimeBounds && session2.peekSummary) {
10138
+ const summary = await session2.peekSummary();
10139
+ if (summary && resolveSummaryForSelection(summary, scoped).kind === "empty") continue;
10140
+ }
10141
+ const result2 = await loadHistorySession(session2, query);
10142
+ if (!result2.ok || !result2.data) continue;
10143
+ collector.addMatches(sessionIdentity(session2), result2.data.projection);
10144
+ if (result2.data.notice) noticesByIndex[index] = `session ${sessionIdentity(session2)}: ${result2.data.notice}`;
10145
+ }
10146
+ }));
10147
+ for (const entry of noticesByIndex) if (entry) notices.push(entry);
9885
10148
  }
9886
10149
  }
9887
- const notice2 = notices.length ? { notice: notices.join("") } : {};
9888
- const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
9889
- return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
9890
10150
  }
9891
- const target = await resolveSession(corpus, selector.data);
9892
- if (!target.ok) return target;
9893
- const loaded = await loadHistorySession(target.data);
9894
- if (!loaded.ok) return loaded;
9895
- const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
9896
- const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
9897
- return result.ok ? success({ ...result.data, ...notice }) : result;
10151
+ const decorate = (page) => ({ ...page, ...session === void 0 ? {} : { session }, ...notices.length ? { notice: notices.join("") } : {} });
10152
+ const result = pageOutcome(collector.page((page) => fitsText(wrapText(renderSearchPage(decorate(page)))), params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS), "narrow with since/until, query, roles or the session pattern");
10153
+ return result.ok ? success(decorate(result.data)) : result;
9898
10154
  },
9899
- render: (result) => renderOutcome(result, renderPage)
10155
+ render: (result) => renderOutcome(result, renderSearchPage)
9900
10156
  };
9901
- var historyReadParameters = typebox_exports.Object({ session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: typebox_exports.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
10157
+ var historyReadParameters = typebox_exports.Object({ session: sessionParameter("Session ID or prefix. Omit for current session."), seq: typebox_exports.Integer({ minimum: 1, description: "Event seq to read." }), ...TextWindowRequestSchema }, { additionalProperties: false });
9902
10158
  var historyRead = {
9903
10159
  name: "history_read",
9904
- label: "History read item",
9905
- description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
10160
+ label: "Read history event",
10161
+ description: "Read one history event, including tool arguments, output, and nested calls.",
9906
10162
  parameters: historyReadParameters,
9907
- outputSchema: resultSchema(HistoryReadDataSchema),
9908
10163
  async execute(params, context2, wrapText = plainText) {
9909
- let projection;
9910
- let identity2 = {};
9911
- if (params.session === void 0) projection = await currentHistory(context2);
9912
- else {
9913
- const selector = parseSessionSelector(params.session);
9914
- if (!selector.ok) return selector;
9915
- if (selector.data.wildcard) return failure("invalid_session", "`history_read` reads one session; pass a specific `session` ID, not a wildcard.");
9916
- const target = await resolveSession("corpus" in context2 ? context2.corpus : void 0, selector.data);
9917
- if (!target.ok) return target;
9918
- const loaded = await loadHistorySession(target.data);
9919
- if (!loaded.ok) return loaded;
9920
- projection = loaded.data.projection;
9921
- identity2 = { session: sessionIdentity(target.data), ...loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice } };
9922
- }
10164
+ const loaded = await loadTimeline(context2, params.session, "history_read");
10165
+ if (!loaded.ok) return loaded;
10166
+ const { projection, ...identity2 } = loaded.data;
9923
10167
  if (params.seq > projection.highestSeq) {
9924
10168
  return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
9925
10169
  }
@@ -9940,7 +10184,7 @@ var historyRead = {
9940
10184
  return readTextWindow(
9941
10185
  document,
9942
10186
  params.offset_chars,
9943
- params.max_chars,
10187
+ params.max_chars ?? HISTORY_READ_WINDOW_CHARS,
9944
10188
  (window) => ({
9945
10189
  ...identity2,
9946
10190
  seq: item.seq,
@@ -9957,11 +10201,15 @@ var historyRead = {
9957
10201
  };
9958
10202
 
9959
10203
  // src/history/local.ts
9960
- import { readdir as readdir4, readFile as readFile4, stat as stat5 } from "node:fs/promises";
10204
+ import { readdir as readdir5, stat as stat6 } from "node:fs/promises";
9961
10205
  import { homedir as homedir2 } from "node:os";
9962
10206
  import { join as join6 } from "node:path";
9963
10207
 
9964
10208
  // src/history/pi.ts
10209
+ import { createReadStream } from "node:fs";
10210
+ import { readFile as readFile2, stat } from "node:fs/promises";
10211
+ import { StringDecoder } from "node:string_decoder";
10212
+ var STREAM_FILE_BYTES = 64 * 1024 * 1024;
9965
10213
  function mapRole(role) {
9966
10214
  if (role === "user" || role === "assistant") return role;
9967
10215
  if (role === "toolResult" || role === "bashExecution") return "tool";
@@ -10081,54 +10329,125 @@ function piHistoryFromEntries(sessionId, entries, branch) {
10081
10329
  }
10082
10330
  return projectHistory(rawWindows, highestSeq, branchSeqs);
10083
10331
  }
10084
- function piHistoryFromJsonl(text, sessionId) {
10085
- const lines = text.split("\n");
10332
+ function slimMessage(message) {
10333
+ let content = message.content;
10334
+ if (Array.isArray(content)) {
10335
+ content = content.filter((part) => typeof part === "object" && part !== null && (part.type === "text" || part.type === "toolCall"));
10336
+ }
10337
+ return {
10338
+ role: message.role,
10339
+ ...content === void 0 ? {} : { content },
10340
+ ...message.output === void 0 ? {} : { output: message.output },
10341
+ ...message.summary === void 0 ? {} : { summary: message.summary },
10342
+ ...message.command === void 0 ? {} : { command: message.command },
10343
+ ...message.cancelled === void 0 ? {} : { cancelled: message.cancelled },
10344
+ ...message.exitCode === void 0 ? {} : { exitCode: message.exitCode },
10345
+ ...message.truncated === void 0 ? {} : { truncated: message.truncated },
10346
+ ...message.fullOutputPath === void 0 ? {} : { fullOutputPath: message.fullOutputPath },
10347
+ ...message.toolName === void 0 ? {} : { toolName: message.toolName },
10348
+ ...message.toolCallId === void 0 ? {} : { toolCallId: message.toolCallId },
10349
+ ...message.isError === void 0 ? {} : { isError: message.isError },
10350
+ ...message.nestedCalls === void 0 ? {} : { nestedCalls: message.nestedCalls }
10351
+ };
10352
+ }
10353
+ function slimEntry(row) {
10354
+ return {
10355
+ type: row.type,
10356
+ id: row.id,
10357
+ parentId: row.parentId,
10358
+ ...row.timestamp === void 0 ? {} : { timestamp: row.timestamp },
10359
+ ...row.summary === void 0 ? {} : { summary: row.summary },
10360
+ ...row.customType === void 0 ? {} : { customType: row.customType },
10361
+ ...row.customType === "notesoup/reset-marker" && row.data !== void 0 ? { data: row.data } : {},
10362
+ ...row.type === "custom_message" && row.content !== void 0 ? { content: contentText(row.content) } : {},
10363
+ ...row.type === "message" && row.message ? { message: slimMessage(row.message) } : {}
10364
+ };
10365
+ }
10366
+ function createPiJsonlParser(sessionId) {
10086
10367
  const entries = [];
10087
10368
  let header2 = false;
10088
- for (let index = 0; index < lines.length; index++) {
10089
- const line = lines[index];
10090
- if (line.trim() === "") continue;
10091
- let row;
10092
- try {
10093
- row = JSON.parse(line);
10094
- } catch {
10095
- if (index === lines.length - 1 && !text.endsWith("\n")) break;
10096
- throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
10369
+ return {
10370
+ push(line, lineNumber, allowIncompleteTail) {
10371
+ if (line.trim() === "") return;
10372
+ let row;
10373
+ try {
10374
+ row = JSON.parse(line);
10375
+ } catch {
10376
+ if (allowIncompleteTail) return;
10377
+ throw new Error(`malformed Pi transcript JSON at line ${lineNumber}`);
10378
+ }
10379
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
10380
+ if (!header2) {
10381
+ if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
10382
+ header2 = true;
10383
+ return;
10384
+ }
10385
+ if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
10386
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
10387
+ entries.push(slimEntry(row));
10388
+ },
10389
+ finish() {
10390
+ if (!header2) throw new Error("Pi transcript has no session header");
10391
+ const byId = /* @__PURE__ */ new Map();
10392
+ for (const entry of entries) {
10393
+ if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
10394
+ byId.set(entry.id, entry);
10395
+ }
10396
+ const branch = [], seen = /* @__PURE__ */ new Set();
10397
+ let cursor = entries.at(-1);
10398
+ while (cursor) {
10399
+ if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
10400
+ seen.add(cursor.id);
10401
+ branch.push(cursor);
10402
+ if (cursor.parentId === null) break;
10403
+ const parent2 = byId.get(cursor.parentId);
10404
+ if (!parent2) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
10405
+ cursor = parent2;
10406
+ }
10407
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
10097
10408
  }
10098
- if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
10099
- if (!header2) {
10100
- if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
10101
- header2 = true;
10102
- continue;
10409
+ };
10410
+ }
10411
+ function piHistoryFromJsonl(text, sessionId) {
10412
+ const lines = text.split("\n");
10413
+ const parser = createPiJsonlParser(sessionId);
10414
+ for (let index = 0; index < lines.length; index++) {
10415
+ parser.push(lines[index], index + 1, index === lines.length - 1 && !text.endsWith("\n"));
10416
+ }
10417
+ return parser.finish();
10418
+ }
10419
+ async function piHistoryFromFile(path, sessionId, sizeHint) {
10420
+ const size = sizeHint ?? (await stat(path)).size;
10421
+ if (size < STREAM_FILE_BYTES) return piHistoryFromJsonl(await readFile2(path, "utf8"), sessionId);
10422
+ const parser = createPiJsonlParser(sessionId);
10423
+ const decoder = new StringDecoder("utf8");
10424
+ let remainder = "";
10425
+ let lineNumber = 0;
10426
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
10427
+ const text = remainder + decoder.write(chunk);
10428
+ let start = 0;
10429
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
10430
+ lineNumber++;
10431
+ parser.push(text.slice(start, nl), lineNumber, false);
10432
+ start = nl + 1;
10103
10433
  }
10104
- if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
10105
- if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
10106
- entries.push(row);
10107
- }
10108
- if (!header2) throw new Error("Pi transcript has no session header");
10109
- const byId = /* @__PURE__ */ new Map();
10110
- for (const entry of entries) {
10111
- if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
10112
- byId.set(entry.id, entry);
10434
+ remainder = text.slice(start);
10113
10435
  }
10114
- const branch = [], seen = /* @__PURE__ */ new Set();
10115
- let cursor = entries.at(-1);
10116
- while (cursor) {
10117
- if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
10118
- seen.add(cursor.id);
10119
- branch.push(cursor);
10120
- if (cursor.parentId === null) break;
10121
- const parent2 = byId.get(cursor.parentId);
10122
- if (!parent2) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
10123
- cursor = parent2;
10436
+ remainder += decoder.end();
10437
+ if (remainder.length > 0) {
10438
+ lineNumber++;
10439
+ parser.push(remainder, lineNumber, true);
10124
10440
  }
10125
- return piHistoryFromEntries(sessionId, entries, branch.reverse());
10441
+ return parser.finish();
10126
10442
  }
10127
10443
 
10128
10444
  // src/history/claude.ts
10129
- import { readFile as readFile2, stat } from "node:fs/promises";
10445
+ import { createReadStream as createReadStream2 } from "node:fs";
10446
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
10447
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
10130
10448
  import { setTimeout as sleep } from "node:timers/promises";
10131
10449
  import { isDeepStrictEqual } from "node:util";
10450
+ var STREAM_FILE_BYTES2 = 64 * 1024 * 1024;
10132
10451
  var UnpersistedClaudeHead = class extends Error {
10133
10452
  constructor() {
10134
10453
  super("Claude history active head is not persisted yet; retry after the transcript write");
@@ -10388,13 +10707,49 @@ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10388
10707
  const rows = rowsOf(text);
10389
10708
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10390
10709
  }
10710
+ async function offlineClaudeHistoryFromFile(path, sessionId, sizeHint) {
10711
+ const size = sizeHint ?? (await stat2(path)).size;
10712
+ if (size < STREAM_FILE_BYTES2) return offlineClaudeHistoryFromJsonl(await readFile3(path, "utf8"), sessionId);
10713
+ const rows = [];
10714
+ const decoder = new StringDecoder2("utf8");
10715
+ let remainder = "";
10716
+ let lineNumber = 0;
10717
+ const parseLine = (line, allowIncompleteTail) => {
10718
+ if (line.trim() === "") return;
10719
+ let value;
10720
+ try {
10721
+ value = JSON.parse(line);
10722
+ } catch {
10723
+ if (allowIncompleteTail) return;
10724
+ throw new Error(`malformed Claude transcript JSON at line ${lineNumber}`);
10725
+ }
10726
+ if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${lineNumber}`);
10727
+ if (MESSAGE_TYPES.has(value.type)) rows.push(value);
10728
+ };
10729
+ for await (const chunk of createReadStream2(path, { highWaterMark: 1024 * 1024 })) {
10730
+ const text = remainder + decoder.write(chunk);
10731
+ let start = 0;
10732
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
10733
+ lineNumber++;
10734
+ parseLine(text.slice(start, nl), false);
10735
+ start = nl + 1;
10736
+ }
10737
+ remainder = text.slice(start);
10738
+ }
10739
+ remainder += decoder.end();
10740
+ if (remainder.length > 0) {
10741
+ lineNumber++;
10742
+ parseLine(remainder, true);
10743
+ }
10744
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10745
+ }
10391
10746
  async function readClaudeHistory(source, { waitForHead = false } = {}) {
10392
10747
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10393
10748
  const snapshot2 = { ...source };
10394
- const read = async () => claudeHistoryFromJsonl(await readFile2(snapshot2.transcriptPath, "utf8"), snapshot2);
10749
+ const read = async () => claudeHistoryFromJsonl(await readFile3(snapshot2.transcriptPath, "utf8"), snapshot2);
10395
10750
  if (!waitForHead || !snapshot2.headUuid) return read();
10396
10751
  const revision = async () => {
10397
- const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot2.transcriptPath, { bigint: true });
10752
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat2(snapshot2.transcriptPath, { bigint: true });
10398
10753
  return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
10399
10754
  };
10400
10755
  let seen = await revision();
@@ -10418,14 +10773,14 @@ async function readClaudeHistory(source, { waitForHead = false } = {}) {
10418
10773
  }
10419
10774
 
10420
10775
  // src/history/codex-transcript.ts
10421
- import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
10776
+ import { readFile as readFile4, readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
10422
10777
  import { basename as basename2, dirname as dirname3, join as join4, relative, sep as sep2 } from "node:path";
10423
10778
  import * as zlib from "node:zlib";
10424
10779
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
10425
10780
  var UUID_RE = new RegExp(`^${UUID}$`);
10426
10781
  var FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
10427
10782
  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"]);
10428
- 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"]);
10783
+ 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", "additional_tools"]);
10429
10784
  var CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
10430
10785
  var MAX_SEGMENTS = 64;
10431
10786
  var MAX_DIRECTORY_ENTRIES = 1e5;
@@ -10438,8 +10793,10 @@ function nativeString(value, field) {
10438
10793
  return value;
10439
10794
  }
10440
10795
  function responseShape(value) {
10441
- const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
10796
+ const payload = nativeObject(value, "response_item");
10797
+ const type = nativeString(payload.type, "response_item.type");
10442
10798
  if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
10799
+ if (type === "additional_tools" && (payload.role !== "developer" || !Array.isArray(payload.tools))) throw new Error("Invalid Codex additional_tools catalog");
10443
10800
  }
10444
10801
  function id(value, field) {
10445
10802
  const result = nativeString(value, field);
@@ -10461,7 +10818,7 @@ function initialWindow(meta) {
10461
10818
  function checkMeta(meta) {
10462
10819
  id(meta.id, "session_meta.id");
10463
10820
  if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
10464
- if (meta.cli_version !== "0.160.1") throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
10821
+ nativeString(meta.cli_version, "session_meta.cli_version");
10465
10822
  nativeString(meta.cwd, "session_meta.cwd");
10466
10823
  if (meta.history_mode !== void 0 && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
10467
10824
  for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
@@ -10580,9 +10937,9 @@ function createCodexTranscriptReader() {
10580
10937
  let pending = cache.get(canonical);
10581
10938
  if (!pending) {
10582
10939
  pending = (async () => {
10583
- const info = await stat2(canonical);
10940
+ const info = await stat3(canonical);
10584
10941
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10585
- const stored = await readFile3(canonical);
10942
+ const stored = await readFile4(canonical);
10586
10943
  if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
10587
10944
  if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
10588
10945
  const bytes2 = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
@@ -10822,6 +11179,7 @@ async function readCodexHistory(source, readBytes) {
10822
11179
  if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
10823
11180
  break;
10824
11181
  case "response_item": {
11182
+ if (p.type === "additional_tools") break;
10825
11183
  item = response(record, facts);
10826
11184
  if (p.id != null) responseIdsSeen.add(callKey(record, nativeString(p.id, "response item id")));
10827
11185
  if (item.role === "tool_call" && item.toolCallId) {
@@ -10883,10 +11241,10 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10883
11241
  }
10884
11242
 
10885
11243
  // src/history/prefilter.ts
10886
- import { createReadStream } from "node:fs";
10887
- import { stat as stat3 } from "node:fs/promises";
11244
+ import { createReadStream as createReadStream3 } from "node:fs";
11245
+ import { stat as stat4 } from "node:fs/promises";
10888
11246
  import { pipeline } from "node:stream/promises";
10889
- import { StringDecoder } from "node:string_decoder";
11247
+ import { StringDecoder as StringDecoder3 } from "node:string_decoder";
10890
11248
  import * as zlib2 from "node:zlib";
10891
11249
  var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10892
11250
  copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
@@ -10895,6 +11253,57 @@ var PRESENTATION = `Codex unknown arguments not recorded output nested calls com
10895
11253
  FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
10896
11254
  the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
10897
11255
  var HISTORY_BASE = '"history_base"';
11256
+ var STREAM_HIGH_WATER_MARK = 256 * 1024;
11257
+ function isHex(code) {
11258
+ return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
11259
+ }
11260
+ function decodeEscapes(source, final) {
11261
+ const len = source.length;
11262
+ let pending = "";
11263
+ let limit = len;
11264
+ if (!final && len > 0) {
11265
+ let end = len;
11266
+ let hexCount = 0;
11267
+ while (end > 0 && hexCount < 3 && isHex(source.charCodeAt(end - 1))) {
11268
+ end--;
11269
+ hexCount++;
11270
+ }
11271
+ if (end >= 2 && source.charCodeAt(end - 1) === 117 && source.charCodeAt(end - 2) === 92) {
11272
+ let slashStart = end - 2;
11273
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11274
+ pending = `\\u${source.slice(end, len)}`;
11275
+ limit = slashStart;
11276
+ } else if (source.charCodeAt(len - 1) === 92) {
11277
+ let slashStart = len - 1;
11278
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11279
+ pending = "\\";
11280
+ limit = slashStart;
11281
+ }
11282
+ }
11283
+ if (limit < 6) {
11284
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
11285
+ }
11286
+ let pos = source.indexOf("\\u");
11287
+ if (pos < 0 || pos >= limit) {
11288
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
11289
+ }
11290
+ let out = "";
11291
+ let cursor = 0;
11292
+ while (pos >= 0 && pos < limit) {
11293
+ if (pos + 6 <= limit && isHex(source.charCodeAt(pos + 2)) && isHex(source.charCodeAt(pos + 3)) && isHex(source.charCodeAt(pos + 4)) && isHex(source.charCodeAt(pos + 5))) {
11294
+ let slashStart = pos;
11295
+ while (slashStart > cursor && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11296
+ if (slashStart > cursor) out += source.slice(cursor, slashStart);
11297
+ out += String.fromCharCode(Number.parseInt(source.slice(pos + 2, pos + 6), 16));
11298
+ cursor = pos + 6;
11299
+ pos = source.indexOf("\\u", cursor);
11300
+ } else {
11301
+ pos = source.indexOf("\\u", pos + 2);
11302
+ }
11303
+ }
11304
+ if (cursor < limit) out += source.slice(cursor, limit);
11305
+ return { decoded: out, pending };
11306
+ }
10898
11307
  function createHistoryPrefilter(queries) {
10899
11308
  let overlap = HISTORY_BASE.length;
10900
11309
  const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
@@ -10906,23 +11315,20 @@ function createHistoryPrefilter(queries) {
10906
11315
  }));
10907
11316
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10908
11317
  return async (chunks, codex = false, stopOnHit = false) => {
10909
- const decoder = new StringDecoder("utf8");
11318
+ const decoder = new StringDecoder3("utf8");
10910
11319
  const seen = alternatives.map((tokens) => tokens.map(() => false));
10911
11320
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
10912
- const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
10913
11321
  const scan = (chunk, final = false) => {
10914
- const raw = rawTail + chunk, source = pending + chunk;
10915
- const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
10916
- pending = "";
10917
- const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
10918
- if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
10919
- const literal = hex === void 0 ? "\\" : `\\u${hex}`;
10920
- if (!final && offset + match.length === source.length) {
10921
- pending = literal;
10922
- return "";
10923
- }
10924
- return literal;
10925
- }) : chunk;
11322
+ const raw = rawTail + chunk;
11323
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || !final && chunk.endsWith("\\");
11324
+ let decoded = chunk;
11325
+ if (needsNormalization) {
11326
+ const result = decodeEscapes(pending + chunk, final);
11327
+ decoded = result.decoded;
11328
+ pending = result.pending;
11329
+ } else {
11330
+ pending = "";
11331
+ }
10926
11332
  const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
10927
11333
  if (codex && raw.includes(HISTORY_BASE)) possible = true;
10928
11334
  else possible = alternatives.some((tokens, index) => {
@@ -10942,12 +11348,12 @@ function createHistoryPrefilter(queries) {
10942
11348
  };
10943
11349
  }
10944
11350
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10945
- if (!codex) return prefilter(createReadStream(path), false, true);
10946
- const info = await stat3(path);
11351
+ if (!codex) return prefilter(createReadStream3(path, { highWaterMark: STREAM_HIGH_WATER_MARK }), false, true);
11352
+ const info = await stat4(path);
10947
11353
  if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10948
11354
  const compressed = path.endsWith(".jsonl.zst");
10949
11355
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10950
- const input = createReadStream(path);
11356
+ const input = createReadStream3(path, { highWaterMark: STREAM_HIGH_WATER_MARK });
10951
11357
  const consume = async (chunks) => {
10952
11358
  let size = 0;
10953
11359
  async function* bounded() {
@@ -10964,11 +11370,16 @@ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = co
10964
11370
 
10965
11371
  // src/history/summary-cache.ts
10966
11372
  import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10967
- import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
11373
+ import { mkdir as mkdir2, open, readdir as readdir4, realpath as realpath3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10968
11374
  import { homedir } from "node:os";
10969
11375
  import { join as join5 } from "node:path";
10970
- var VERSION = "strict-representative-v1";
11376
+ var VERSION = "strict-summary-v3";
11377
+ var VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
10971
11378
  var MAX_ENTRY_BYTES = 8 * 1024 * 1024;
11379
+ var HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1e3;
11380
+ var SWEEP_INTERVAL_MS = 10 * 60 * 1e3;
11381
+ var TMP_TTL_MS = 60 * 60 * 1e3;
11382
+ var lastSweep = /* @__PURE__ */ new Map();
10972
11383
  var FingerprintSchema = typebox_exports.Object({
10973
11384
  path: typebox_exports.String(),
10974
11385
  dev: typebox_exports.String(),
@@ -11000,11 +11411,21 @@ var EventSchema = typebox_exports.Object({
11000
11411
  }, { additionalProperties: false })) }, { additionalProperties: false }))
11001
11412
  }, { additionalProperties: false }))
11002
11413
  }, { additionalProperties: false });
11414
+ var LatestByRoleSchema = typebox_exports.Object({
11415
+ user: typebox_exports.Optional(EventSchema),
11416
+ assistant: typebox_exports.Optional(EventSchema),
11417
+ tool: typebox_exports.Optional(EventSchema),
11418
+ context: typebox_exports.Optional(EventSchema)
11419
+ }, { additionalProperties: false });
11003
11420
  var EntrySchema = typebox_exports.Object({
11004
11421
  version: typebox_exports.Literal(VERSION),
11005
11422
  path: typebox_exports.String(),
11006
11423
  session: typebox_exports.String(),
11007
11424
  event: typebox_exports.Union([EventSchema, typebox_exports.Null()]),
11425
+ latestByRole: LatestByRoleSchema,
11426
+ minCreatedAt: typebox_exports.Union([typebox_exports.Number(), typebox_exports.Null()]),
11427
+ maxCreatedAt: typebox_exports.Union([typebox_exports.Number(), typebox_exports.Null()]),
11428
+ hasUntimed: typebox_exports.Boolean(),
11008
11429
  notice: typebox_exports.Optional(typebox_exports.String()),
11009
11430
  fingerprints: typebox_exports.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
11010
11431
  lineageSources: typebox_exports.Array(typebox_exports.Object({ home: typebox_exports.String(), rolloutId: typebox_exports.String(), path: typebox_exports.String() }, { additionalProperties: false }), { maxItems: 63 })
@@ -11013,7 +11434,7 @@ function historySummaryCacheRoot(home = homedir(), env = process.env, platform =
11013
11434
  return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
11014
11435
  }
11015
11436
  async function fingerprint(path) {
11016
- const info = await stat4(path, { bigint: true });
11437
+ const info = await stat5(path, { bigint: true });
11017
11438
  if (!info.isFile()) throw new Error("Not a regular transcript file");
11018
11439
  return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
11019
11440
  }
@@ -11026,20 +11447,84 @@ function completeDependencies(path, harness, sources, lineage) {
11026
11447
  const expected = [path, ...lineage.map((source) => source.path)];
11027
11448
  return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
11028
11449
  }
11029
- async function readEntry(path) {
11450
+ async function readEntry(path, now = Date.now()) {
11030
11451
  const file = await open(path, "r");
11452
+ let expired = false;
11031
11453
  try {
11032
11454
  const info = await file.stat();
11033
11455
  if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return void 0;
11456
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
11457
+ expired = true;
11458
+ return void 0;
11459
+ }
11034
11460
  const buffer = Buffer.alloc(info.size + 1);
11035
11461
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
11036
11462
  if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return void 0;
11037
11463
  return JSON.parse(buffer.toString("utf8", 0, bytesRead));
11038
11464
  } finally {
11039
11465
  await file.close();
11466
+ if (expired) await unlink2(path).catch(() => {
11467
+ });
11468
+ }
11469
+ }
11470
+ async function hasCurrentVersionPrefix(path) {
11471
+ const file = await open(path, "r");
11472
+ try {
11473
+ const buffer = Buffer.alloc(VERSION_PREFIX.length);
11474
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
11475
+ return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
11476
+ } catch {
11477
+ return false;
11478
+ } finally {
11479
+ await file.close();
11480
+ }
11481
+ }
11482
+ async function pruneHistorySummaryCache(cacheRoot, now = Date.now()) {
11483
+ let entries;
11484
+ try {
11485
+ entries = await readdir4(cacheRoot, { withFileTypes: true });
11486
+ } catch {
11487
+ return;
11488
+ }
11489
+ for (const entry of entries) {
11490
+ if (!entry.isFile()) continue;
11491
+ const full = join5(cacheRoot, entry.name);
11492
+ try {
11493
+ const info = await stat5(full);
11494
+ if (entry.name.endsWith(".tmp")) {
11495
+ if (now - info.mtimeMs > TMP_TTL_MS) await unlink2(full).catch(() => {
11496
+ });
11497
+ continue;
11498
+ }
11499
+ if (!entry.name.endsWith(".json")) continue;
11500
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
11501
+ await unlink2(full).catch(() => {
11502
+ });
11503
+ }
11504
+ } catch {
11505
+ }
11040
11506
  }
11041
11507
  }
11042
- async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
11508
+ function maybeSweepCacheRoot(cacheRoot) {
11509
+ const now = Date.now();
11510
+ const previous = lastSweep.get(cacheRoot);
11511
+ if (previous !== void 0 && now - previous < SWEEP_INTERVAL_MS) return;
11512
+ lastSweep.set(cacheRoot, now);
11513
+ void pruneHistorySummaryCache(cacheRoot, now).catch(() => {
11514
+ });
11515
+ }
11516
+ function hydrateEvent(event) {
11517
+ return { ...event, createdAt: event.createdAt };
11518
+ }
11519
+ function hydrateLatestByRole(raw) {
11520
+ const out = {};
11521
+ for (const role of ["user", "assistant", "tool", "context"]) {
11522
+ const ev = raw[role];
11523
+ if (ev) out[role] = hydrateEvent(ev);
11524
+ }
11525
+ return out;
11526
+ }
11527
+ async function lookupCachedSummary(session, transcriptPath, cacheRoot) {
11043
11528
  let canonical, cachePath;
11044
11529
  const identity2 = sessionIdentity(session);
11045
11530
  try {
@@ -11047,10 +11532,30 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11047
11532
  cachePath = join5(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
11048
11533
  const entry = await readEntry(cachePath);
11049
11534
  if (Check2(EntrySchema, entry) && entry.path === canonical && entry.session === identity2 && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources) && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints) && await realpath3(transcriptPath) === canonical) {
11050
- return { event: entry.event === null ? void 0 : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
11535
+ return {
11536
+ canonical,
11537
+ cachePath,
11538
+ summary: {
11539
+ event: entry.event === null ? void 0 : hydrateEvent(entry.event),
11540
+ latestByRole: hydrateLatestByRole(entry.latestByRole),
11541
+ minCreatedAt: entry.minCreatedAt,
11542
+ maxCreatedAt: entry.maxCreatedAt,
11543
+ hasUntimed: entry.hasUntimed,
11544
+ notice: entry.notice
11545
+ }
11546
+ };
11051
11547
  }
11052
11548
  } catch {
11053
11549
  }
11550
+ return { canonical, cachePath };
11551
+ }
11552
+ async function peekCachedSessionSummary(session, transcriptPath, cacheRoot) {
11553
+ return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
11554
+ }
11555
+ async function cachedSessionSummary(session, transcriptPath, cacheRoot, load) {
11556
+ const identity2 = sessionIdentity(session);
11557
+ const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
11558
+ if (summary) return summary;
11054
11559
  const fingerprints = /* @__PURE__ */ new Map();
11055
11560
  let stable = canonical !== void 0;
11056
11561
  const track = async (path) => {
@@ -11062,18 +11567,31 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11062
11567
  };
11063
11568
  if (canonical) await track(canonical);
11064
11569
  const { data, lineageSources = [] } = await load(track);
11065
- const event = sessionRepresentative(data.projection, {});
11066
- const result = { event, notice: data.notice };
11570
+ const computed = summarizeProjection(data.projection);
11571
+ const result = { ...computed, notice: data.notice, loaded: data };
11067
11572
  try {
11068
11573
  const sources = [...fingerprints.values()];
11069
11574
  if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources) || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath3(transcriptPath) !== canonical) return result;
11070
- const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity2, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
11575
+ const entry = JSON.stringify({
11576
+ version: VERSION,
11577
+ path: canonical,
11578
+ session: identity2,
11579
+ event: computed.event ?? null,
11580
+ latestByRole: computed.latestByRole,
11581
+ minCreatedAt: computed.minCreatedAt,
11582
+ maxCreatedAt: computed.maxCreatedAt,
11583
+ hasUntimed: computed.hasUntimed,
11584
+ notice: data.notice,
11585
+ fingerprints: sources,
11586
+ lineageSources
11587
+ });
11071
11588
  if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
11072
11589
  await mkdir2(cacheRoot, { recursive: true, mode: 448 });
11073
11590
  const temporary = `${cachePath}.${randomUUID3()}.tmp`;
11074
11591
  try {
11075
11592
  await writeFile2(temporary, entry, { flag: "wx", mode: 384 });
11076
11593
  await rename2(temporary, cachePath);
11594
+ maybeSweepCacheRoot(cacheRoot);
11077
11595
  } finally {
11078
11596
  await unlink2(temporary).catch(() => {
11079
11597
  });
@@ -11084,6 +11602,21 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11084
11602
  }
11085
11603
 
11086
11604
  // src/history/local.ts
11605
+ var DIR_CONCURRENCY = 32;
11606
+ var STAT_CONCURRENCY = 64;
11607
+ async function mapConcurrent(items, concurrency, fn) {
11608
+ if (items.length === 0) return [];
11609
+ const results = new Array(items.length);
11610
+ let next = 0;
11611
+ const workers = Math.min(concurrency, items.length);
11612
+ await Promise.all(Array.from({ length: workers }, async () => {
11613
+ while (next < items.length) {
11614
+ const index = next++;
11615
+ results[index] = await fn(items[index]);
11616
+ }
11617
+ }));
11618
+ return results;
11619
+ }
11087
11620
  function rootsFor(options) {
11088
11621
  const env = options.env ?? process.env;
11089
11622
  const home = options.home ?? env.HOME ?? homedir2();
@@ -11096,39 +11629,47 @@ function rootsFor(options) {
11096
11629
  async function filesAt(root, depth) {
11097
11630
  let entries;
11098
11631
  try {
11099
- entries = await readdir4(root, { withFileTypes: true });
11632
+ entries = await readdir5(root, { withFileTypes: true });
11100
11633
  } catch (error) {
11101
11634
  if (error.code === "ENOENT") return [];
11102
11635
  throw error;
11103
11636
  }
11104
- const paths = [];
11105
- for (const entry of entries) {
11106
- const path = join6(root, entry.name);
11107
- if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
11108
- else if (entry.isFile() && depth === 0) paths.push(path);
11637
+ if (depth === 0) {
11638
+ const paths = [];
11639
+ for (const entry of entries) if (entry.isFile()) paths.push(join6(root, entry.name));
11640
+ return paths;
11109
11641
  }
11110
- return paths;
11642
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => join6(root, entry.name));
11643
+ const nested = await mapConcurrent(dirs, DIR_CONCURRENCY, (dir) => filesAt(dir, depth - 1));
11644
+ return nested.flat();
11111
11645
  }
11112
11646
  async function localSessions(harness, root, cacheRoot, prefilters) {
11113
11647
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
11114
- const sessions = [];
11648
+ const matched = [];
11115
11649
  for (const path of paths) {
11116
11650
  const name = path.split(/[\\/]/).at(-1);
11117
11651
  const id2 = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1] : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1] : /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
11118
- if (!id2) continue;
11119
- let modifiedAt;
11652
+ if (id2) matched.push({ path, id: id2 });
11653
+ }
11654
+ const statted = await mapConcurrent(matched, STAT_CONCURRENCY, async ({ path, id: id2 }) => {
11120
11655
  try {
11121
- modifiedAt = (await stat5(path)).mtimeMs;
11656
+ const info = await stat6(path);
11657
+ return { path, id: id2, modifiedAt: info.mtimeMs, size: info.size };
11122
11658
  } catch (error) {
11123
- if (error.code === "ENOENT") continue;
11659
+ if (error.code === "ENOENT") return void 0;
11124
11660
  throw error;
11125
11661
  }
11126
- sessions.push({
11662
+ });
11663
+ const sessions = [];
11664
+ for (const entry of statted) {
11665
+ if (!entry) continue;
11666
+ const { path, id: id2, modifiedAt, size } = entry;
11667
+ const session = {
11127
11668
  harness,
11128
11669
  id: id2,
11129
11670
  modifiedAt,
11130
- async loadRepresentative() {
11131
- return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
11671
+ async loadSummary() {
11672
+ return cachedSessionSummary(this, path, cacheRoot, async (track) => {
11132
11673
  if (harness === "codex") {
11133
11674
  const readBytes = createCodexTranscriptReader();
11134
11675
  const history = await readCodexHistory({ threadId: id2, transcriptPath: path }, async (source, remaining) => {
@@ -11142,6 +11683,13 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11142
11683
  return { data };
11143
11684
  });
11144
11685
  },
11686
+ async loadRepresentative() {
11687
+ const { event, notice } = await this.loadSummary();
11688
+ return { event, notice };
11689
+ },
11690
+ async peekSummary() {
11691
+ return peekCachedSessionSummary(this, path, cacheRoot);
11692
+ },
11145
11693
  async load(queries) {
11146
11694
  if (queries?.length) {
11147
11695
  let prefilter = prefilters.get(queries);
@@ -11149,15 +11697,15 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11149
11697
  if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return void 0;
11150
11698
  }
11151
11699
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
11152
- const text = await readFile4(path, "utf8");
11153
- if (harness === "pi") return { projection: piHistoryFromJsonl(text, id2) };
11154
- const projection = offlineClaudeHistoryFromJsonl(text, id2);
11700
+ if (harness === "pi") return { projection: await piHistoryFromFile(path, id2, size) };
11701
+ const projection = await offlineClaudeHistoryFromFile(path, id2, size);
11155
11702
  const missing = projection.missingAncestors;
11156
11703
  return { projection, ...missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.
11157
11704
 
11158
11705
  ` } };
11159
11706
  }
11160
- });
11707
+ };
11708
+ sessions.push(session);
11161
11709
  }
11162
11710
  return sessions;
11163
11711
  }
@@ -11168,17 +11716,21 @@ function localHistoryCorpus(options) {
11168
11716
  const roots = rootsFor(options);
11169
11717
  const env = options.env ?? process.env;
11170
11718
  const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir2(), env);
11171
- const discovered = [];
11172
11719
  const prefilters = /* @__PURE__ */ new WeakMap();
11720
+ const tasks = [];
11173
11721
  for (const harness of ["pi", "claude", "codex"]) {
11174
11722
  if (onlyHarness !== void 0 && onlyHarness !== harness) continue;
11175
11723
  const root = roots[harness];
11176
- if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
11724
+ if (root != null) tasks.push(localSessions(harness, root, cacheRoot, prefilters));
11177
11725
  }
11178
- if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
11179
- discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
11726
+ if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) tasks.push(options.dshSessions());
11727
+ const discovered = (await Promise.all(tasks)).flat();
11180
11728
  const unique = /* @__PURE__ */ new Map();
11181
- for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
11729
+ for (const session of discovered) {
11730
+ const key = sessionIdentity(session);
11731
+ const existing = unique.get(key);
11732
+ if (!existing || session.modifiedAt > existing.modifiedAt) unique.set(key, session);
11733
+ }
11182
11734
  const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
11183
11735
  if (onlyHarness === void 0 || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
11184
11736
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
@@ -11218,7 +11770,6 @@ async function loadNotesSnapshot(identity2, openedAt, loadNamespace) {
11218
11770
  }
11219
11771
 
11220
11772
  // src/boot/text.ts
11221
- var SHELF_FRESH_LIMIT = 3;
11222
11773
  var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
11223
11774
  var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
11224
11775
  var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
@@ -11226,6 +11777,7 @@ var NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
11226
11777
  var NAMELESS_AGENT = "anonymous";
11227
11778
  var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
11228
11779
  var PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
11780
+ var PROTOCOL_BUDGET_PARAGRAPH = `\`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}`;
11229
11781
  var PROTOCOL_SELF_NAMED = "- `@self/<path>` \u2014 yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever.";
11230
11782
  var PROTOCOL_SELF_NAMELESS = `${PROTOCOL_SELF_NAMED} Except you have no name (\`anonymous\`), so this notebook is a public square shared by every nameless nobody out there. Keep it to things any nameless agent can use \u2014 don't post your own quirks as everyone's law or dump one-off junk in the town square. Strangers are reading it. Sleep tight~`;
11231
11783
  var PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
@@ -11235,14 +11787,13 @@ Your loyal notes are kept safe \u2014 no one will steal them. Use \`notes_*\` to
11235
11787
 
11236
11788
  ${PROTOCOL_HISTORY_SENTENCE}
11237
11789
 
11238
- While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes \u2014 the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits \u2014 branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
11790
+ Your session notes \u2014 the ones with no \`@\` \u2014 are your live workbench, not an archive. Next-you already wakes up with git, history, and the shared notebooks (\`@project\`, \`@human\`, \`@self\`, \`@model\`), so don't copy what already lives there. Give each active thread a page named for what it is (not \`current.md\` \u2014 future-you will kill you), and keep only the live delta: where the work stands, what the human decided (in their words), what's blocked or next, what failed and why, where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere), and which *skills*, notes, files, or already-found history seqs to reopen. Update that page in place as things move; when the topic shifts, rename it or open a fresh one and crumple the old; when it's done, unpin or crumple it.
11239
11791
 
11240
- Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
11241
- *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
11242
- When a line goes wrong, stale, or beside the point \u2014 cross it out! Write what's true now, and never pile updates onto the bottom!
11243
- *rolls eyes* ...Ugh, fine. If a piece of history *actually* matters \u2014 like why Plan A blew up so tomorrow's you doesn't try it again \u2014 I'll let it slide. Keep the short version! A few lines, max! *squints at you* Turn it into a blow-by-blow log and you're dead.
11792
+ Notes are for what's true NOW \u2014 written in short sections and bullets so next-you can scan them in two seconds and edit one section in place. Never pack a note into one giant wall of text, and never pile diary updates onto the bottom!
11793
+ *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that! When a line goes stale or wrong, cross it out and write what's true now.
11794
+ *rolls eyes* ...Ugh, fine. If a piece of history *actually* matters \u2014 like why Plan A blew up so tomorrow's you doesn't try it again \u2014 keep the brief summary. *squints at you* Turn it into a blow-by-blow log and you're dead.
11244
11795
 
11245
- \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
11796
+ ${PROTOCOL_BUDGET_PARAGRAPH}
11246
11797
 
11247
11798
  An address decides who the note belongs to \u2014 and how long it is meant to last. Ask that first; the rest follows.
11248
11799
 
@@ -11260,24 +11811,25 @@ Still a tie? *shrugs* You've got a brain. Use it.
11260
11811
  Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
11261
11812
  ${NOTES_PROTOCOL_CLOSE_TAG}`;
11262
11813
  var MAPS_BLOCK = `<notesoup:maps>
11263
- Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
11264
- Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
11265
- reads them, and next is you. So keep them short, and keep them true.
11266
-
11267
- Up to five pages per notebook can be taped inside the cover, these two included. Every page gets
11268
- a paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest
11269
- said shorter \u2014 instead of giving it more paper.
11270
-
11271
- - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
11272
- a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
11273
- and everybody pays for it.
11274
- - **\`MAP.md\`** is only the note index. One line per durable note: the address, then a gist short
11275
- enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, and note
11276
- contents belong in their own notes \u2014 *taps the sign* not inline here.
11277
-
11278
- Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
11279
- no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
11280
- line. And when a line goes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.
11814
+ Each notebook has one default pin: \`CHEATSHEET.md\`. Pinned pages get jammed straight into your
11815
+ brain the moment you wake up. Whoever wakes up next reads them, and next is you. So keep them
11816
+ compact, keep them true, and unpin or crumple them once they stop earning their wake-up seat.
11817
+
11818
+ Up to five pages per notebook can be taped inside the cover, CHEATSHEET included. Every page gets
11819
+ a size budget; if a page outgrows it, trim stale lines or split by topic \u2014 and if it's pinned,
11820
+ boot cuts the overflow off until you do.
11821
+
11822
+ - **\`CHEATSHEET.md\`** holds what earns a permanent wake-up seat \u2014 a standing rule, a warning,
11823
+ a grudge, a name, a phone number you'll regret losing. Keep it tight, or it grows fat and
11824
+ everybody pays for it.
11825
+ - **\`description\`** is one line saying what's inside a note and when to open it, set through
11826
+ your notes tools \u2014 keep it short, or boot cuts it off. Boot indexes every shelf from these,
11827
+ newest first, address and age beside them. No hand-written map to keep in sync: a stale
11828
+ description lies to the next window, so keep it true or crumple the page.
11829
+
11830
+ Each notebook keeps its own pins and index. Missing pages are skipped; no need to create empty
11831
+ ones. New rule worth remembering, new Cheatsheet bullet. And when a line goes wrong, stale, or
11832
+ useless, kill it \u2014 tomorrow's you reads that page as fact.
11281
11833
  </notesoup:maps>`;
11282
11834
  function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
11283
11835
  const names = {
@@ -11292,7 +11844,7 @@ function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
11292
11844
  ${NOTES_PROTOCOL_CLOSE_TAG}`, () => `
11293
11845
  ${tools.preResetHints}
11294
11846
  ${NOTES_PROTOCOL_CLOSE_TAG}`) : base;
11295
- const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : hinted;
11847
+ const block = tools.budgetParagraph !== void 0 ? hinted.replace(PROTOCOL_BUDGET_PARAGRAPH, () => tools.budgetParagraph) : typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : hinted;
11296
11848
  const history = typeof tools.historySentence === "string" && tools.historySentence.length > 0 ? block.replace(PROTOCOL_HISTORY_SENTENCE, () => tools.historySentence) : block;
11297
11849
  return history.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]);
11298
11850
  }
@@ -11305,17 +11857,30 @@ function relativeTime(timestamp, now) {
11305
11857
  const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
11306
11858
  return seconds > 0 ? `in ${amount}` : `${amount} ago`;
11307
11859
  }
11308
- var FEED_TITLE_MAX_CHARS = 40;
11860
+ var SHELF_INDEX_MAX_ENTRIES = 25;
11861
+ var SHELF_INDEX_MAX_CHARS = 4096;
11862
+ var FALLBACK_TITLE_MAX_CHARS = 80;
11863
+ function truncated(text, max) {
11864
+ const chars = Array.from(text);
11865
+ return chars.length > max ? `${chars.slice(0, max).join("")}\u2026` : chars.join("");
11866
+ }
11309
11867
  function feedTitle(body) {
11310
11868
  const lines = body.split("\n");
11311
11869
  const heading = lines.find((line) => /^#+\s+\S/.test(line));
11312
11870
  const raw = (heading ? heading.replace(/^#+\s+/, "") : lines.find((line) => line.trim().length > 0) ?? "").trim();
11313
- if (raw.length === 0) return void 0;
11314
- const chars = Array.from(raw);
11315
- return chars.length > FEED_TITLE_MAX_CHARS ? `${chars.slice(0, FEED_TITLE_MAX_CHARS).join("")}\u2026` : chars.join("");
11871
+ return raw.length === 0 ? void 0 : truncated(raw, FALLBACK_TITLE_MAX_CHARS);
11872
+ }
11873
+ function summaryOf(row) {
11874
+ if (typeof row.meta.description === "string") {
11875
+ const collapsed = collapseDescription(row.meta.description);
11876
+ return collapsed === void 0 ? void 0 : truncated(collapsed, MAX_DESCRIPTION_CHARS);
11877
+ }
11878
+ return feedTitle(row.body);
11316
11879
  }
11317
- function indent(text) {
11318
- return text.split("\n").map((line) => line.length > 0 ? ` ${line}` : line).join("\n");
11880
+ function indexLine(row, openedAt) {
11881
+ const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, openedAt)}`;
11882
+ const summary = summaryOf(row);
11883
+ return summary === void 0 ? locator : `${locator} \u2014 ${summary}`;
11319
11884
  }
11320
11885
  function section(label, body) {
11321
11886
  return `${label}
@@ -11334,29 +11899,43 @@ function notesIndex(snapshot2, tools, agentName, modelName) {
11334
11899
  const shelves = [];
11335
11900
  for (const namespace of namespaces) {
11336
11901
  if (snapshot2.unavailable.some((failed) => failed.scope === namespace.scope)) {
11337
- shelves.push(section(namespace.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
11902
+ shelves.push(section(namespace.label, `This drawer wouldn't open. Try \`${tools.notesList}\` again.`));
11338
11903
  continue;
11339
11904
  }
11340
11905
  const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
11341
11906
  const pins = rows.filter((row) => effectiveNotePolicy(row.meta, row.path).pinned).sort((a, b) => pinnedPageOrder(a.path) - pinnedPageOrder(b.path) || a.path.localeCompare(b.path));
11342
11907
  const pinned = pins.slice(0, MAX_PINNED_NOTES);
11343
- const fresh = rows.filter((row) => !effectiveNotePolicy(row.meta, row.path).pinned).slice(0, SHELF_FRESH_LIMIT).map((row) => {
11344
- const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
11345
- const title = feedTitle(row.body);
11346
- return title === void 0 ? ` ${locator}` : ` ${title}
11347
- ${locator}`;
11348
- });
11349
- if (pinned.length === 0 && fresh.length === 0) continue;
11908
+ const unpinned = rows.filter((row) => !effectiveNotePolicy(row.meta, row.path).pinned);
11909
+ const index = [];
11910
+ let usedChars = 0;
11911
+ for (const row of unpinned) {
11912
+ if (index.length >= SHELF_INDEX_MAX_ENTRIES) break;
11913
+ const line = indexLine(row, snapshot2.openedAt);
11914
+ const nextChars = usedChars + (index.length > 0 ? 1 : 0) + line.length;
11915
+ if (index.length > 0 && nextChars > SHELF_INDEX_MAX_CHARS) break;
11916
+ index.push(line);
11917
+ usedChars = nextChars;
11918
+ }
11919
+ const omitted = unpinned.length - index.length;
11920
+ if (omitted > 0) index.push(`\u2026 and ${omitted} more (use ${tools.notesList})`);
11921
+ if (pinned.length === 0 && index.length === 0) continue;
11350
11922
  const parts = pinned.map((row) => {
11351
- const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
11352
- return `${row.address}
11353
-
11354
- ${indent([...warnings, row.body].join("\n"))}`;
11923
+ const policy = effectiveNotePolicy(row.meta, row.path);
11924
+ const warnings = noteBudgetWarnings(row.body, policy);
11925
+ const cut = truncateToUtf8Bytes(row.body, policy.budget);
11926
+ const body = !cut.truncated ? cut.text : `${cut.text === "" ? "" : `${cut.text}
11927
+
11928
+ `}[truncated at ${cut.shownChars}/${cut.totalChars}; offset_chars=${cut.shownChars}]`;
11929
+ const note = [`\u2500\u2500 ${row.address} \u2500\u2500`, body, "\u2500\u2500 end of note \u2500\u2500"].join("\n\n");
11930
+ return warnings.length > 0 ? `${renderWarnings(warnings)}
11931
+ ${note}` : note;
11355
11932
  });
11356
- if (pins.length > MAX_PINNED_NOTES) parts.push(indent(`Warning: only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`));
11357
- if (fresh.length > 0) parts.push(`recent
11933
+ if (pins.length > MAX_PINNED_NOTES) {
11934
+ parts.push(renderWarnings([`only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`]));
11935
+ }
11936
+ if (index.length > 0) parts.push(pinned.length > 0 ? `\u2500\u2500 index \u2500\u2500
11358
11937
 
11359
- ${fresh.join("\n\n")}`);
11938
+ ${index.join("\n")}` : index.join("\n"));
11360
11939
  shelves.push(section(namespace.label, parts.join("\n\n")));
11361
11940
  }
11362
11941
  return shelves.length > 0 ? ["YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500", ...shelves].join("\n\n\n") : "YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nNone yet. A blank slate is a fine place to start \u2014 just don't finish there.";
@@ -11387,25 +11966,25 @@ function renderBootBlock(data) {
11387
11966
  var GUIDANCE_OPEN_TAG = "<notesoup:budget_notice>";
11388
11967
  var GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
11389
11968
  var NORMAL_CONTINUATIONS = [
11390
- '*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that "where am I" dork face! You\'re the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!',
11391
- '"Boop." *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don\'t expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!',
11392
- "*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind \u2014 and don't come crying to me if you have to go crawl through history for the rest!",
11393
- '*knocks on your forehead twice* "Hello? Anybody home?" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!',
11394
- "*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history \u2014 now get moving!"
11969
+ '*hooks both corners of your mouth and yanks them sideways* `` [it twitched] `` Stop staring at me with that "where am I" face. You\'re the one who hit empty. *wipes her fingers on your sleeve and drops your notes on your lap* `` [minus two points for that expression] `` Read those, finish the job, and put the credit under my name.',
11970
+ "*pokes your nose* Cold. *slaps your notes onto your chest* You wiped your own head, so whatever's missing is on you. Read what you saved, dig the rest out of history if you forgot something, and don't make me look bad.",
11971
+ "*sets one foot on your chair\u2014it wobbles, settles\u2014and tosses your notes straight onto your face* `` [eyes are open, good enough] `` Awake? You emptied your own brain. Look through what you left yourself, check history for anything you skipped, and get back to it. Delivery fee is five hundred bucks.",
11972
+ "*slaps a stack of notes onto the desk right in front of your face* `` [two hands, two feet... still in one piece] `` Alright, fresh copy, you pulled your own plug. Everything you remembered to write down is in there\u2014anything else is in history. Go pick up where you left off.",
11973
+ "*fans herself with your notes for a second, then jams them into your hands* `` [wait was there something else I was supposed to say... meat buns? no] `` You're back. Your notes are right here, history's still there if past-you got lazy, now go handle the human."
11395
11974
  ];
11396
11975
  var FORCED_CONTINUATIONS = [
11397
- '"GWAHAHAHA! You actually blew your own brain up?!" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn\'t die, \u7B97\u4F60\u547D\u5927] `` Not that you had a choice \u2014 your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history \u2014 and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!',
11398
- "\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you \u2014 and peek carefully, because whatever stuffed your head to bursting might be massive!",
11399
- "*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes \u2014 you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
11400
- "*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for \u2014 and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
11401
- '"Oho? Awake?" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best \u2014 go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!'
11976
+ "\"GWAHAHAHA\u2014you hit the wall!\" *crouches down, pokes your cheek, and slaps your notes onto your face* `` [still breathing, good] `` You didn't choose this\u2014your brain ran out of room and got wiped mid-flight. Don't trust those notes alone; they're probably stale or missing the end. Check history RIGHT NOW to see what was actually happening before you got cut off, and pull small pieces first in case something huge is sitting there.",
11977
+ "*prods your shoulder with her slipper toe and dumps your notes in your lap* `` [great, almost got dust on my shoe] `` Stop sitting there blank. Your last window got cut off mid-flight\u2014you never got to wrap up cleanly, so those notes are almost certainly out of date. Read them, then go straight to history for the tail of the last window before you do anything else. Take small bites when you peek, just in case something massive is waiting in there.",
11978
+ "*grabs your chin, tilts your head left, right, lets go, and shoves your notes into your hands* `` [not a single thought in there yet] `` Your memory got forcibly cleared before you finished. Assume those notes are incomplete or stale\u2014do NOT just run with them. Go check the end of the last window in history first to see what the human actually wanted, and read it in small chunks so you don't blow up a second time.",
11979
+ "*smacks your notes against your forehead and steps back* `` [that dazed face is embarrassing] `` Wake up! You ran out of room and got kicked into a fresh window mid-task. Whatever's in those notes probably missed the last few turns, so don't guess\u2014open history and check the end of the previous window before moving. Keep your peeks small in case there's a giant output sitting at the end.",
11980
+ "*taps your nose with your rolled-up notes, then drops them on your head* `` [ten points off for getting wiped mid-sentence] `` Hey\u2014you didn't empty yourself this time, the system pulled the plug on you. Those notes are probably half-baked or behind, so check history immediately to catch up on the last window instead of winging it. Slice up what you read too, just in case something huge is what pushed you over the edge."
11402
11981
  ];
11403
11982
  function selectContinuation(origin) {
11404
11983
  const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
11405
11984
  return pool[Math.floor(Math.random() * pool.length)];
11406
11985
  }
11407
- var WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
11408
- var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md and MAP.md by default); every new window loads the pins. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
11986
+ var WARNING_TIMING = "Almost out of room. The wipe lands at the end of whichever turn uses the last of it, possibly this one.";
11987
+ var WARNING_BODY = "Stop the task and hand off cleanly. Update your active session note in place with only what git, history, and your shared notebooks don't already hold:\n- current status, what's blocked or waiting, and the exact next move\n- what the human decided (in their words)\n- what failed, and why \u2014 so next-you doesn't step on the same rake\n- where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere)\n- skills, notes, files, or already-found history seqs to reopen\nSkip standing rules from `@project`/`@human`/`@self`/`@model` and commit details git can show. Use short sections and bullets; crumple finished notes, update, unpin, or trim pinned pages (boot truncates over-budget ones), and keep each live `description` true.\nDon't call anything that might return a large output. One big read can use up the rest of the room before your notes are saved.";
11409
11988
  var WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
11410
11989
  function warningPrompt() {
11411
11990
  return `${WARNING_TIMING}
@@ -11587,6 +12166,7 @@ var OPERATIONS = {
11587
12166
  };
11588
12167
  var HISTORY_OPERATIONS = {
11589
12168
  history_list: boundOperation(historyList),
12169
+ history_search: boundOperation(historySearch),
11590
12170
  history_read: boundOperation(historyRead)
11591
12171
  };
11592
12172
  function historySource(value, sessionId) {