notesoup 0.0.0-stage → 0.40.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +94 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +17 -0
  8. package/dist/src/boot/text.js +48 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +156 -0
  36. package/dist/src/history/history.js +212 -0
  37. package/dist/src/history/query.d.ts +63 -0
  38. package/dist/src/history/query.js +201 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +103 -0
  58. package/dist/src/notes/store.js +474 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +9 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +7 -0
  98. package/dist/src/pi/tool-names.js +7 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +58 -0
  108. package/dist/src/tools/history.js +210 -0
  109. package/dist/src/tools/notes.d.ts +250 -0
  110. package/dist/src/tools/notes.js +360 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +82 -0
  114. package/dist/src/tools/result.js +104 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +367 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +633 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +274 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +515 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +530 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +78 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9265 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +240 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +58 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +286 -0
  188. package/src/history/query.ts +222 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +494 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +11 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +9 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +234 -0
  224. package/src/tools/notes.ts +381 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +144 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,633 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { Check } from "typebox/value";
4
+ import { earliestMatchOffsetChars, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
5
+ import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
6
+ import { historyDocument, projectHistory } from "../src/history/history.js";
7
+ import { selectPage } from "../src/history/query.js";
8
+ import { appendText, assertWithinBudget, call, context, makeExtension, manager, resultData, resultError, resultRead, } from "./helpers/extension.js";
9
+ import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
10
+ installExtensionTestHooks("notesoup-history-v2");
11
+ /** Append a message the way the host records one, without the harness's per-role sugar. */
12
+ function append(session, message) {
13
+ return session.appendMessage(message);
14
+ }
15
+ function toolCall(session, id, name, args) {
16
+ return append(session, { role: "assistant", content: [{ type: "toolCall", id, name, arguments: args }], stopReason: "toolUse", timestamp: Date.now() });
17
+ }
18
+ function toolResult(session, id, name, text, extra = {}) {
19
+ return append(session, { role: "toolResult", toolCallId: id, toolName: name, content: [{ type: "text", text }], isError: false, timestamp: Date.now(), ...extra });
20
+ }
21
+ function page(result) {
22
+ return resultData(result);
23
+ }
24
+ function seqs(result) {
25
+ return page(result).items.map((item) => item.seq);
26
+ }
27
+ /** What the model reads for one result, so a test can check the text surface directly. */
28
+ function rendered(result) {
29
+ return result.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("");
30
+ }
31
+ test("history_list exposes bounded paging, `from` and a literal query, while notes use snapshot limits", () => {
32
+ const captured = makeExtension(manager());
33
+ const readSchema = captured.tools.get("history_read")?.parameters;
34
+ const legacyItemKey = ["item", "id"].join("_");
35
+ assert.ok(readSchema.properties?.seq);
36
+ assert.deepEqual(readSchema.required, ["seq"]);
37
+ assert.equal(readSchema.properties?.[legacyItemKey], undefined);
38
+ assert.equal(readSchema.properties?.window_id, undefined);
39
+ const listSchema = captured.tools.get("history_list").parameters;
40
+ const properties = listSchema.properties;
41
+ assert.equal(properties.before_seq?.minimum, 1, "bounds are positive seqs");
42
+ assert.equal(properties.after_seq?.minimum, 1);
43
+ assert.equal(Check(listSchema, { before_seq: 0 }), false, "before_seq:0 is refused by the schema, not answered with a silent empty page");
44
+ assert.equal(Check(listSchema, { after_seq: 0 }), false);
45
+ assert.deepEqual(properties.from?.anyOf?.map((item) => item.const), ["newest", "oldest"]);
46
+ assert.ok(properties.query);
47
+ assert.equal(properties.around, undefined);
48
+ assert.equal(properties.tool_name, undefined);
49
+ assert.equal(properties.custom_type, undefined);
50
+ assert.equal(properties.cursor, undefined);
51
+ assert.deepEqual(properties.roles?.items?.anyOf?.map((item) => item.const), ["user", "assistant", "tool", "context"], "the role filter carries the four public roles");
52
+ assert.ok(properties.since, "the time filter has a since param");
53
+ assert.ok(properties.until, "the time filter has an until param");
54
+ assert.equal(Check(listSchema, { since: "2026-10-10", until: "2026-10-10T06:00:00Z" }), true);
55
+ assert.equal(Check(listSchema, { since: "" }), false, "an empty time value is refused by the schema");
56
+ assert.equal(Check(listSchema, { query: "needle", from: "oldest", roles: ["tool"] }), true);
57
+ assert.equal(Check(listSchema, { from: "recent" }), false);
58
+ // The retired names are unknown parameters, refused like any other: `additionalProperties: false`.
59
+ for (const retired of [{ before: 5 }, { after: 5 }, { order: "oldest" }, { limit_chars: 10 }]) {
60
+ assert.equal(Check(listSchema, retired), false, `${Object.keys(retired)[0]} is refused as an unknown parameter`);
61
+ }
62
+ assert.equal(Check(listSchema, { query: "" }), true, "an empty literal is schema-valid; the operation refuses it as invalid_query");
63
+ for (const invalid of [{ roles: ["tool_call"] }, { roles: ["system"] }, { tool_name: "bash" }, { roles: [] }]) {
64
+ assert.equal(Check(listSchema, invalid), false, JSON.stringify(invalid));
65
+ }
66
+ const windowsSchema = captured.tools.get("history_windows")?.parameters;
67
+ assert.deepEqual(Object.keys(windowsSchema.properties ?? []), []);
68
+ const notesSchema = captured.tools.get("notes_list")?.parameters;
69
+ assert.equal(notesSchema.properties?.cursor, undefined);
70
+ assert.ok(notesSchema.properties?.limit);
71
+ const notesSearchSchema = captured.tools.get("notes_search")?.parameters;
72
+ assert.equal(notesSearchSchema.properties?.cursor, undefined);
73
+ assert.ok(notesSearchSchema.properties?.limit);
74
+ });
75
+ test("every history operation declares a result schema its own payload satisfies", async () => {
76
+ const session = manager();
77
+ const captured = makeExtension(session);
78
+ const ctx = context(session);
79
+ appendText(session, "user", "hello");
80
+ toolCall(session, "call-1", "bash", { command: "pwd" });
81
+ toolResult(session, "call-1", "bash", "/tmp");
82
+ for (const toolName of ["history_windows", "history_list", "history_read"]) {
83
+ const operation = { history_windows: historyWindows, history_list: historyList, history_read: historyRead }[toolName];
84
+ const result = await call(captured, toolName, toolName === "history_read" ? { seq: 1 } : toolName === "history_list" ? { query: "hello" } : {}, ctx);
85
+ const structured = result.structuredContent;
86
+ assert.ok(structured !== undefined, `${toolName} carries a structured outcome`);
87
+ assert.equal(Check(operation.outputSchema, structured), true, `${toolName} payload satisfies its own outputSchema`);
88
+ assertWithinBudget(result, `${toolName} page`);
89
+ }
90
+ const conversation = await call(captured, "history_list", {}, ctx);
91
+ assert.equal(Check(historyList.outputSchema, conversation.structuredContent), true);
92
+ const refusal = await call(captured, "history_read", { seq: 999 }, ctx);
93
+ assert.equal(Check(historyRead.outputSchema, refusal.structuredContent), true, "a refusal satisfies the same result schema");
94
+ });
95
+ test("seq is stable across branch changes, abandoned entries stay unreadable, and a paired result seq is refused precisely", async () => {
96
+ const session = manager();
97
+ const captured = makeExtension(session);
98
+ const ctx = context(session);
99
+ const firstId = appendText(session, "user", "first");
100
+ const abandonedId = appendText(session, "assistant", "abandoned reply");
101
+ const before = page(await call(captured, "history_list", { roles: ["user", "assistant"] }, ctx));
102
+ assert.deepEqual(before.items.map((item) => [item.seq, item.content]), [[1, "first"], [2, "abandoned reply"]]);
103
+ session.branch(firstId);
104
+ const branchId = appendText(session, "user", "new branch");
105
+ const after = page(await call(captured, "history_list", { roles: ["user", "assistant"] }, ctx));
106
+ assert.deepEqual(after.items.map((item) => [item.seq, item.content]), [[1, "first"], [3, "new branch"]]);
107
+ assert.equal(branchId !== abandonedId, true);
108
+ const offBranch = resultError(await call(captured, "history_read", { seq: 2 }, ctx));
109
+ assert.equal(offBranch.code, "not_on_branch");
110
+ assert.match(offBranch.message, /another branch/);
111
+ assert.equal(JSON.stringify(offBranch).includes("abandoned"), false, "the refusal does not leak the abandoned entry's text");
112
+ const unknown = resultError(await call(captured, "history_read", { seq: 4 }, ctx));
113
+ assert.equal(unknown.code, "unknown_seq");
114
+ assert.match(unknown.message, /run 1\.\.3/);
115
+ });
116
+ test("a result address consumed by a pairing names its call instead of serving a second read", async () => {
117
+ const session = manager();
118
+ const captured = makeExtension(session);
119
+ const ctx = context(session);
120
+ toolCall(session, "paired", "edit", { path: "a.md" });
121
+ toolResult(session, "paired", "edit", "edited");
122
+ // The assistant message takes seq 1 and its tool call seq 2; the result at seq 3 is absorbed.
123
+ assert.deepEqual(seqs(await call(captured, "history_list", { roles: ["tool"] }, ctx)), [2], "the pairing is one event at the call's address");
124
+ const consumed = resultError(await call(captured, "history_read", { seq: 3 }, ctx));
125
+ assert.equal(consumed.code, "not_an_event");
126
+ assert.match(consumed.message, /already shown inside the call at seq 2/);
127
+ const callSeq = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
128
+ assert.equal(callSeq.seq, 2);
129
+ assert.equal(callSeq.content, 'edit {"path":"a.md"}\n--- output ---\nedited');
130
+ });
131
+ test("history_list pages from the end `from` names and returns bounded ranges", async () => {
132
+ const session = manager();
133
+ const captured = makeExtension(session);
134
+ const ctx = context(session);
135
+ for (let index = 1; index <= 5; index++)
136
+ appendText(session, "user", `message-${index}`);
137
+ assert.deepEqual(seqs(await call(captured, "history_list", { limit: 2 }, ctx)), [4, 5], "the default newest page is the highest seqs, ascending");
138
+ assert.deepEqual(seqs(await call(captured, "history_list", { limit: 2, from: "oldest" }, ctx)), [1, 2], "from oldest takes the other end of the same selection");
139
+ appendText(session, "user", "message-6");
140
+ const older = page(await call(captured, "history_list", { before_seq: 5, limit: 2 }, ctx));
141
+ assert.deepEqual(older.items.map((item) => item.seq), [3, 4]);
142
+ assert.deepEqual(older.page_older, { before_seq: 3 });
143
+ assert.equal(older.page_newer, null);
144
+ assert.deepEqual(seqs(await call(captured, "history_list", { after_seq: 5, limit: 2, from: "oldest" }, ctx)), [6]);
145
+ for (let index = 7; index <= 10; index++)
146
+ appendText(session, "user", `message-${index}`);
147
+ const range = page(await call(captured, "history_list", { after_seq: 2, before_seq: 10, limit: 3, from: "oldest" }, ctx));
148
+ assert.deepEqual(range.items.map((item) => item.seq), [3, 4, 5]);
149
+ assert.equal(range.page_older, null);
150
+ assert.deepEqual(range.page_newer, { after_seq: 5, from: "oldest" }, "both bounds do not imply a direction; the cursor carries one");
151
+ assert.match(rendered(await call(captured, "history_list", { after_seq: 2, before_seq: 10, limit: 3, from: "oldest" }, ctx)), /→ newer: \{"after_seq":5,"from":"oldest"\}/, "the footer prints the exact call to page newer");
152
+ assert.deepEqual(seqs(await call(captured, "history_list", { after_seq: 2, before_seq: 10, limit: 3 }, ctx)), [7, 8, 9], "the same range with the default from starts from the newest end");
153
+ const rangeNext = page(await call(captured, "history_list", { ...range.page_newer, before_seq: 10, limit: 3 }, ctx));
154
+ assert.deepEqual(rangeNext.items.map((item) => item.seq), [6, 7, 8]);
155
+ const rangeLast = page(await call(captured, "history_list", { ...rangeNext.page_newer, before_seq: 10, limit: 3 }, ctx));
156
+ assert.deepEqual(rangeLast.items.map((item) => item.seq), [9]);
157
+ assert.equal(rangeLast.page_older, null);
158
+ assert.equal(rangeLast.page_newer, null);
159
+ assert.equal("has_older" in rangeLast, false);
160
+ assert.equal("has_newer" in rangeLast, false);
161
+ });
162
+ test("a one-row page budget admits the newest candidate first", () => {
163
+ const windowId = "w1";
164
+ const items = [1, 2, 3].map((seq) => ({ seq, windowId, role: "user", text: `message-${seq}`, createdAt: undefined }));
165
+ const projection = projectHistory([{ windowId, items }], 12, new Set([1, 2, 3]));
166
+ const keptSeqs = (fitsRows, from) => {
167
+ const outcome = selectPage(projection, { limit: 3, ...(from === undefined ? {} : { from }) }, (candidate) => candidate.items.length <= fitsRows, 200);
168
+ assert.equal(outcome.ok, true);
169
+ return outcome.ok ? outcome.data.items.map((item) => ("folded" in item ? item.first_seq : item.seq)) : [];
170
+ };
171
+ assert.deepEqual(keptSeqs(1), [3], "a budget for one row admits the newest candidate, not the oldest");
172
+ assert.deepEqual(keptSeqs(2), [2, 3], "a truncated prefix is the newest rows, delivered in chronological order");
173
+ assert.deepEqual(keptSeqs(1, "oldest"), [1], "from oldest keeps the other end when the budget is short");
174
+ });
175
+ test("since and until select a half-open time range, compose with query and paging, and refuse bad bounds", async () => {
176
+ const items = [
177
+ { seq: 1, windowId: "w1", role: "user", text: "first needle", createdAt: "2026-10-10T00:00:00.000Z" },
178
+ { seq: 2, windowId: "w1", role: "assistant", text: "second", createdAt: "2026-10-10T06:00:00.000Z" },
179
+ { seq: 3, windowId: "w1", role: "user", text: "third needle", createdAt: "2026-10-10T12:00:00.000Z" },
180
+ { seq: 4, windowId: "w1", role: "assistant", text: "fourth", createdAt: "2026-10-10T18:00:00.000Z" },
181
+ { seq: 5, windowId: "w1", role: "user", text: "fifth needle", createdAt: undefined },
182
+ ];
183
+ const projection = projectHistory([{ windowId: "w1", items }], 5, new Set([1, 2, 3, 4, 5]));
184
+ const selected = async (params) => {
185
+ const outcome = await historyList.execute(params, projection);
186
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
187
+ return outcome.ok ? outcome.data.items.map((item) => ("folded" in item ? item.first_seq : item.seq)) : [];
188
+ };
189
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", since: "2026-10-10T06:00:00Z" }), [2, 3, 4], "since keeps later events and drops one with no time");
190
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", until: "2026-10-10T12:00:00Z" }), [1, 2], "until is exclusive");
191
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", since: "2026-10-10T06:00:00Z", until: "2026-10-10T18:00:00Z" }), [2, 3], "both bounds make a half-open range");
192
+ assert.deepEqual(await selected({ query: "needle", from: "oldest", since: "2026-10-10T06:00:00Z" }), [3], "a query composes with the time range");
193
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", since: "2026-10-10T00:00:00Z", until: "2026-10-10T18:00:00Z", after_seq: 1, before_seq: 4 }), [2, 3], "seq paging composes with the time range");
194
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", since: "2026-10-10" }), [1, 2, 3, 4], "a date-only since is inclusive UTC midnight, not local midnight");
195
+ assert.deepEqual(await selected({ roles: ["user", "assistant"], from: "oldest", until: "2026-10-10T12:00" }), [1, 2], "a time without an offset is UTC");
196
+ const malformed = await historyList.execute({ since: "yesterday" }, projection);
197
+ assert.equal(malformed.ok, false);
198
+ if (!malformed.ok) {
199
+ assert.equal(malformed.error.code, "invalid_time");
200
+ assert.match(malformed.error.message, /"yesterday"/, "the refusal names the offending param and value");
201
+ }
202
+ const inverted = await historyList.execute({ since: "2026-10-11", until: "2026-10-10" }, projection);
203
+ assert.equal(inverted.ok, false);
204
+ if (!inverted.ok)
205
+ assert.equal(inverted.error.code, "invalid_time");
206
+ });
207
+ test("time bounds also keep untimed events out of the folded conversation view", async () => {
208
+ const items = [
209
+ { seq: 1, windowId: "w1", role: "user", text: "before", createdAt: "2026-10-10T00:00:00.000Z" },
210
+ { seq: 2, windowId: "w1", role: "tool", text: "output", createdAt: undefined },
211
+ { seq: 3, windowId: "w1", role: "user", text: "after", createdAt: "2026-10-10T12:00:00.000Z" },
212
+ ];
213
+ const projection = projectHistory([{ windowId: "w1", items }], 3, new Set([1, 2, 3]));
214
+ const bounded = await historyList.execute({ since: "2026-10-10T00:00:00Z" }, projection);
215
+ assert.equal(bounded.ok, true);
216
+ if (bounded.ok)
217
+ assert.deepEqual(bounded.data.items.map((item) => ("folded" in item ? `folded ${item.count}` : `seq ${item.seq}`)), ["seq 1", "seq 3"], "an untimed tool event is not folded into a bounded selection");
218
+ const unbounded = await historyList.execute({}, projection);
219
+ assert.equal(unbounded.ok, true);
220
+ if (unbounded.ok)
221
+ assert.equal(unbounded.data.items.some((item) => "folded" in item), true, "without bounds the untimed run still folds");
222
+ });
223
+ test("conversation view folds tools and injected messages, while explicit roles expand them", async () => {
224
+ const session = manager();
225
+ const captured = makeExtension(session);
226
+ const ctx = context(session);
227
+ appendText(session, "user", "please inspect");
228
+ const turnId = append(session, {
229
+ role: "assistant",
230
+ content: [
231
+ { type: "text", text: "I will inspect" },
232
+ { type: "toolCall", id: "tc-1", name: "bash", arguments: { command: "pwd" } },
233
+ { type: "toolCall", id: "tc-2", name: "read", arguments: { path: "README.md" } },
234
+ ],
235
+ stopReason: "toolUse",
236
+ timestamp: Date.now(),
237
+ });
238
+ toolResult(session, "tc-1", "bash", "ok");
239
+ toolResult(session, "tc-2", "read", "contents");
240
+ session.appendCustomMessageEntry("square", "injected event", false);
241
+ append(session, { role: "assistant", content: [], stopReason: "toolUse", timestamp: Date.now() });
242
+ const conversation = page(await call(captured, "history_list", {}, ctx));
243
+ const legacyItemKey = ["item", "id"].join("_");
244
+ assert.equal(conversation.items.some((item) => item.folded === true), true);
245
+ assert.equal(conversation.items.some((item) => item.role === "developer"), false);
246
+ assert.equal(conversation.items.some((item) => item.role === "tool"), false);
247
+ assert.equal(conversation.items.some((item) => item.role === "assistant" && item.content === ""), false);
248
+ assert.equal(conversation.items.every((item) => legacyItemKey in item === false), true);
249
+ const folded = conversation.items.find((item) => item.folded === true);
250
+ assert.equal(folded.count, 3, "two tool events and one injected context are folded, not the empty assistant message");
251
+ assert.deepEqual(folded.tools, { bash: 1, read: 1 });
252
+ assert.equal("custom_types" in folded, false);
253
+ const empty = page(await call(captured, "history_list", { roles: ["context"], before_seq: 2 }, ctx));
254
+ assert.deepEqual(empty.items, []);
255
+ const hiddenOnly = page(await call(captured, "history_list", { after_seq: 2, before_seq: 6 }, ctx));
256
+ assert.deepEqual(hiddenOnly.items, [{ folded: true, first_seq: 3, last_seq: 4, count: 2, tools: { bash: 1, read: 1 } }]);
257
+ const expanded = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
258
+ assert.deepEqual(expanded.items.map((item) => [item.seq, item.role, item.tool, item.tool_status]), [[3, "tool", "bash", "ok"], [4, "tool", "read", "ok"]]);
259
+ assert.equal(expanded.items[0].content, 'bash {"command":"pwd"}\n--- output ---\nok');
260
+ assert.equal(expanded.items[1].content, 'read {"path":"README.md"}\n--- output ---\ncontents');
261
+ assert.equal(expanded.items.every((item) => !("call_seq" in item || "result_seq" in item || "tool_name" in item)), true);
262
+ assert.deepEqual(seqs(await call(captured, "history_list", { query: "bash", roles: ["tool"] }, ctx)), [3]);
263
+ const injected = page(await call(captured, "history_list", { roles: ["context"] }, ctx));
264
+ assert.deepEqual(injected.items.map((item) => [item.role, item.content]), [["context", "injected event"]]);
265
+ assert.equal(turnId.length > 0, true);
266
+ });
267
+ test("tool summaries and documents preserve pending, errored, and orphan runs", async () => {
268
+ const session = manager();
269
+ const captured = makeExtension(session);
270
+ const ctx = context(session);
271
+ append(session, { role: "assistant", content: [{ type: "toolCall", id: "paired", name: "edit", arguments: { path: "šŸ˜€.md", oldText: "before" } }], stopReason: "toolUse", timestamp: Date.now() });
272
+ toolResult(session, "paired", "edit", "replacement OK", { isError: true });
273
+ append(session, { role: "assistant", content: [{ type: "toolCall", id: "pending", name: "edit", arguments: { path: "pending.md" } }], stopReason: "toolUse", timestamp: Date.now() });
274
+ toolResult(session, "orphan", "edit", "orphan output", {
275
+ nestedCalls: { complete: true, calls: [{ id: "orphan/1", name: "read", arguments: { path: "orphan-nested.md" }, status: "ok" }] },
276
+ });
277
+ const events = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
278
+ // The orphan result ran and succeeded; nothing about its missing call changes that. Only the
279
+ // pending call, which no result ended, is unfinished.
280
+ assert.deepEqual(events.items.map((item) => [item.seq, item.tool_status]), [[2, "error"], [5, "unfinished"], [6, "ok"]]);
281
+ assert.equal(events.items[0].content, 'edit {"path":"šŸ˜€.md","oldText":"before"}\n--- output ---\nreplacement OK');
282
+ assert.equal(events.items[1].content, 'edit {"path":"pending.md"}', "an unfinished call claims no output");
283
+ assert.equal(events.items[2].content, 'edit (arguments not recorded)\n--- output ---\norphan output\n--- nested calls (complete, 1 recorded) ---\n- orphan/1 read [ok] {"path":"orphan-nested.md"}', "an orphan result invents no arguments, and keeps the nested evidence the host recorded");
284
+ const errored = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
285
+ assert.equal(errored.tool, "edit");
286
+ assert.equal(errored.tool_status, "error");
287
+ assert.equal(errored.text, events.items[0].content);
288
+ assert.equal("execution" in errored, false, "arguments are delivered once, in the document");
289
+ const pending = resultRead(await call(captured, "history_read", { seq: 5 }, ctx));
290
+ assert.equal(pending.tool_status, "unfinished");
291
+ const orphan = resultRead(await call(captured, "history_read", { seq: 6 }, ctx));
292
+ assert.deepEqual(orphan.nested_calls, { call_count: 1, complete: true });
293
+ assert.equal(orphan.text, events.items[2].content, "an orphan's nested evidence stays readable despite the missing call");
294
+ assert.deepEqual(seqs(await call(captured, "history_list", { query: "edit", roles: ["tool"] }, ctx)), [2, 5, 6]);
295
+ assert.deepEqual(seqs(await call(captured, "history_list", { query: "pending.md", roles: ["tool"] }, ctx)), [5]);
296
+ assert.deepEqual(seqs(await call(captured, "history_list", { query: "orphan output", roles: ["tool"] }, ctx)), [6]);
297
+ assert.deepEqual(seqs(await call(captured, "history_list", { query: "orphan-nested.md", roles: ["tool"] }, ctx)), [6], "nested evidence stays findable even when the call it belongs to was never recorded");
298
+ });
299
+ test("native nested-call records are searchable, readable, and never gain a result or an address", async () => {
300
+ const session = manager();
301
+ const captured = makeExtension(session);
302
+ const ctx = context(session);
303
+ toolCall(session, "codemode", "codemode", { script: "run()" });
304
+ toolResult(session, "codemode", "codemode", "script finished", {
305
+ nestedCalls: {
306
+ complete: false,
307
+ calls: [
308
+ { id: "codemode/1", name: "read", arguments: { path: "nested-needle.md" }, status: "ok", durationMs: 12 },
309
+ { id: "codemode/2", name: "bash", status: "error", durationMs: 4, error: "exit 1" },
310
+ { id: "codemode/3", name: "spawn", status: "unfinished" },
311
+ ],
312
+ },
313
+ });
314
+ const found = page(await call(captured, "history_list", { query: "nested-needle" }, ctx));
315
+ assert.deepEqual(found.items.map((item) => item.seq), [2], "nested arguments are part of the searchable document");
316
+ const read = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
317
+ assert.deepEqual(read.nested_calls, { call_count: 3, complete: false }, "the host's completeness flag stays unchanged");
318
+ assert.equal(read.text, 'codemode {"script":"run()"}\n--- output ---\nscript finished\n--- nested calls (incomplete, 3 recorded) ---\n- codemode/1 read [ok] 12ms {"path":"nested-needle.md"}\n- codemode/2 bash [error] 4ms error: exit 1 (arguments not recorded)\n- codemode/3 spawn [unfinished] (arguments not recorded)');
319
+ assert.equal(read.next_offset_chars, null);
320
+ assert.equal("execution" in read, false, "nested records are not duplicated outside the document");
321
+ const rendered = read.content;
322
+ for (const [needle, offset] of [["nested-needle.md", earliestMatchOffsetChars(read.content, ["nested-needle.md"])], ["exit 1", earliestMatchOffsetChars(read.content, ["exit 1"])], ["unfinished", earliestMatchOffsetChars(read.content, ["unfinished"])]]) {
323
+ assert.ok(offset >= 0 && rendered.slice(offset).startsWith(needle), `nested evidence "${needle}" is readable in the document`);
324
+ }
325
+ });
326
+ test("absent nested calls mean unavailable, not a known-empty record", async () => {
327
+ const session = manager();
328
+ const captured = makeExtension(session);
329
+ const ctx = context(session);
330
+ toolCall(session, "plain", "read", { path: "a.md" });
331
+ toolResult(session, "plain", "read", "contents");
332
+ const listed = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
333
+ assert.equal("nested_calls" in listed.items[0], false, "a page row never carries nested-call evidence; one read does");
334
+ const read = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
335
+ assert.equal("nested_calls" in read, false);
336
+ assert.equal(read.content.includes("nested calls"), false);
337
+ });
338
+ test("oversized arguments and long nested records remain fully pageable and searchable", async () => {
339
+ const session = manager();
340
+ const captured = makeExtension(session);
341
+ const ctx = context(session);
342
+ const huge = "x".repeat(TOOL_OUTPUT_MAX_BYTES * 2);
343
+ toolCall(session, "big", "write", { path: "big.md", content: huge });
344
+ toolResult(session, "big", "write", "written", {
345
+ nestedCalls: {
346
+ complete: true,
347
+ calls: Array.from({ length: 400 }, (_, index) => ({ id: `big/${index}`, name: "read", arguments: { path: `p${index}.md` }, status: "ok", durationMs: 1 })),
348
+ },
349
+ });
350
+ let read = resultRead(await call(captured, "history_read", { seq: 2, max_chars: 50_000 }, ctx));
351
+ assert.deepEqual(read.nested_calls, { call_count: 400, complete: true }, "the read counts every recorded call, not only the records one page can carry");
352
+ let document = read.text;
353
+ while (read.next_offset_chars !== null) {
354
+ const next = read.next_offset_chars;
355
+ const result = await call(captured, "history_read", { seq: 2, offset_chars: next, max_chars: 50_000 }, ctx);
356
+ assertWithinBudget(result, "bounded document page");
357
+ read = resultRead(result);
358
+ assert.ok(read.text.length > 0, "every continuation makes progress");
359
+ document += read.text;
360
+ }
361
+ const expectedCalls = Array.from({ length: 400 }, (_, index) => `- big/${index} read [ok] 1ms {"path":"p${index}.md"}`).join("\n");
362
+ assert.equal(document, `write ${JSON.stringify({ path: "big.md", content: huge })}\n--- output ---\nwritten\n--- nested calls (complete, 400 recorded) ---\n${expectedCalls}`, "paging reconstructs all arguments and all recorded calls exactly");
363
+ assertWithinBudget(await call(captured, "history_read", { seq: 2 }, ctx), "bounded first read");
364
+ assertWithinBudget(await call(captured, "history_list", { roles: ["tool"] }, ctx), "bounded list row");
365
+ const hit = page(await call(captured, "history_list", { query: "big.md", max_chars_per_item: 40 }, ctx));
366
+ assert.deepEqual(hit.items.map((item) => item.seq), [2], "the document still carries the real arguments, so a query still finds them");
367
+ const late = page(await call(captured, "history_list", { query: "p399.md" }, ctx)).items[0];
368
+ assert.equal(late.seq, 2);
369
+ const resumed = resultRead(await call(captured, "history_read", { seq: 2, offset_chars: late.offset_chars }, ctx));
370
+ assert.ok(resumed.text.startsWith("p399.md"), "a query can jump directly to evidence beyond the first read");
371
+ });
372
+ test("standalone bash execution retains command, output, and truncation path", async () => {
373
+ const session = manager();
374
+ const captured = makeExtension(session);
375
+ const ctx = context(session);
376
+ append(session, { role: "bashExecution", command: "echo needle", output: "needle output", exitCode: 0, cancelled: false, truncated: true, fullOutputPath: "/tmp/bash-output.txt", timestamp: Date.now() });
377
+ const raw = await call(captured, "history_list", { roles: ["tool"] }, ctx);
378
+ const found = page(raw);
379
+ assert.equal(found.items.length, 1);
380
+ assert.deepEqual(found.items[0], {
381
+ seq: 1,
382
+ window_id: found.items[0].window_id,
383
+ role: "tool",
384
+ created_at: found.items[0].created_at,
385
+ tool: "bash",
386
+ tool_status: "ok",
387
+ output_truncated: true,
388
+ full_output_path: "/tmp/bash-output.txt",
389
+ truncated: false,
390
+ content: 'bash {"command":"echo needle"}\n--- output ---\nneedle output',
391
+ });
392
+ assert.match(rendered(raw), /output truncated, full text at \/tmp\/bash-output\.txt/, "a truncation with a path names both");
393
+ const query = page(await call(captured, "history_list", { roles: ["tool"], query: "NEEDLE OUTPUT" }, ctx));
394
+ assert.deepEqual(query.items.map((item) => item.seq), [1]);
395
+ const read = resultRead(await call(captured, "history_read", { seq: 1, offset_chars: query.items[0].offset_chars }, ctx));
396
+ assert.equal(read.content, "needle output");
397
+ assert.equal(read.seq, 1);
398
+ });
399
+ test("a truncated tool run without a recorded path still reports output_truncated", async () => {
400
+ const session = manager();
401
+ const captured = makeExtension(session);
402
+ const ctx = context(session);
403
+ append(session, { role: "bashExecution", command: "echo big", output: "big output", exitCode: 0, cancelled: false, truncated: true, timestamp: Date.now() });
404
+ const raw = await call(captured, "history_list", { roles: ["tool"] }, ctx);
405
+ const found = page(raw);
406
+ assert.equal(found.items.length, 1);
407
+ const item = found.items[0];
408
+ assert.equal(item.output_truncated, true, "the truncation is reported even with no path");
409
+ assert.equal("full_output_path" in item, false, "no path is invented");
410
+ assert.match(rendered(raw), /output truncated/, "the header still says the output was truncated");
411
+ assert.equal(rendered(raw).includes("full text at"), false, "the header claims no path");
412
+ const read = resultRead(await call(captured, "history_read", { seq: 1 }, ctx));
413
+ assert.equal(read.output_truncated, true, "the read reports the same truncation");
414
+ assert.equal("full_output_path" in read, false);
415
+ });
416
+ test("list renders paging and fold recipes, read renders a neighborhood call, and @previous resolves", async () => {
417
+ const session = manager();
418
+ const captured = makeExtension(session);
419
+ const ctx = context(session);
420
+ for (let i = 0; i < 30; i++)
421
+ appendText(session, "user", `older window ${i}`);
422
+ session.appendCustomEntry("notesoup/reset-marker", { windowId: "pcw:test:w2" });
423
+ appendText(session, "user", "current window");
424
+ const listed = await call(captured, "history_list", {}, ctx);
425
+ assert.match(rendered(listed), /→ older: \{"before_seq":\d+\}/, "the footer prints the exact call to page older");
426
+ const windows = resultData(await call(captured, "history_windows", {}, ctx));
427
+ assert.equal(windows.windows.length, 2);
428
+ const previous = page(await call(captured, "history_list", { window_id: "@previous" }, ctx));
429
+ assert.ok(previous.items.length > 0 && previous.items.every((item) => item.window_id === windows.windows[0].window_id), "@previous names the window before the current one");
430
+ const previousQuery = page(await call(captured, "history_list", { query: "older window", window_id: "@previous" }, ctx));
431
+ assert.ok(previousQuery.items.length > 0, "a query resolves the alias too");
432
+ toolCall(session, "t1", "bash", { command: "ls" });
433
+ toolResult(session, "t1", "bash", "done");
434
+ appendText(session, "user", "after tools");
435
+ const folded = await call(captured, "history_list", {}, ctx);
436
+ assert.match(rendered(folded), /→ expand: \{"after_seq":\d+,"before_seq":\d+,"from":"oldest","roles":\["tool","context"\]\}/, "a folded row prints its own expand recipe");
437
+ appendText(session, "user", "needle read target");
438
+ const hits = page(await call(captured, "history_list", { query: "needle read target" }, ctx));
439
+ const read = await call(captured, "history_read", { seq: hits.items[0].seq }, ctx);
440
+ assert.match(rendered(read), /neighborhood → `history_list`\(\{"after_seq":\d+,"before_seq":\d+\}\)/, "a read prints the call for surrounding events");
441
+ const solo = manager();
442
+ const soloCaptured = makeExtension(solo);
443
+ appendText(solo, "user", "only window");
444
+ const soloWindows = resultData(await call(soloCaptured, "history_windows", {}, context(solo)));
445
+ const noPrevious = resultError(await call(soloCaptured, "history_list", { window_id: "@previous" }, context(solo)));
446
+ assert.equal(noPrevious.code, "unknown_window_id");
447
+ assert.match(noPrevious.message, /@previous/);
448
+ assert.match(noPrevious.message, new RegExp(`; known: ${soloWindows.windows[0].window_id}$`), "the refusal names the window the session does have");
449
+ });
450
+ test("compaction summary becomes context and is folded in the default list", async () => {
451
+ const session = manager();
452
+ const captured = makeExtension(session);
453
+ const ctx = context(session);
454
+ appendText(session, "user", "before checkpoint");
455
+ session.appendCompaction("summary needle", session.getLeafId(), 100);
456
+ appendText(session, "assistant", "after checkpoint");
457
+ const regular = page(await call(captured, "history_list", {}, ctx));
458
+ assert.deepEqual(regular.items.map((item) => item.folded ? "folded" : item.role), ["user", "folded", "assistant"]);
459
+ const folded = regular.items[1];
460
+ assert.equal(folded.count, 1);
461
+ assert.deepEqual(folded.tools, {});
462
+ const contextItems = page(await call(captured, "history_list", { roles: ["context"] }, ctx));
463
+ assert.deepEqual(contextItems.items.map((item) => [item.role, item.content]), [["context", "summary needle"]]);
464
+ });
465
+ test("a query covers every role, carries match offsets and refuses an empty literal", async () => {
466
+ const session = manager();
467
+ const captured = makeExtension(session);
468
+ const ctx = context(session);
469
+ appendText(session, "user", "visible needle");
470
+ session.appendCustomMessageEntry("notesoup/boot", "developer needle", false);
471
+ appendText(session, "assistant", "assistant needle");
472
+ const all = page(await call(captured, "history_list", { query: "needle" }, ctx));
473
+ assert.deepEqual(all.items.map((item) => item.role), ["user", "context", "assistant"]);
474
+ assert.ok(all.items.every((item) => typeof item.seq === "number" && typeof item.offset_chars === "number"));
475
+ const developers = page(await call(captured, "history_list", { query: "needle", roles: ["context"] }, ctx));
476
+ assert.deepEqual(developers.items.map((item) => item.role), ["context"]);
477
+ assert.equal("custom_type" in developers.items[0], false);
478
+ const first = page(await call(captured, "history_list", { query: "needle", after_seq: 1, limit: 1, from: "oldest" }, ctx));
479
+ assert.deepEqual(first.items.map((item) => item.seq), [2]);
480
+ assert.deepEqual(first.page_newer, { after_seq: 2, from: "oldest" });
481
+ const next = page(await call(captured, "history_list", { query: "needle", ...first.page_newer, limit: 2 }, ctx));
482
+ assert.deepEqual(next.items.map((item) => item.seq), [3]);
483
+ const absent = await call(captured, "history_list", { query: "absent" }, ctx);
484
+ assert.deepEqual(page(absent).items, []);
485
+ assert.equal(rendered(absent), "no events match this selection", "an empty page says so instead of rendering nothing");
486
+ assert.deepEqual(resultError(await call(captured, "history_list", { query: "" }, ctx)).code, "invalid_query");
487
+ });
488
+ test("page_older and page_newer round-trip a session with no duplicates and no gaps", async () => {
489
+ const session = manager();
490
+ const captured = makeExtension(session);
491
+ const ctx = context(session);
492
+ for (let seq = 1; seq <= 10; seq++)
493
+ appendText(session, "user", `needle ${seq}`);
494
+ const forward = [];
495
+ let current = page(await call(captured, "history_list", { query: "needle", from: "oldest", limit: 3 }, ctx));
496
+ assert.deepEqual(current.items.map((item) => item.seq), [1, 2, 3]);
497
+ assert.equal(current.page_older, null, "the first page in `from` oldest has nothing older");
498
+ assert.deepEqual(current.page_newer, { after_seq: 3, from: "oldest" });
499
+ forward.push(...current.items.map((item) => item.seq));
500
+ while (current.page_newer !== null) {
501
+ const cursor = current.page_newer;
502
+ current = page(await call(captured, "history_list", { query: "needle", ...cursor, limit: 3 }, ctx));
503
+ forward.push(...current.items.map((item) => item.seq));
504
+ }
505
+ assert.deepEqual(forward, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "page_newer visits every event exactly once, in order");
506
+ const backward = [];
507
+ current = page(await call(captured, "history_list", { query: "needle", limit: 3 }, ctx));
508
+ assert.deepEqual(current.items.map((item) => item.seq), [8, 9, 10]);
509
+ assert.deepEqual(current.page_older, { before_seq: 8 });
510
+ backward.push(...current.items.map((item) => item.seq));
511
+ while (current.page_older !== null) {
512
+ const cursor = current.page_older;
513
+ current = page(await call(captured, "history_list", { query: "needle", ...cursor, limit: 3 }, ctx));
514
+ backward.push(...current.items.map((item) => item.seq));
515
+ }
516
+ assert.deepEqual(backward, [8, 9, 10, 5, 6, 7, 2, 3, 4, 1], "page_older walks back with no duplicates and no gaps");
517
+ assert.equal(current.page_older, null);
518
+ });
519
+ test("query previews start at case-insensitive literal matches and offsets read the same Unicode document", async () => {
520
+ const session = manager();
521
+ const captured = makeExtension(session);
522
+ const ctx = context(session);
523
+ const prefix = "šŸ˜€Ä°".repeat(1000);
524
+ appendText(session, "user", prefix + "NeEdLe.* trailing");
525
+ const found = page(await call(captured, "history_list", { query: ["absent", "needle.*"], max_chars_per_item: 8 }, ctx));
526
+ assert.equal(found.items.length, 1);
527
+ const hit = found.items[0];
528
+ assert.equal(hit.offset_chars, 2000);
529
+ assert.equal("match_offset_chars" in hit, false);
530
+ assert.equal(hit.content, "NeEdLe.*");
531
+ assert.equal(hit.truncated, true);
532
+ const read = resultRead(await call(captured, "history_read", { seq: hit.seq, offset_chars: hit.offset_chars, max_chars: 8 }, ctx));
533
+ assert.equal(read.content, hit.content);
534
+ const listed = page(await call(captured, "history_list", { max_chars_per_item: 8 }, ctx));
535
+ assert.equal(listed.items.length, 1);
536
+ assert.equal("offset_chars" in listed.items[0], false, "a list preview reports no match offset");
537
+ const atStart = page(await call(captured, "history_list", { query: "šŸ˜€", max_chars_per_item: 4 }, ctx));
538
+ const zero = atStart.items[0];
539
+ assert.equal(zero.offset_chars, 0, "a match at the document start reports an explicit zero offset");
540
+ assert.equal(zero.content, "šŸ˜€Ä°šŸ˜€Ä°", "an explicit zero offset still previews from the document start");
541
+ assert.equal(zero.truncated, true);
542
+ assert.deepEqual(page(await call(captured, "history_list", { query: "needle.+" }, ctx)).items, []);
543
+ });
544
+ test("history_read paginates one document with an accurate limit and a bounded byte cap", async () => {
545
+ const session = manager();
546
+ const captured = makeExtension(session);
547
+ const ctx = context(session);
548
+ const content = "z".repeat(TOOL_OUTPUT_MAX_BYTES * 2);
549
+ appendText(session, "user", content);
550
+ const seq = seqs(await call(captured, "history_list", { max_chars_per_item: 1 }, ctx))[0];
551
+ // 50k requested chars of 64 KiB of text exceeds the byte cap, so the delivered slice stops short
552
+ // of the request rather than at it.
553
+ const full = await call(captured, "history_read", { seq, max_chars: 50_000 }, ctx);
554
+ assertWithinBudget(full, "history_read page");
555
+ const read = resultRead(full);
556
+ assert.equal(read.seq, seq);
557
+ assert.ok(read.window_id.length > 0);
558
+ assert.equal(read.total_chars, content.length);
559
+ assert.equal(read.content, content.slice(0, read.content.length), "the delivered slice is a verbatim prefix");
560
+ assert.equal(read.next_offset_chars !== null, true);
561
+ const text = full.content[0];
562
+ assert.equal(text.type === "text" && text.text.includes("READ WINDOW"), false, "no READ WINDOW block survives");
563
+ assert.match(text.type === "text" ? text.text : "", /\[truncated; continue at offset_chars=\d+\]$/, "a byte-capped window states where to continue");
564
+ const next = resultRead(await call(captured, "history_read", { seq, offset_chars: read.next_offset_chars, max_chars: 50_000 }, ctx));
565
+ assert.equal(read.content + next.content, content.slice(0, read.content.length + next.content.length));
566
+ assert.equal(Array.from(read.content).length, read.next_offset_chars, "the cursor addresses the first undelivered character");
567
+ const limited = resultRead(await call(captured, "history_read", { seq, max_chars: 10 }, ctx));
568
+ assert.equal(limited.content, "z".repeat(10));
569
+ const limitedText = (await call(captured, "history_read", { seq, max_chars: 10 }, ctx)).content[0];
570
+ const limitedSuffix = "\n\n[truncated; continue at offset_chars=10]";
571
+ assert.equal(limitedText.type === "text" && limitedText.text.endsWith(limitedSuffix), true, "a count-limited window states where to resume");
572
+ const tail = resultRead(await call(captured, "history_read", { seq, offset_chars: -10 }, ctx));
573
+ assert.equal(tail.content, "z".repeat(10));
574
+ assert.equal(tail.next_offset_chars, null, "the true end has no continuation");
575
+ const past = resultError(await call(captured, "history_read", { seq, offset_chars: content.length + 1 }, ctx));
576
+ assert.equal(past.code, "invalid_offset");
577
+ assert.match(past.message, new RegExp(`${content.length} chars`), "the refusal names the real length");
578
+ });
579
+ test("history windows expose stable ranges and session identity", async () => {
580
+ const session = manager();
581
+ const captured = makeExtension(session);
582
+ const ctx = context(session);
583
+ appendText(session, "user", "before");
584
+ const windows = resultData(await call(captured, "history_windows", {}, ctx));
585
+ assert.equal(windows.session_id, session.getSessionId());
586
+ assert.equal(windows.windows.length, 1);
587
+ assert.deepEqual(windows.windows[0], { window_id: windows.windows[0].window_id, created_at: null, first_seq: 1, last_seq: 1 });
588
+ });
589
+ test("historyDocument is one deterministic projection of the facts, with no UI header or continuation suffix", async () => {
590
+ const windowId = "w1";
591
+ const items = [
592
+ { seq: 2, windowId, role: "user", text: "hello", createdAt: undefined },
593
+ { seq: 5, windowId, role: "tool_call", text: "", toolName: "read", toolCallId: "call", createdAt: undefined, arguments: { path: "one" } },
594
+ { seq: 6, windowId, role: "tool", text: "šŸ˜€ needle", toolName: "read", toolCallId: "call", createdAt: undefined },
595
+ { seq: 9, windowId, role: "assistant", text: "done", createdAt: undefined },
596
+ ];
597
+ const projection = projectHistory([{ windowId, items }], 12, new Set([2, 5, 6, 9]));
598
+ assert.deepEqual([...projection.pairedResults], [[6, 5]], "the pairing consumes the result address instead of aliasing it");
599
+ assert.deepEqual(projection.windows[0].items.map((event) => event.seq), [2, 5, 9], "projection does not allocate or renumber native addresses");
600
+ const tool = projection.windows[0].items[1];
601
+ assert.equal(historyDocument(tool), 'read {"path":"one"}\n--- output ---\nšŸ˜€ needle');
602
+ assert.equal(historyDocument(projection.windows[0].items[0]), "hello");
603
+ assert.equal(historyDocument(tool).includes("READ WINDOW"), false);
604
+ assert.equal(historyDocument(tool).includes("offset_chars"), false);
605
+ assert.equal(historyDocument(tool).includes("seq "), false, "the document carries no UI identity block");
606
+ const found = await historyList.execute({ query: "NEEDLE" }, projection);
607
+ assert.equal(found.ok, true);
608
+ if (found.ok) {
609
+ const hit = found.data.items[0];
610
+ assert.equal(hit.seq, 5);
611
+ assert.equal(hit.offset_chars, earliestMatchOffsetChars('read {"path":"one"}\n--- output ---\nšŸ˜€ needle', ["NEEDLE"]));
612
+ }
613
+ const consumed = await historyRead.execute({ seq: 6 }, projection);
614
+ assert.equal(consumed.ok, false);
615
+ if (!consumed.ok)
616
+ assert.equal(consumed.error.code, "not_an_event");
617
+ const offBranch = await historyRead.execute({ seq: 12 }, projection);
618
+ assert.equal(offBranch.ok, false);
619
+ if (!offBranch.ok)
620
+ assert.match(offBranch.error.message, /another branch/);
621
+ const unknown = await historyRead.execute({ seq: 13 }, projection);
622
+ assert.equal(unknown.ok, false);
623
+ if (!unknown.ok)
624
+ assert.match(unknown.error.message, /unknown seq/);
625
+ const listed = await historyList.execute({}, projection);
626
+ assert.equal(listed.ok, true);
627
+ if (listed.ok)
628
+ assert.equal(listed.data.items.some((item) => "folded" in item && item.count === 1), true);
629
+ const windows = await historyWindows.execute({}, projection, "session-x");
630
+ assert.equal(windows.ok, true);
631
+ if (windows.ok)
632
+ assert.equal(windows.data.session_id, "session-x");
633
+ });