notesoup 0.0.0-stage → 0.39.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 +91 -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 +21 -0
  8. package/dist/src/boot/text.js +52 -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 +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -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 +104 -0
  58. package/dist/src/notes/store.js +478 -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 +10 -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 +11 -0
  98. package/dist/src/pi/tool-names.js +11 -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 +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -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 +79 -0
  114. package/dist/src/tools/result.js +130 -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 +368 -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 +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -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 +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -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 +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -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 +66 -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 +270 -0
  188. package/src/history/query.ts +147 -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 +497 -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 +12 -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 +13 -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 +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,556 @@
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, historySearch, 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 schemas expose seq and anchor paging, 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
+ const legacyOrderingKey = ["recent", "first"].join("_");
36
+ assert.ok(readSchema.properties?.seq);
37
+ assert.deepEqual(readSchema.required, ["seq"]);
38
+ assert.equal(readSchema.properties?.[legacyItemKey], undefined);
39
+ assert.equal(readSchema.properties?.window_id, undefined);
40
+ const listSchema = captured.tools.get("history_list")?.parameters;
41
+ assert.ok(listSchema.properties?.before);
42
+ assert.ok(listSchema.properties?.after);
43
+ assert.equal(listSchema.properties?.around, undefined);
44
+ assert.ok(listSchema.properties?.roles);
45
+ assert.equal(listSchema.properties?.tool_name, undefined);
46
+ const searchSchema = captured.tools.get("history_search")?.parameters;
47
+ assert.equal(searchSchema.properties?.tool_name, undefined);
48
+ const publicRoles = (listSchema.properties?.roles).items?.anyOf?.map((item) => item.const);
49
+ assert.deepEqual(publicRoles, ["user", "assistant", "tool", "context"]);
50
+ for (const toolName of ["history_list", "history_search"]) {
51
+ const schema = captured.tools.get(toolName).parameters;
52
+ const base = toolName === "history_search" ? { query: "needle" } : {};
53
+ assert.equal(Check(schema, { ...base, roles: ["tool"] }), true);
54
+ for (const invalid of [{ roles: ["tool_call"] }, { roles: ["system"] }, { tool_name: "bash" }, { roles: [] }]) {
55
+ assert.equal(Check(schema, { ...base, ...invalid }), false, `${toolName}: ${JSON.stringify(invalid)}`);
56
+ }
57
+ }
58
+ assert.equal(listSchema.properties?.custom_type, undefined);
59
+ assert.equal(listSchema.properties?.cursor, undefined);
60
+ assert.equal(listSchema.properties?.[legacyOrderingKey], undefined);
61
+ const windowsSchema = captured.tools.get("history_windows")?.parameters;
62
+ assert.deepEqual(Object.keys(windowsSchema.properties ?? []), []);
63
+ const notesSchema = captured.tools.get("notes_list")?.parameters;
64
+ assert.equal(notesSchema.properties?.cursor, undefined);
65
+ assert.ok(notesSchema.properties?.limit);
66
+ const notesSearchSchema = captured.tools.get("notes_search")?.parameters;
67
+ assert.equal(notesSearchSchema.properties?.cursor, undefined);
68
+ assert.ok(notesSearchSchema.properties?.limit);
69
+ });
70
+ test("every history operation declares a result schema its own payload satisfies", async () => {
71
+ const session = manager();
72
+ const captured = makeExtension(session);
73
+ const ctx = context(session);
74
+ appendText(session, "user", "hello");
75
+ toolCall(session, "call-1", "bash", { command: "pwd" });
76
+ toolResult(session, "call-1", "bash", "/tmp");
77
+ for (const toolName of ["history_windows", "history_list", "history_search", "history_read"]) {
78
+ const operation = { history_windows: historyWindows, history_list: historyList, history_search: historySearch, history_read: historyRead }[toolName];
79
+ const result = await call(captured, toolName, toolName === "history_read" ? { seq: 1 } : toolName === "history_search" ? { query: "hello" } : {}, ctx);
80
+ const structured = result.structuredContent;
81
+ assert.ok(structured !== undefined, `${toolName} carries a structured outcome`);
82
+ assert.equal(Check(operation.outputSchema, structured), true, `${toolName} payload satisfies its own outputSchema`);
83
+ assertWithinBudget(result, `${toolName} page`);
84
+ }
85
+ const conversation = await call(captured, "history_list", {}, ctx);
86
+ assert.equal(Check(historyList.outputSchema, conversation.structuredContent), true);
87
+ assert.equal(Check(historySearch.outputSchema, conversation.structuredContent), false, "search schema excludes list-only folds");
88
+ const refusal = await call(captured, "history_read", { seq: 999 }, ctx);
89
+ assert.equal(Check(historyRead.outputSchema, refusal.structuredContent), true, "a refusal satisfies the same result schema");
90
+ });
91
+ test("seq is stable across branch changes, abandoned entries stay unreadable, and a paired result seq is refused precisely", async () => {
92
+ const session = manager();
93
+ const captured = makeExtension(session);
94
+ const ctx = context(session);
95
+ const firstId = appendText(session, "user", "first");
96
+ const abandonedId = appendText(session, "assistant", "abandoned reply");
97
+ const before = page(await call(captured, "history_list", { roles: ["user", "assistant"] }, ctx));
98
+ assert.deepEqual(before.items.map((item) => [item.seq, item.content]), [[1, "first"], [2, "abandoned reply"]]);
99
+ session.branch(firstId);
100
+ const branchId = appendText(session, "user", "new branch");
101
+ const after = page(await call(captured, "history_list", { roles: ["user", "assistant"] }, ctx));
102
+ assert.deepEqual(after.items.map((item) => [item.seq, item.content]), [[1, "first"], [3, "new branch"]]);
103
+ assert.equal(branchId !== abandonedId, true);
104
+ const offBranch = resultError(await call(captured, "history_read", { seq: 2 }, ctx));
105
+ assert.equal(offBranch.code, "not_on_branch");
106
+ assert.match(offBranch.message, /another branch/);
107
+ assert.equal(JSON.stringify(offBranch).includes("abandoned"), false, "the refusal does not leak the abandoned entry's text");
108
+ const unknown = resultError(await call(captured, "history_read", { seq: 4 }, ctx));
109
+ assert.equal(unknown.code, "unknown_seq");
110
+ assert.match(unknown.message, /run 1\.\.3/);
111
+ });
112
+ test("a result address consumed by a pairing names its call instead of serving a second read", async () => {
113
+ const session = manager();
114
+ const captured = makeExtension(session);
115
+ const ctx = context(session);
116
+ toolCall(session, "paired", "edit", { path: "a.md" });
117
+ toolResult(session, "paired", "edit", "edited");
118
+ // The assistant message takes seq 1 and its tool call seq 2; the result at seq 3 is absorbed.
119
+ assert.deepEqual(seqs(await call(captured, "history_list", { roles: ["tool"] }, ctx)), [2], "the pairing is one event at the call's address");
120
+ const consumed = resultError(await call(captured, "history_read", { seq: 3 }, ctx));
121
+ assert.equal(consumed.code, "not_an_event");
122
+ assert.match(consumed.message, /already shown inside the call at seq 2/);
123
+ assert.equal(consumed.details?.read_seq, 2, "the refusal names the address to read instead");
124
+ const callSeq = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
125
+ assert.equal(callSeq.seq, 2);
126
+ assert.equal(callSeq.content, 'edit {"path":"a.md"}\n--- output ---\nedited');
127
+ });
128
+ test("anchor paging is chronological, stable under appends, and supports ranges", async () => {
129
+ const session = manager();
130
+ const captured = makeExtension(session);
131
+ const ctx = context(session);
132
+ for (let index = 1; index <= 5; index++)
133
+ appendText(session, "user", `message-${index}`);
134
+ assert.deepEqual(seqs(await call(captured, "history_list", { limit: 2 }, ctx)), [4, 5]);
135
+ appendText(session, "user", "message-6");
136
+ const older = page(await call(captured, "history_list", { before: 5, limit: 2 }, ctx));
137
+ assert.deepEqual(older.items.map((item) => item.seq), [3, 4]);
138
+ assert.equal(older.older_before, 3);
139
+ assert.equal(older.newer_after, null);
140
+ assert.deepEqual(seqs(await call(captured, "history_list", { after: 5, limit: 2 }, ctx)), [6]);
141
+ for (let index = 7; index <= 10; index++)
142
+ appendText(session, "user", `message-${index}`);
143
+ const range = page(await call(captured, "history_list", { after: 2, before: 10, limit: 3 }, ctx));
144
+ assert.deepEqual(range.items.map((item) => item.seq), [3, 4, 5]);
145
+ assert.equal(range.older_before, null);
146
+ assert.equal(range.newer_after, 5);
147
+ const rangeNext = page(await call(captured, "history_list", { after: range.newer_after, before: 10, limit: 3 }, ctx));
148
+ assert.deepEqual(rangeNext.items.map((item) => item.seq), [6, 7, 8]);
149
+ const rangeLast = page(await call(captured, "history_list", { after: rangeNext.newer_after, before: 10, limit: 3 }, ctx));
150
+ assert.deepEqual(rangeLast.items.map((item) => item.seq), [9]);
151
+ assert.equal(rangeLast.older_before, null);
152
+ assert.equal(rangeLast.newer_after, null);
153
+ assert.equal("has_older" in rangeLast, false);
154
+ assert.equal("has_newer" in rangeLast, false);
155
+ assert.equal((captured.tools.get("history_list")?.parameters).properties?.before?.minimum, undefined, "bounds take any integer; the implementation treats out-of-range values as empty/open");
156
+ assert.equal((captured.tools.get("history_list")?.parameters).properties?.after?.minimum, undefined);
157
+ });
158
+ test("a one-row page budget admits the newest candidate first", () => {
159
+ const windowId = "w1";
160
+ const items = [1, 2, 3].map((seq) => ({ seq, windowId, role: "user", text: `message-${seq}`, createdAt: undefined }));
161
+ const projection = projectHistory([{ windowId, items }], 12, new Set([1, 2, 3]));
162
+ const candidates = projection.windows[0].items.map((event) => ({ event }));
163
+ const newestFirst = (fitsRows) => {
164
+ const outcome = selectPage(projection, { limit: 3 }, candidates, false, (candidate) => candidate.items.length <= fitsRows, 200);
165
+ assert.equal(outcome.ok, true);
166
+ return outcome.ok ? outcome.data.items.map((item) => ("folded" in item ? item.first_seq : item.seq)) : [];
167
+ };
168
+ assert.deepEqual(newestFirst(1), [3], "a budget for one row admits the newest candidate, not the oldest");
169
+ assert.deepEqual(newestFirst(2), [2, 3], "a truncated prefix is the newest rows, delivered in chronological order");
170
+ });
171
+ test("conversation view folds tools and injected messages, while explicit roles expand them", async () => {
172
+ const session = manager();
173
+ const captured = makeExtension(session);
174
+ const ctx = context(session);
175
+ appendText(session, "user", "please inspect");
176
+ const turnId = append(session, {
177
+ role: "assistant",
178
+ content: [
179
+ { type: "text", text: "I will inspect" },
180
+ { type: "toolCall", id: "tc-1", name: "bash", arguments: { command: "pwd" } },
181
+ { type: "toolCall", id: "tc-2", name: "read", arguments: { path: "README.md" } },
182
+ ],
183
+ stopReason: "toolUse",
184
+ timestamp: Date.now(),
185
+ });
186
+ toolResult(session, "tc-1", "bash", "ok");
187
+ toolResult(session, "tc-2", "read", "contents");
188
+ session.appendCustomMessageEntry("square", "injected event", false);
189
+ append(session, { role: "assistant", content: [], stopReason: "toolUse", timestamp: Date.now() });
190
+ const conversation = page(await call(captured, "history_list", {}, ctx));
191
+ const legacyItemKey = ["item", "id"].join("_");
192
+ assert.equal(conversation.items.some((item) => item.folded === true), true);
193
+ assert.equal(conversation.items.some((item) => item.role === "developer"), false);
194
+ assert.equal(conversation.items.some((item) => item.role === "tool"), false);
195
+ assert.equal(conversation.items.some((item) => item.role === "assistant" && item.total_chars === 0), false);
196
+ assert.equal(conversation.items.every((item) => legacyItemKey in item === false), true);
197
+ const folded = conversation.items.find((item) => item.folded === true);
198
+ assert.equal(folded.count, 3, "two tool events and one injected context are folded, not the empty assistant message");
199
+ assert.deepEqual(folded.tools, { bash: 1, read: 1 });
200
+ assert.equal("custom_types" in folded, false);
201
+ const empty = page(await call(captured, "history_list", { roles: ["context"], before: 2 }, ctx));
202
+ assert.deepEqual(empty.items, []);
203
+ const hiddenOnly = page(await call(captured, "history_list", { after: 2, before: 6 }, ctx));
204
+ assert.deepEqual(hiddenOnly.items, [{ folded: true, first_seq: 3, last_seq: 4, count: 2, tools: { bash: 1, read: 1 } }]);
205
+ const expanded = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
206
+ assert.deepEqual(expanded.items.map((item) => [item.seq, item.role, item.tool, item.tool_status]), [[3, "tool", "bash", "ok"], [4, "tool", "read", "ok"]]);
207
+ assert.equal(expanded.items[0].content, 'bash {"command":"pwd"}\n--- output ---\nok');
208
+ assert.equal(expanded.items[1].content, 'read {"path":"README.md"}\n--- output ---\ncontents');
209
+ assert.equal(expanded.items.every((item) => !("call_seq" in item || "result_seq" in item || "tool_name" in item)), true);
210
+ assert.deepEqual(seqs(await call(captured, "history_search", { query: "bash", roles: ["tool"] }, ctx)), [3]);
211
+ const injected = page(await call(captured, "history_list", { roles: ["context"] }, ctx));
212
+ assert.deepEqual(injected.items.map((item) => [item.role, item.content]), [["context", "injected event"]]);
213
+ assert.equal(turnId.length > 0, true);
214
+ });
215
+ test("tool summaries and documents preserve pending, errored, and orphan runs", async () => {
216
+ const session = manager();
217
+ const captured = makeExtension(session);
218
+ const ctx = context(session);
219
+ append(session, { role: "assistant", content: [{ type: "toolCall", id: "paired", name: "edit", arguments: { path: "šŸ˜€.md", oldText: "before" } }], stopReason: "toolUse", timestamp: Date.now() });
220
+ toolResult(session, "paired", "edit", "replacement OK", { isError: true });
221
+ append(session, { role: "assistant", content: [{ type: "toolCall", id: "pending", name: "edit", arguments: { path: "pending.md" } }], stopReason: "toolUse", timestamp: Date.now() });
222
+ toolResult(session, "orphan", "edit", "orphan output", {
223
+ nestedCalls: { complete: true, calls: [{ id: "orphan/1", name: "read", arguments: { path: "orphan-nested.md" }, status: "ok" }] },
224
+ });
225
+ const events = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
226
+ // The orphan result ran and succeeded; nothing about its missing call changes that. Only the
227
+ // pending call, which no result ended, is unfinished.
228
+ assert.deepEqual(events.items.map((item) => [item.seq, item.tool_status]), [[2, "error"], [5, "unfinished"], [6, "ok"]]);
229
+ assert.equal(events.items[0].content, 'edit {"path":"šŸ˜€.md","oldText":"before"}\n--- output ---\nreplacement OK');
230
+ assert.equal(events.items[1].content, 'edit {"path":"pending.md"}', "an unfinished call claims no output");
231
+ 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");
232
+ assert.deepEqual(events.items[2].nested_calls, { call_count: 1, complete: true }, "an orphan's nested records are counted on its row like any other run's");
233
+ const errored = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
234
+ assert.equal(errored.tool, "edit");
235
+ assert.equal(errored.tool_status, "error");
236
+ assert.equal(errored.text, events.items[0].content);
237
+ assert.equal("execution" in errored, false, "arguments are delivered once, in the document");
238
+ const pending = resultRead(await call(captured, "history_read", { seq: 5 }, ctx));
239
+ assert.equal(pending.tool_status, "unfinished");
240
+ const orphan = resultRead(await call(captured, "history_read", { seq: 6 }, ctx));
241
+ assert.deepEqual(orphan.nested_calls, { call_count: 1, complete: true });
242
+ assert.equal(orphan.text, events.items[2].content, "an orphan's nested evidence stays readable despite the missing call");
243
+ assert.deepEqual(seqs(await call(captured, "history_search", { query: "edit", roles: ["tool"] }, ctx)), [2, 5, 6]);
244
+ assert.deepEqual(seqs(await call(captured, "history_search", { query: "pending.md", roles: ["tool"] }, ctx)), [5]);
245
+ assert.deepEqual(seqs(await call(captured, "history_search", { query: "orphan output", roles: ["tool"] }, ctx)), [6]);
246
+ assert.deepEqual(seqs(await call(captured, "history_search", { query: "orphan-nested.md", roles: ["tool"] }, ctx)), [6], "nested evidence is searchable even when the call it belongs to was never recorded");
247
+ });
248
+ test("native nested-call records are searchable, readable, and never gain a result or an address", async () => {
249
+ const session = manager();
250
+ const captured = makeExtension(session);
251
+ const ctx = context(session);
252
+ toolCall(session, "codemode", "codemode", { script: "run()" });
253
+ toolResult(session, "codemode", "codemode", "script finished", {
254
+ nestedCalls: {
255
+ complete: false,
256
+ calls: [
257
+ { id: "codemode/1", name: "read", arguments: { path: "nested-needle.md" }, status: "ok", durationMs: 12 },
258
+ { id: "codemode/2", name: "bash", status: "error", durationMs: 4, error: "exit 1" },
259
+ { id: "codemode/3", name: "spawn", status: "unfinished" },
260
+ ],
261
+ },
262
+ });
263
+ const found = page(await call(captured, "history_search", { query: "nested-needle" }, ctx));
264
+ assert.deepEqual(found.items.map((item) => item.seq), [2], "nested arguments are part of the searchable document");
265
+ const row = found.items[0];
266
+ assert.deepEqual(row.nested_calls, { call_count: 3, complete: false }, "the list row reports counts and the host's own completeness flag");
267
+ const read = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
268
+ assert.deepEqual(read.nested_calls, { call_count: 3, complete: false }, "the host's completeness flag stays unchanged");
269
+ 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)');
270
+ assert.equal(read.next_offset_chars, null);
271
+ assert.equal("execution" in read, false, "nested records are not duplicated outside the document");
272
+ const rendered = read.content;
273
+ 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"])]]) {
274
+ assert.ok(offset >= 0 && rendered.slice(offset).startsWith(needle), `nested evidence "${needle}" is readable in the document`);
275
+ }
276
+ });
277
+ test("absent nested calls mean unavailable, not a known-empty record", async () => {
278
+ const session = manager();
279
+ const captured = makeExtension(session);
280
+ const ctx = context(session);
281
+ toolCall(session, "plain", "read", { path: "a.md" });
282
+ toolResult(session, "plain", "read", "contents");
283
+ const listed = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
284
+ assert.equal("nested_calls" in listed.items[0], false, "no record is reported as empty when none was recorded");
285
+ const read = resultRead(await call(captured, "history_read", { seq: 2 }, ctx));
286
+ assert.equal("nested_calls" in read, false);
287
+ assert.equal(read.content.includes("nested calls"), false);
288
+ });
289
+ test("oversized arguments and long nested records remain fully pageable and searchable", async () => {
290
+ const session = manager();
291
+ const captured = makeExtension(session);
292
+ const ctx = context(session);
293
+ const huge = "x".repeat(TOOL_OUTPUT_MAX_BYTES * 2);
294
+ toolCall(session, "big", "write", { path: "big.md", content: huge });
295
+ toolResult(session, "big", "write", "written", {
296
+ nestedCalls: {
297
+ complete: true,
298
+ calls: Array.from({ length: 400 }, (_, index) => ({ id: `big/${index}`, name: "read", arguments: { path: `p${index}.md` }, status: "ok", durationMs: 1 })),
299
+ },
300
+ });
301
+ const listed = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
302
+ assert.deepEqual(listed.items[0].nested_calls, { call_count: 400, complete: true }, "the page row counts every recorded call, not only the records one read can carry");
303
+ let read = resultRead(await call(captured, "history_read", { seq: 2, limit_chars: 50_000 }, ctx));
304
+ assert.deepEqual(read.nested_calls, { call_count: 400, complete: true });
305
+ assert.equal(read.limited_by, "bytes");
306
+ let document = read.text;
307
+ while (read.next_offset_chars !== null) {
308
+ const next = read.next_offset_chars;
309
+ const result = await call(captured, "history_read", { seq: 2, offset_chars: next, limit_chars: 50_000 }, ctx);
310
+ assertWithinBudget(result, "bounded document page");
311
+ read = resultRead(result);
312
+ assert.equal(read.offset_chars, next);
313
+ assert.ok(read.text.length > 0, "every continuation makes progress");
314
+ document += read.text;
315
+ }
316
+ const expectedCalls = Array.from({ length: 400 }, (_, index) => `- big/${index} read [ok] 1ms {"path":"p${index}.md"}`).join("\n");
317
+ 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");
318
+ assertWithinBudget(await call(captured, "history_read", { seq: 2 }, ctx), "bounded first read");
319
+ assertWithinBudget(await call(captured, "history_list", { roles: ["tool"] }, ctx), "bounded list row");
320
+ const searchHit = page(await call(captured, "history_search", { query: "big.md", max_chars_per_item: 40 }, ctx));
321
+ assert.deepEqual(searchHit.items.map((item) => item.seq), [2], "the document still carries the real arguments, so search still finds them");
322
+ const late = page(await call(captured, "history_search", { query: "p399.md" }, ctx)).items[0];
323
+ assert.equal(late.seq, 2);
324
+ const resumed = resultRead(await call(captured, "history_read", { seq: 2, offset_chars: late.offset_chars }, ctx));
325
+ assert.ok(resumed.text.startsWith("p399.md"), "search can jump directly to evidence beyond the first read");
326
+ });
327
+ test("standalone bash execution retains command, output, and truncation path", async () => {
328
+ const session = manager();
329
+ const captured = makeExtension(session);
330
+ const ctx = context(session);
331
+ append(session, { role: "bashExecution", command: "echo needle", output: "needle output", exitCode: 0, cancelled: false, truncated: true, fullOutputPath: "/tmp/bash-output.txt", timestamp: Date.now() });
332
+ const found = page(await call(captured, "history_list", { roles: ["tool"] }, ctx));
333
+ assert.equal(found.items.length, 1);
334
+ assert.deepEqual(found.items[0], {
335
+ seq: 1,
336
+ window_id: found.items[0].window_id,
337
+ role: "tool",
338
+ created_at: found.items[0].created_at,
339
+ tool: "bash",
340
+ tool_status: "ok",
341
+ output_truncated: true,
342
+ full_output_path: "/tmp/bash-output.txt",
343
+ truncated: false,
344
+ total_chars: 59,
345
+ content: 'bash {"command":"echo needle"}\n--- output ---\nneedle output',
346
+ });
347
+ const query = page(await call(captured, "history_search", { roles: ["tool"], query: "NEEDLE OUTPUT" }, ctx));
348
+ assert.deepEqual(query.items.map((item) => item.seq), [1]);
349
+ const read = resultRead(await call(captured, "history_read", { seq: 1, offset_chars: query.items[0].offset_chars }, ctx));
350
+ assert.equal(read.content, "needle output");
351
+ assert.equal(read.seq, 1);
352
+ });
353
+ test("list renders paging and fold recipes, read renders a neighborhood call, and @previous resolves", async () => {
354
+ const session = manager();
355
+ const captured = makeExtension(session);
356
+ const ctx = context(session);
357
+ for (let i = 0; i < 30; i++)
358
+ appendText(session, "user", `older window ${i}`);
359
+ session.appendCustomEntry("notesoup/reset-marker", { windowId: "pcw:test:w2" });
360
+ appendText(session, "user", "current window");
361
+ const listed = await call(captured, "history_list", {}, ctx);
362
+ assert.match(rendered(listed), /→ older: \{"before":\d+\}/, "the footer prints the exact call to page older");
363
+ const windows = resultData(await call(captured, "history_windows", {}, ctx));
364
+ assert.equal(windows.windows.length, 2);
365
+ const previous = page(await call(captured, "history_list", { window_id: "@previous" }, ctx));
366
+ 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");
367
+ const previousSearch = page(await call(captured, "history_search", { query: "older window", window_id: "@previous" }, ctx));
368
+ assert.ok(previousSearch.items.length > 0, "search resolves the alias too");
369
+ toolCall(session, "t1", "bash", { command: "ls" });
370
+ toolResult(session, "t1", "bash", "done");
371
+ appendText(session, "user", "after tools");
372
+ const folded = await call(captured, "history_list", {}, ctx);
373
+ assert.match(rendered(folded), /→ expand: \{"after":\d+,"before":\d+,"roles":\["tool","context"\]\}/, "a folded row prints its own expand recipe");
374
+ appendText(session, "user", "needle read target");
375
+ const hits = page(await call(captured, "history_search", { query: "needle read target" }, ctx));
376
+ const read = await call(captured, "history_read", { seq: hits.items[0].seq }, ctx);
377
+ assert.match(rendered(read), /neighborhood → history_list\(\{"after":\d+,"before":\d+\}\)/, "a read prints the call for surrounding events");
378
+ const solo = manager();
379
+ const soloCaptured = makeExtension(solo);
380
+ appendText(solo, "user", "only window");
381
+ const noPrevious = resultError(await call(soloCaptured, "history_list", { window_id: "@previous" }, context(solo)));
382
+ assert.equal(noPrevious.code, "unknown_window_id");
383
+ assert.match(noPrevious.message, /@previous/);
384
+ });
385
+ test("compaction summary becomes context and is folded in the default list", async () => {
386
+ const session = manager();
387
+ const captured = makeExtension(session);
388
+ const ctx = context(session);
389
+ appendText(session, "user", "before checkpoint");
390
+ session.appendCompaction("summary needle", session.getLeafId(), 100);
391
+ appendText(session, "assistant", "after checkpoint");
392
+ const regular = page(await call(captured, "history_list", {}, ctx));
393
+ assert.deepEqual(regular.items.map((item) => item.folded ? "folded" : item.role), ["user", "folded", "assistant"]);
394
+ const folded = regular.items[1];
395
+ assert.equal(folded.count, 1);
396
+ assert.deepEqual(folded.tools, {});
397
+ const contextItems = page(await call(captured, "history_list", { roles: ["context"] }, ctx));
398
+ assert.deepEqual(contextItems.items.map((item) => [item.role, item.content]), [["context", "summary needle"]]);
399
+ });
400
+ test("search covers all roles, supports filters and anchor paging", async () => {
401
+ const session = manager();
402
+ const captured = makeExtension(session);
403
+ const ctx = context(session);
404
+ appendText(session, "user", "visible needle");
405
+ session.appendCustomMessageEntry("notesoup/boot", "developer needle", false);
406
+ appendText(session, "assistant", "assistant needle");
407
+ const all = page(await call(captured, "history_search", { query: "needle" }, ctx));
408
+ assert.deepEqual(all.items.map((item) => item.role), ["user", "context", "assistant"]);
409
+ assert.ok(all.items.every((item) => typeof item.seq === "number" && typeof item.offset_chars === "number"));
410
+ const developers = page(await call(captured, "history_search", { query: "needle", roles: ["context"] }, ctx));
411
+ assert.deepEqual(developers.items.map((item) => item.role), ["context"]);
412
+ assert.equal("custom_type" in developers.items[0], false);
413
+ const first = page(await call(captured, "history_search", { query: "needle", after: 1, limit: 1 }, ctx));
414
+ assert.equal(first.items.length, 1);
415
+ const next = page(await call(captured, "history_search", { query: "needle", after: first.items[0].seq, limit: 2 }, ctx));
416
+ assert.equal(next.items.length, 1);
417
+ const absent = await call(captured, "history_search", { query: "absent" }, ctx);
418
+ assert.deepEqual(page(absent).items, []);
419
+ assert.equal(rendered(absent), "no events match this selection", "an empty page says so instead of rendering nothing");
420
+ assert.deepEqual(resultError(await call(captured, "history_search", { query: "" }, ctx)).code, "invalid_query");
421
+ });
422
+ test("search keeps exclusive bounds and follows newer_after through three pages", async () => {
423
+ const session = manager();
424
+ const captured = makeExtension(session);
425
+ const ctx = context(session);
426
+ for (let seq = 1; seq <= 10; seq++)
427
+ appendText(session, "user", `needle ${seq}`);
428
+ const first = page(await call(captured, "history_search", { query: "needle", after: 2, before: 10, limit: 3 }, ctx));
429
+ assert.deepEqual(first.items.map((item) => item.seq), [3, 4, 5]);
430
+ assert.equal(first.older_before, null);
431
+ assert.equal(first.newer_after, 5);
432
+ const second = page(await call(captured, "history_search", { query: "needle", after: first.newer_after, before: 10, limit: 3 }, ctx));
433
+ assert.deepEqual(second.items.map((item) => item.seq), [6, 7, 8]);
434
+ const third = page(await call(captured, "history_search", { query: "needle", after: second.newer_after, before: 10, limit: 3 }, ctx));
435
+ assert.deepEqual(third.items.map((item) => item.seq), [9]);
436
+ assert.equal(third.newer_after, null);
437
+ });
438
+ test("search previews start at case-insensitive literal matches and offsets read the same Unicode document", async () => {
439
+ const session = manager();
440
+ const captured = makeExtension(session);
441
+ const ctx = context(session);
442
+ const prefix = "šŸ˜€Ä°".repeat(1000);
443
+ appendText(session, "user", prefix + "NeEdLe.* trailing");
444
+ const found = page(await call(captured, "history_search", { query: ["absent", "needle.*"], max_chars_per_item: 8 }, ctx));
445
+ assert.equal(found.items.length, 1);
446
+ const hit = found.items[0];
447
+ assert.equal(hit.offset_chars, 2000);
448
+ assert.equal("match_offset_chars" in hit, false);
449
+ assert.equal(hit.content, "NeEdLe.*");
450
+ assert.equal(hit.truncated, true);
451
+ assert.equal(hit.total_chars, 2017);
452
+ const read = resultRead(await call(captured, "history_read", { seq: hit.seq, offset_chars: hit.offset_chars, limit_chars: 8 }, ctx));
453
+ assert.equal(read.content, hit.content);
454
+ const listed = page(await call(captured, "history_list", { max_chars_per_item: 8 }, ctx));
455
+ assert.equal(listed.items.length, 1);
456
+ assert.equal("offset_chars" in listed.items[0], false, "a list preview reports no match offset");
457
+ const atStart = page(await call(captured, "history_search", { query: "šŸ˜€", max_chars_per_item: 4 }, ctx));
458
+ const zero = atStart.items[0];
459
+ assert.equal(zero.offset_chars, 0, "a match at the document start reports an explicit zero offset");
460
+ assert.equal(zero.content, "šŸ˜€Ä°šŸ˜€Ä°", "an explicit zero offset still previews from the document start");
461
+ assert.equal(zero.truncated, true);
462
+ assert.equal(zero.total_chars, 2017);
463
+ assert.deepEqual(page(await call(captured, "history_search", { query: "needle.+" }, ctx)).items, []);
464
+ });
465
+ test("history_read paginates one document with an accurate limit and a bounded byte cap", async () => {
466
+ const session = manager();
467
+ const captured = makeExtension(session);
468
+ const ctx = context(session);
469
+ const content = "z".repeat(TOOL_OUTPUT_MAX_BYTES * 2);
470
+ appendText(session, "user", content);
471
+ const seq = seqs(await call(captured, "history_list", { max_chars_per_item: 1 }, ctx))[0];
472
+ // 50k requested chars of 64 KiB of text exceeds the byte cap, so the delivered slice stops short
473
+ // of the request rather than at it.
474
+ const full = await call(captured, "history_read", { seq, limit_chars: 50_000 }, ctx);
475
+ assertWithinBudget(full, "history_read page");
476
+ const read = resultRead(full);
477
+ assert.equal(read.seq, seq);
478
+ assert.ok(read.window_id.length > 0);
479
+ assert.equal(read.total_chars, content.length);
480
+ assert.equal(read.content, content.slice(0, read.content.length), "the delivered slice is a verbatim prefix");
481
+ assert.equal(read.next_offset_chars !== null, true);
482
+ const text = full.content[0];
483
+ assert.equal(text.type === "text" && text.text.includes("READ WINDOW"), false, "no READ WINDOW block survives");
484
+ assert.match(text.type === "text" ? text.text : "", /\(32KB limit\)\. Use offset_chars=\d+ to continue\.\]$/, "the byte cap is stated as a continuation suffix");
485
+ const next = resultRead(await call(captured, "history_read", { seq, offset_chars: read.next_offset_chars, limit_chars: 50_000 }, ctx));
486
+ assert.equal(read.content + next.content, content.slice(0, read.content.length + next.content.length));
487
+ assert.equal(read.next_offset_chars, next.offset_chars, "the cursor addresses the first undelivered character");
488
+ const limited = resultRead(await call(captured, "history_read", { seq, limit_chars: 10 }, ctx));
489
+ assert.equal(limited.limited_by, "limit", "a window inside the budget stops at the requested count");
490
+ assert.equal(limited.content, "z".repeat(10));
491
+ const limitedText = (await call(captured, "history_read", { seq, limit_chars: 10 }, ctx)).content[0];
492
+ const limitedSuffix = `\n\n[${content.length - 10} more characters. Use offset_chars=10 to continue.]`;
493
+ assert.equal(limitedText.type === "text" && limitedText.text.endsWith(limitedSuffix), true, "a count-limited window states what remains and where to resume");
494
+ const tail = resultRead(await call(captured, "history_read", { seq, offset_chars: -10 }, ctx));
495
+ assert.equal(tail.offset_chars, content.length - 10);
496
+ assert.equal(tail.content, "z".repeat(10));
497
+ assert.equal(tail.next_offset_chars, null, "the true end has no continuation");
498
+ const past = resultError(await call(captured, "history_read", { seq, offset_chars: content.length + 1 }, ctx));
499
+ assert.equal(past.code, "invalid_offset");
500
+ assert.equal(past.details?.total_chars, content.length);
501
+ });
502
+ test("history windows expose stable ranges and session identity", async () => {
503
+ const session = manager();
504
+ const captured = makeExtension(session);
505
+ const ctx = context(session);
506
+ appendText(session, "user", "before");
507
+ const windows = resultData(await call(captured, "history_windows", {}, ctx));
508
+ assert.equal(windows.session_id, session.getSessionId());
509
+ assert.equal(windows.windows.length, 1);
510
+ assert.deepEqual(windows.windows[0], { window_id: windows.windows[0].window_id, created_at: null, first_seq: 1, last_seq: 1, item_count: 1 });
511
+ });
512
+ test("historyDocument is one deterministic projection of the facts, with no UI header or continuation suffix", async () => {
513
+ const windowId = "w1";
514
+ const items = [
515
+ { seq: 2, windowId, role: "user", text: "hello", createdAt: undefined },
516
+ { seq: 5, windowId, role: "tool_call", text: "", toolName: "read", toolCallId: "call", createdAt: undefined, arguments: { path: "one" } },
517
+ { seq: 6, windowId, role: "tool", text: "šŸ˜€ needle", toolName: "read", toolCallId: "call", createdAt: undefined },
518
+ { seq: 9, windowId, role: "assistant", text: "done", createdAt: undefined },
519
+ ];
520
+ const projection = projectHistory([{ windowId, items }], 12, new Set([2, 5, 6, 9]));
521
+ assert.deepEqual([...projection.pairedResults], [[6, 5]], "the pairing consumes the result address instead of aliasing it");
522
+ assert.deepEqual(projection.windows[0].items.map((event) => event.seq), [2, 5, 9], "projection does not allocate or renumber native addresses");
523
+ const tool = projection.windows[0].items[1];
524
+ assert.equal(historyDocument(tool), 'read {"path":"one"}\n--- output ---\nšŸ˜€ needle');
525
+ assert.equal(historyDocument(projection.windows[0].items[0]), "hello");
526
+ assert.equal(historyDocument(tool).includes("READ WINDOW"), false);
527
+ assert.equal(historyDocument(tool).includes("offset_chars"), false);
528
+ assert.equal(historyDocument(tool).includes("seq "), false, "the document carries no UI identity block");
529
+ const search = await historySearch.execute({ query: "NEEDLE" }, projection);
530
+ assert.equal(search.ok, true);
531
+ if (search.ok) {
532
+ const hit = search.data.items[0];
533
+ assert.equal(hit.seq, 5);
534
+ assert.equal(hit.offset_chars, earliestMatchOffsetChars('read {"path":"one"}\n--- output ---\nšŸ˜€ needle', ["NEEDLE"]));
535
+ }
536
+ const consumed = await historyRead.execute({ seq: 6 }, projection);
537
+ assert.equal(consumed.ok, false);
538
+ if (!consumed.ok)
539
+ assert.equal(consumed.error.code, "not_an_event");
540
+ const offBranch = await historyRead.execute({ seq: 12 }, projection);
541
+ assert.equal(offBranch.ok, false);
542
+ if (!offBranch.ok)
543
+ assert.match(offBranch.error.message, /another branch/);
544
+ const unknown = await historyRead.execute({ seq: 13 }, projection);
545
+ assert.equal(unknown.ok, false);
546
+ if (!unknown.ok)
547
+ assert.match(unknown.error.message, /unknown seq/);
548
+ const listed = await historyList.execute({}, projection);
549
+ assert.equal(listed.ok, true);
550
+ if (listed.ok)
551
+ assert.equal(listed.data.items.some((item) => "folded" in item && item.count === 1), true);
552
+ const windows = await historyWindows.execute({}, projection, "session-x");
553
+ assert.equal(windows.ok, true);
554
+ if (windows.ok)
555
+ assert.equal(windows.data.session_id, "session-x");
556
+ });
@@ -0,0 +1 @@
1
+ export {};