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,300 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { Type } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { loadNotesSnapshot } from "../src/boot/snapshot.js";
9
+ import { renderBootBlock } from "../src/boot/render.js";
10
+ import { HistoryPageItemSchema, HistoryRoleSchema, projectHistory } from "../src/history/history.js";
11
+ import { createNotesStore } from "../src/notes/store.js";
12
+ import { notesWrite, notesUpdate, notesRead } from "../src/tools/notes.js";
13
+ import { historyWindows, historyList, historyRead, historySearch } from "../src/tools/history.js";
14
+ import { historyRoles } from "../src/tools/schema.js";
15
+ import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
16
+ import { ERROR_DETAILS_MAX_BYTES, ERROR_MESSAGE_MAX_CHARS, failure, fitsResult, resultSchema, wireResult, readTextWindow, renderOutcome, renderTextWindow, success, structuredBytes, } from "../src/tools/result.js";
17
+ function identity(t) {
18
+ const home = mkdtempSync(join(tmpdir(), "host-neutral-notes-"));
19
+ t.after(() => rmSync(home, { recursive: true, force: true }));
20
+ return { home, sessionId: "explicit-session", projectKey: "explicit-12345678", agent: "explicit-agent", model: "explicit-model" };
21
+ }
22
+ /** The data of a successful outcome, or a failed assertion naming the refusal. */
23
+ function data(result) {
24
+ assert.ok(result.ok, `expected success, got ${result.ok ? "" : JSON.stringify(result.error)}`);
25
+ return result.data;
26
+ }
27
+ /** The refusal of a failed outcome, or a failed assertion naming the data. */
28
+ function refusal(result) {
29
+ assert.ok(!result.ok, `expected a refusal, got success ${JSON.stringify(result.ok ? result.data : null)}`);
30
+ return result.error;
31
+ }
32
+ const makeData = (window) => ({ header: "identity, metadata, cursors, and a footer".repeat(4), window });
33
+ const renderData = (result) => result.ok ? `${result.data.header}\n${renderTextWindow(result.data.window)}` : renderOutcome(result, () => "");
34
+ const read = (text, offset, limit) => readTextWindow(text, offset, limit, makeData, renderData);
35
+ test("shared boot uses only explicit identity, loader, captured time and logical tool bindings", async (t) => {
36
+ const notesIdentity = identity(t);
37
+ const openedAt = 1_700_000_000_000;
38
+ const scopes = [];
39
+ const snapshot = await loadNotesSnapshot(notesIdentity, openedAt, (scope) => {
40
+ scopes.push(scope);
41
+ if (scope === "human")
42
+ throw Object.assign(new Error("unavailable"), { code: "EIO" });
43
+ return scope === "session" ? [{ address: "checkpoint.md", path: "checkpoint.md", scope, body: "😀", sizeBytes: 4, meta: { scope, origin: "self", createdAt: openedAt, updatedAt: openedAt - 60_000, lastAccessed: openedAt, accessCount: 0 } }] : [];
44
+ });
45
+ assert.deepEqual(scopes, ["session", "project", "human", "agent", "model"]);
46
+ assert.equal(snapshot.openedAt, openedAt);
47
+ const tools = { notes: "memo_*", notesList: "memo_list", history: "archive_*", historyWindows: "archive_windows", historyList: "archive_list", historySearch: "archive_search", historyRead: "archive_read", remaining: "room", wipe: "forget" };
48
+ const block = { agentName: notesIdentity.agent, modelName: notesIdentity.model, firstWindowId: "root", currentWindowId: "next", notes: snapshot, tools };
49
+ const rendered = renderBootBlock(block);
50
+ assert.equal(renderBootBlock(block), rendered);
51
+ assert.ok(rendered.includes("😀\n checkpoint.md · 1m ago"), "a feed entry is the note's own first line over its locator");
52
+ assert.ok(rendered.includes("ask memo_list to try again"));
53
+ assert.equal(/notes_\*|notes_list|history_\*|history_list|history_search|history_read|get_context_remaining|clear_memory/.test(rendered), false);
54
+ });
55
+ test("the shared result module bounds both surfaces and names what a window withheld", () => {
56
+ const text = `${"a".repeat(120)}😀${"b".repeat(30)}`;
57
+ const chars = Array.from(text);
58
+ // The requested count stops the read, and the footer says only that.
59
+ const first = data(read(text, 0, 10));
60
+ assert.equal(first.window.text, chars.slice(0, 10).join(""));
61
+ assert.equal(first.window.limited_by, "limit");
62
+ assert.equal(first.window.next_offset_chars, 10);
63
+ assert.equal(first.window.total_chars, chars.length);
64
+ assert.match(renderData(success(first)), /\[141 more characters\. Use offset_chars=10 to continue\.\]$/);
65
+ // Concatenating windows by their cursors reproduces the source, marker-free.
66
+ const second = data(read(text, first.window.next_offset_chars ?? 0, 10));
67
+ assert.equal(second.window.offset_chars, 10);
68
+ assert.equal(`${first.window.text}${second.window.text}`, chars.slice(0, 20).join(""));
69
+ // A negative offset counts back from the end and reaches a complete window: no footer at all.
70
+ const tail = data(read(text, -4));
71
+ assert.equal(tail.window.text, "bbbb");
72
+ assert.equal(tail.window.offset_chars, chars.length - 4);
73
+ assert.equal(tail.window.next_offset_chars, null);
74
+ assert.equal(tail.window.limited_by, null);
75
+ assert.equal(renderTextWindow(tail.window), "bbbb");
76
+ // The byte cap, not the requested count, is what stops an oversized read, and the rendered
77
+ // header is counted against the same budget as the payload.
78
+ const huge = "b".repeat(4 * MAX_READ_WINDOW_CHARS);
79
+ const capped = data(read(huge, 0, MAX_READ_WINDOW_CHARS));
80
+ const cappedEnd = capped.window.next_offset_chars ?? 0;
81
+ assert.equal(capped.window.limited_by, "bytes");
82
+ assert.ok(cappedEnd < MAX_READ_WINDOW_CHARS, "the byte cap cut the requested window short");
83
+ assert.equal(fitsResult(success(capped), renderData), true);
84
+ assert.ok(Buffer.byteLength(renderData(success(capped)), "utf8") <= TOOL_OUTPUT_MAX_BYTES, "the model text fits");
85
+ assert.ok(Buffer.byteLength(JSON.stringify(wireResult(success(capped))), "utf8") <= TOOL_OUTPUT_MAX_BYTES, "the structured outcome fits");
86
+ assert.equal(capped.window.text, huge.slice(0, cappedEnd), "the delivered slice is a verbatim prefix");
87
+ assert.match(renderData(success(capped)), new RegExp(`\\[Showing chars \\[0, ${cappedEnd}\\) of ${huge.length} \\(32KB limit\\)\\. Use offset_chars=${cappedEnd} to continue\\.\\]$`));
88
+ // Code points, not UTF-16 units.
89
+ const emoji = data(read("😀😀😀", 1, 1));
90
+ assert.equal(emoji.window.text, "😀");
91
+ assert.equal(emoji.window.total_chars, 3);
92
+ assert.equal(emoji.window.next_offset_chars, 2);
93
+ // An empty source is a complete, footer-free window rather than a refusal.
94
+ const empty = data(read("", 0, 10));
95
+ assert.equal(empty.window.text, "");
96
+ assert.equal(empty.window.total_chars, 0);
97
+ assert.equal(empty.window.next_offset_chars, null);
98
+ assert.equal(renderOutcome(success(first), () => "model text"), "model text");
99
+ assert.equal(renderOutcome(failure("not_found", "note not found"), () => "never"), "error: not_found: note not found");
100
+ assert.equal(renderOutcome(failure("ambiguous_edit", "occurs 2 times", { line_numbers: [2, 7] }), () => "never"), 'error: ambiguous_edit: occurs 2 times {"line_numbers":[2,7]}');
101
+ const schema = resultSchema(Type.Object({ name: Type.String() }));
102
+ assert.equal(Check(schema, wireResult(success({ name: "test" }))), true);
103
+ assert.equal(Check(schema, wireResult(failure("not_found", "missing"))), true);
104
+ assert.equal(Check(schema, { name: 123 }), false);
105
+ assert.equal(Check(schema, success({ name: "test" })), false, "the old success envelope is not the wire contract");
106
+ assert.equal(Check(schema, failure("not_found", "missing")), false, "the old error envelope is not the wire contract");
107
+ });
108
+ test("an envelope that cannot fit is refused rather than resumed forever", () => {
109
+ const text = "c".repeat(1000);
110
+ // An operation whose rendered text is over budget whatever window it delivers.
111
+ const envelope = (header) => ({
112
+ makeData: (window) => ({ header, window }),
113
+ render: (result) => result.ok ? `${result.data.header}\n${renderTextWindow(result.data.window)}` : renderOutcome(result, () => ""),
114
+ });
115
+ const oversized = envelope("h".repeat(2 * TOOL_OUTPUT_MAX_BYTES));
116
+ const refusing = readTextWindow(text, 0, undefined, oversized.makeData, oversized.render);
117
+ const error = refusal(refusing);
118
+ assert.equal(error.code, "output_too_large");
119
+ assert.equal(error.details?.offset_chars, 0);
120
+ assert.equal(error.details?.budget_bytes, TOOL_OUTPUT_MAX_BYTES);
121
+ assert.ok(structuredBytes(wireResult(refusing)) <= TOOL_OUTPUT_MAX_BYTES, "the refusal that replaces an unresumable window is itself bounded");
122
+ assert.equal(fitsResult(refusing, oversized.render), true);
123
+ // Empty text fitting is insufficient when not even one source character can fit.
124
+ const noProgressRender = (result) => result.ok ? "x".repeat(TOOL_OUTPUT_MAX_BYTES) + result.data.window.text : renderOutcome(result, () => "");
125
+ assert.equal(refusal(readTextWindow("😀", 0, 1, makeData, noProgressRender)).code, "output_too_large");
126
+ // At the document end, removing the footer can make the full window fit even though prefixes do not.
127
+ const endFitsRender = (result) => result.ok ? (result.data.window.next_offset_chars === null ? result.data.window.text : "x".repeat(TOOL_OUTPUT_MAX_BYTES + 1)) : renderOutcome(result, () => "");
128
+ assert.equal(data(readTextWindow("abc", 0, 3, makeData, endFitsRender)).window.text, "abc");
129
+ // The same text is delivered normally as soon as the envelope fits.
130
+ const fitting = envelope("ok");
131
+ const delivered = data(readTextWindow(text, 0, undefined, fitting.makeData, fitting.render));
132
+ assert.equal(delivered.window.text, text);
133
+ assert.equal(delivered.window.next_offset_chars, null);
134
+ });
135
+ test("every resumed window advances the cursor and reconstructs the source exactly", () => {
136
+ const text = `${"é".repeat(50)}👨‍👩‍👧${"x".repeat(200_000)}\r\n😀${"漢".repeat(1000)}`;
137
+ const chars = Array.from(text);
138
+ assert.notEqual(text.length, chars.length, "the fixture would not catch UTF-16 counting");
139
+ const windows = [];
140
+ for (let offset = 0; offset < chars.length;) {
141
+ const window = data(read(text, offset, MAX_READ_WINDOW_CHARS)).window;
142
+ assert.equal(window.total_chars, chars.length, "one source, one length");
143
+ assert.equal(window.offset_chars, offset, "each window starts where the last one stopped");
144
+ if (window.next_offset_chars === null) {
145
+ assert.equal(window.offset_chars + Array.from(window.text).length, window.total_chars, "the last window reaches the true end");
146
+ windows.push(window);
147
+ break;
148
+ }
149
+ assert.ok(window.next_offset_chars > window.offset_chars, "a window with text left always advances the cursor");
150
+ windows.push(window);
151
+ offset = window.next_offset_chars;
152
+ }
153
+ assert.ok(windows.length > 1, "the fixture needed more than one window");
154
+ assert.equal(windows.slice(0, -1).every((window) => window.limited_by === "bytes"), true, "the byte cap, not the count, split this read");
155
+ assert.equal(windows.at(-1)?.limited_by, null, "the last window withholds nothing");
156
+ assert.equal(windows.map((window) => window.text).join(""), text, "concatenating the windows reproduces the source code point for code point");
157
+ for (const window of windows) {
158
+ assert.equal(Array.from(window.text).length, (window.next_offset_chars ?? window.total_chars) - window.offset_chars, "the delivered length matches the cursor");
159
+ assert.ok(structuredBytes(wireResult(success({ window }))) <= TOOL_OUTPUT_MAX_BYTES, "each window fits the structured surface");
160
+ }
161
+ });
162
+ test("window offsets count code points, not UTF-16 units or graphemes", () => {
163
+ const cases = [
164
+ { name: "astral", text: "😀😀😀", cursor: 1 },
165
+ { name: "zwj sequence", text: "👨‍👩‍👧", cursor: 2 },
166
+ { name: "combining mark", text: "é", cursor: 1 },
167
+ { name: "cjk", text: "漢字", cursor: 1 },
168
+ { name: "crlf", text: "a\r\nb", cursor: 3 },
169
+ { name: "mixed", text: "a😀b👨‍👩‍👧c", cursor: 1 },
170
+ ];
171
+ for (const { name, text, cursor } of cases) {
172
+ const chars = Array.from(text);
173
+ const window = data(read(text, cursor, undefined)).window;
174
+ assert.equal(window.offset_chars, cursor, `${name}: the resolved offset is echoed`);
175
+ assert.equal(window.total_chars, chars.length, `${name}: totals count code points`);
176
+ assert.equal(window.text, chars.slice(cursor).join(""), `${name}: the slice starts on a code-point boundary`);
177
+ assert.equal(window.text.includes("�"), false, `${name}: no surrogate is split`);
178
+ }
179
+ // Negative offsets resolve from the code-point end, not the byte or unit end.
180
+ const emoji = "😀".repeat(3);
181
+ const tail = data(read(emoji, -1)).window;
182
+ assert.equal(tail.text, "😀");
183
+ assert.equal(tail.offset_chars, 2, "the last code point is at 2, not at 5 UTF-16 units");
184
+ assert.equal(tail.next_offset_chars, null);
185
+ });
186
+ test("the dynamic parts of a refusal are bounded by construction", () => {
187
+ // A note edit that matched a million lines is the realistic unbounded case.
188
+ const huge = failure("ambiguous_edit", `edit 0: oldText occurs ${"9".repeat(7)} times`, { line_numbers: Array.from({ length: 1_000_000 }, (_, index) => index + 1) });
189
+ const error = refusal(huge);
190
+ assert.equal(error.code, "ambiguous_edit");
191
+ assert.deepEqual(Object.keys(error.details ?? {}).sort(), ["details_bytes", "truncated"], "oversized context is named, never partially serialized");
192
+ assert.equal(error.details?.truncated, true);
193
+ assert.ok(error.details?.details_bytes > ERROR_DETAILS_MAX_BYTES, "the lost size is reported");
194
+ assert.ok(structuredBytes(wireResult(huge)) <= TOOL_OUTPUT_MAX_BYTES, "even a pathological refusal fits the budget");
195
+ assert.equal(fitsResult(huge, () => renderOutcome(huge, () => "")), true);
196
+ const small = refusal(failure("no_match", "edit 0: oldText does not occur in the note body", { edit_index: 0, line_numbers: [4] }));
197
+ assert.deepEqual(small.details, { edit_index: 0, line_numbers: [4] }, "context inside the budget is kept as it is");
198
+ // A flood of keys is the same hazard as a flood of values: a handler must not spend the budget
199
+ // enumerating what it could not report anyway.
200
+ const manyKeys = failure("unknown_window_id", 'unknown window_id "w"', Object.fromEntries([...Array.from({ length: 300 }, (_, index) => [`window_${index}`, index]), ["k".repeat(5000), 1]]));
201
+ const keyed = refusal(manyKeys);
202
+ assert.deepEqual(Object.keys(keyed.details ?? {}).sort(), ["details_bytes", "truncated"], "oversized keys are replaced by the marker, not trimmed into a partial list");
203
+ assert.ok(structuredBytes(wireResult(manyKeys)) <= TOOL_OUTPUT_MAX_BYTES);
204
+ const long = refusal(failure("internal_error", "m".repeat(50_000)));
205
+ assert.ok(Array.from(long.message).length < ERROR_MESSAGE_MAX_CHARS + 40, "a runaway message is clipped with a marker");
206
+ assert.match(long.message, /…\[truncated \d+ chars\]$/, "the clip says how much was dropped");
207
+ });
208
+ test("internal result invariants stay visible instead of becoming a bounded-looking refusal", () => {
209
+ // Context JSON cannot express is a handler defect, and a defect is not a bounded refusal.
210
+ const circular = {};
211
+ circular.self = circular;
212
+ assert.throws(() => failure("internal_error", "cyclic context", circular), TypeError, "a cyclic context throws instead of being swallowed");
213
+ assert.throws(() => failure("internal_error", "unrepresentable context", { size: 1n }), TypeError, "a BigInt context throws instead of becoming an empty value");
214
+ // A value with no JSON representation has no size to measure, so it is not measured as zero bytes.
215
+ assert.throws(() => structuredBytes(undefined), TypeError, "undefined has no structured size");
216
+ });
217
+ test("shared note operations return canonical outcomes with a body-only read window", async (t) => {
218
+ const notesIdentity = identity(t);
219
+ const written = data(await notesWrite.execute({ address: "@project/test.md", content: "alpha\nbeta" }, notesIdentity));
220
+ assert.equal(written.address, "@project/test.md");
221
+ assert.equal(written.project_key, notesIdentity.projectKey);
222
+ assert.equal(written.outcome, "created");
223
+ const updated = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "alpha", newText: "gamma" }] }, notesIdentity, (change) => {
224
+ assert.equal(change.kind, "body");
225
+ return "caller-rendered-diff";
226
+ }));
227
+ assert.equal(updated.applied, 1);
228
+ assert.equal(updated.change_kind, "body");
229
+ assert.equal(updated.diff, "caller-rendered-diff");
230
+ // Frontmatter is metadata, not body: the window addresses the body and counts only the body.
231
+ const stored = await createNotesStore(notesIdentity).read("@project/test.md");
232
+ assert.ok(stored, "the note is on disk");
233
+ const body = Array.from(stored.body);
234
+ const read = data(await notesRead.execute({ address: "@project/test.md" }, notesIdentity));
235
+ assert.equal(read.text, stored.body, "a complete read is the whole body and nothing else");
236
+ assert.equal(read.total_chars, body.length);
237
+ assert.equal(read.next_offset_chars, null);
238
+ assert.equal(read.limited_by, null);
239
+ assert.equal(read.metadata.origin, "self");
240
+ assert.equal(notesRead.render(success(read)).includes("READ WINDOW"), false, "a read presents no metadata block");
241
+ // A negative offset resolves against the body, never against the serialized file.
242
+ const tail = data(await notesRead.execute({ address: "@project/test.md", offset_chars: -4 }, notesIdentity));
243
+ assert.equal(tail.text, body.slice(-4).join(""));
244
+ assert.equal(tail.offset_chars, body.length - 4);
245
+ assert.equal(tail.total_chars, body.length, "metadata length never enters the body cursor");
246
+ assert.equal(tail.next_offset_chars, null);
247
+ assert.equal(refusal(await notesRead.execute({ address: "@project/missing.md" }, notesIdentity)).code, "not_found");
248
+ assert.equal(refusal(await notesWrite.execute({ address: "../escape", content: "x" }, notesIdentity)).code, "invalid_address");
249
+ assert.equal(refusal(await notesRead.execute({ address: "@project/test.md", offset_chars: 99_999 }, notesIdentity)).code, "invalid_offset");
250
+ });
251
+ test("shared history operations read typed events through the addresses the adapter allocated", async () => {
252
+ const projection = projectHistory([{ windowId: "root", items: [
253
+ { seq: 1, windowId: "root", role: "user", text: "hello there" },
254
+ { seq: 2, windowId: "root", role: "tool_call", text: "", toolName: "read", toolCallId: "call", arguments: { path: "one.md" } },
255
+ { seq: 3, windowId: "root", role: "tool", text: "😀 needle output", toolName: "read", toolCallId: "call" },
256
+ ] }], 3, new Set([1, 2, 3]));
257
+ const windows = data(await historyWindows.execute({}, projection, "explicit-session"));
258
+ assert.equal(windows.session_id, "explicit-session");
259
+ assert.equal(windows.windows.length, 1);
260
+ assert.equal(windows.windows[0]?.item_count, 2, "a call and its result are one event, not two");
261
+ const listed = data(await historyList.execute({ roles: ["tool"] }, projection));
262
+ assert.equal(listed.items.length, 1);
263
+ const item = listed.items[0];
264
+ assert.ok(item && !('folded' in item), "the tool event carries an address");
265
+ const seq = item.seq;
266
+ assert.notEqual(seq, 3, "a paired result address is not an event of its own");
267
+ // A tool event is one typed event whose document carries the call, its arguments, and its result.
268
+ const full = data(await historyRead.execute({ seq }, projection));
269
+ assert.equal(full.seq, seq);
270
+ assert.equal(full.role, "tool");
271
+ assert.match(full.text, /one\.md/, "the document carries the arguments");
272
+ assert.match(full.text, /needle output/, "the document carries the result");
273
+ assert.equal(full.next_offset_chars, null);
274
+ // A search offset addresses that same document, so reading from it resumes inside the result.
275
+ const searched = data(await historySearch.execute({ query: "NEEDLE", roles: ["tool"] }, projection));
276
+ assert.equal(searched.items.length, 1);
277
+ const hit = searched.items[0];
278
+ assert.ok(!('folded' in hit));
279
+ assert.equal(hit.seq, seq);
280
+ assert.ok((hit.offset_chars ?? 0) > 0);
281
+ const fromMatch = data(await historyRead.execute({ seq: hit.seq, offset_chars: hit.offset_chars }, projection));
282
+ assert.match(fromMatch.text, /^needle output/, "the match offset lands on the matched text");
283
+ assert.equal(fromMatch.total_chars, full.total_chars, "one document, one length");
284
+ assert.match(refusal(await historyRead.execute({ seq: 9_999 }, projection)).message, /9,?999/, "an unknown address is refused by name");
285
+ assert.equal(refusal(await historyRead.execute({ seq: 3 }, projection)).code, "not_an_event", "a paired result address is refused");
286
+ });
287
+ test("one role schema declares the four public roles for the page item, the read payload, and the role filter", () => {
288
+ const read = (role) => ({
289
+ seq: 1, window_id: "root", role, created_at: null,
290
+ text: "", offset_chars: 0, total_chars: 0, next_offset_chars: null, limited_by: null,
291
+ });
292
+ assert.equal(HistoryPageItemSchema.properties.role, HistoryRoleSchema, "the page item reuses the authoritative role schema");
293
+ assert.deepEqual(historyRoles().items, HistoryRoleSchema, "the role filter carries the authoritative role schema");
294
+ for (const role of ["user", "assistant", "tool", "context"]) {
295
+ assert.equal(Check(HistoryRoleSchema, role), true, `${role} is a public role`);
296
+ assert.equal(Check(historyRead.outputSchema, read(role)), true, `history_read accepts ${role}`);
297
+ }
298
+ assert.equal(Check(HistoryRoleSchema, "developer"), false, "a role outside the four is refused");
299
+ assert.equal(Check(historyRead.outputSchema, read("developer")), false, "history_read refuses a role outside the four");
300
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,214 @@
1
+ import assert from "node:assert/strict";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { createNotesStore, NoteError } from "../src/notes/index.js";
7
+ function fixture(t) {
8
+ const home = mkdtempSync(join(tmpdir(), "notes-library-"));
9
+ t.after(() => rmSync(home, { recursive: true, force: true }));
10
+ const context = { home, sessionId: "session-a", projectKey: "project-12345678", agent: "root", model: "test-model" };
11
+ return { home, context, notes: createNotesStore(context) };
12
+ }
13
+ test("standalone notes API persists camelCase metadata, edits, lists and searches full results", async (t) => {
14
+ const { home, notes } = fixture(t);
15
+ const first = await notes.write("checkpoint", "alpha\nneedle 😀", { origin: "user" });
16
+ assert.equal(first.meta.project, "project-12345678");
17
+ const read = (await notes.read("checkpoint.md"));
18
+ assert.equal(read.body, "alpha\nneedle 😀");
19
+ assert.equal(read.meta.origin, "user");
20
+ assert.equal(read.meta.accessCount, 1);
21
+ assert.equal(await notes.read("missing.md"), undefined);
22
+ const edited = await notes.update("checkpoint", [{ oldText: "alpha", newText: "beta" }]);
23
+ assert.deepEqual(edited.change, { kind: "body", before: "alpha\nneedle 😀", after: "beta\nneedle 😀" });
24
+ assert.equal(edited.resolvedScope, read.resolvedScope);
25
+ assert.equal(edited.applied, 1);
26
+ const updatedBefore = (await notes.read("checkpoint")).meta.updatedAt;
27
+ const metadataEdit = await notes.update("checkpoint", undefined, { crumpled: true });
28
+ assert.equal(metadataEdit.change.kind, "metadata");
29
+ assert.equal(metadataEdit.change.before.includes("crumpledAt"), false);
30
+ assert.match(metadataEdit.change.after, /\ncrumpledAt: \d{4}-\d{2}-\d{2}T/);
31
+ assert.equal(metadataEdit.change.after.includes("needle"), false, "metadata-only diff excludes body");
32
+ assert.equal((await notes.list()).some((row) => row.address === "checkpoint.md"), false, "a crumpled note leaves the live list");
33
+ assert.equal((await notes.search(["needle"])).length, 0, "search also skips crumpled notes");
34
+ const basket = (await notes.list({ wastebasket: true }))[0];
35
+ assert.equal(basket.address, "checkpoint.md");
36
+ assert.ok(basket.meta.crumpledAt);
37
+ assert.equal(basket.meta.updatedAt, updatedBefore, "crumpling does not bump updatedAt");
38
+ const crumpledAt = basket.meta.crumpledAt;
39
+ await notes.update("checkpoint", undefined, { crumpled: true });
40
+ assert.equal((await notes.list({ wastebasket: true }))[0]?.meta.crumpledAt, crumpledAt, "re-crumpling keeps the original time");
41
+ await notes.update("checkpoint", undefined, { crumpled: false });
42
+ assert.equal((await notes.list()).some((row) => row.address === "checkpoint.md"), true, "smoothing returns the note to the live list");
43
+ assert.equal((await notes.list({ wastebasket: true })).length, 0);
44
+ const matches = await notes.search(["needle"]);
45
+ assert.equal(matches[0]?.matches[0]?.line, 2);
46
+ const body = (await notes.read("checkpoint")).body;
47
+ assert.equal(Array.from(body).slice(matches[0].matches[0].offsetChars).join(""), "needle 😀", "offsets address the body, so they survive the access-counter rewrite a read performs");
48
+ // An existing hand-written extra field and original ownership survive a new caller.
49
+ const path = join(home, "pi/session/session-a/checkpoint.md");
50
+ writeFileSync(path, readFileSync(path, "utf8").replace("\n---\n\n", "\nsourceWindow: pcw:test\nrecurrenceCount: 2\nrecurrenceWindows:\n - pcw:one\n - pcw:two\n__proto__: {\"sentinel\":true}\ncustom: preserved\n---\n\n"));
51
+ const moved = createNotesStore({ home, sessionId: "session-a", projectKey: "other-12345678", agent: "root", model: "test-model" });
52
+ const rewritten = await moved.write("checkpoint", "new body");
53
+ assert.equal(rewritten.meta.createdAt, first.meta.createdAt);
54
+ assert.equal(rewritten.meta.project, "project-12345678");
55
+ assert.equal(rewritten.meta.custom, "preserved");
56
+ assert.deepEqual(rewritten.meta["__proto__"], { sentinel: true });
57
+ assert.deepEqual((await moved.read("checkpoint"))?.meta["__proto__"], { sentinel: true }, "unknown __proto__ metadata survives persistence and reread");
58
+ assert.equal(rewritten.meta.sourceWindow, "pcw:test");
59
+ assert.equal(rewritten.meta.recurrenceCount, 2);
60
+ assert.deepEqual(rewritten.meta.recurrenceWindows, ["pcw:one", "pcw:two"]);
61
+ assert.equal(rewritten.meta.crumpledAt, undefined, "writing always produces an uncrumpled note");
62
+ const combined = await moved.update("checkpoint", [{ oldText: "new", newText: "final" }], { crumpled: true });
63
+ assert.equal(combined.change.kind, "file");
64
+ assert.match(combined.change.after, /\ncrumpledAt: \d{4}-\d{2}-\d{2}T/);
65
+ assert.match(combined.change.after, /final body$/);
66
+ assert.deepEqual((await moved.update("checkpoint", undefined, { crumpled: true })).change, { kind: "none", before: "", after: "" });
67
+ assert.equal((await moved.write("checkpoint", "revived body")).meta.crumpledAt, undefined, "writing a crumpled address smooths it");
68
+ });
69
+ test("same-file read/modify/write operations serialize across stores and markdown aliases", async (t) => {
70
+ const { home, context, notes } = fixture(t);
71
+ const other = createNotesStore(context);
72
+ await notes.write("shared", "alpha\nbeta");
73
+ const firstEdit = notes.update("shared", [{ oldText: "alpha", newText: "A" }]);
74
+ const secondEdit = other.update("shared.md", [{ oldText: "beta", newText: "B" }]);
75
+ await Promise.all([firstEdit, secondEdit]);
76
+ assert.equal((await notes.read("shared"))?.body, "A\nB", "edits through address aliases retain both changes");
77
+ const before = (await notes.read("shared")).meta.accessCount;
78
+ const [readA, readB] = await Promise.all([notes.read("shared.md"), other.read("shared")]);
79
+ assert.ok(readA && readB);
80
+ assert.equal((await notes.list({ scope: "session" }))[0]?.meta.accessCount, before + 2, "parallel reads do not lose access-counter updates");
81
+ const file = join(home, "pi/session/session-a/shared.md");
82
+ const stableEdits = [{ oldText: "A", newText: "first" }];
83
+ const operation = notes.update("shared", stableEdits);
84
+ stableEdits[0].newText = "mutated after call";
85
+ await operation;
86
+ assert.equal((await notes.read("shared"))?.body, "first\nB", "edit arguments are snapshotted at method entry");
87
+ assert.equal(readFileSync(file, "utf8").includes("mutated after call"), false);
88
+ });
89
+ test("stores snapshot explicit identity and do not leak homes across instances", async (t) => {
90
+ const { home, context } = fixture(t);
91
+ const mutable = { ...context };
92
+ const notes = createNotesStore(mutable);
93
+ const other = createNotesStore({ ...context, home: join(home, "other"), agent: "other-agent", model: "other-model" });
94
+ assert.equal(existsSync(join(home, "other")), false, "construction does not create the supplied home");
95
+ mutable.agent = "changed-after-construction";
96
+ await notes.write("@self/private", "first");
97
+ await other.write("@self/private", "second");
98
+ assert.equal((await notes.read("@self/private"))?.body, "first");
99
+ assert.equal((await other.read("@self/private"))?.body, "second");
100
+ assert.equal((await notes.list())[0]?.address, "@self/private.md");
101
+ assert.equal((await other.list())[0]?.address, "@self/private.md");
102
+ mkdirSync(join(home, "agents/visitor"), { recursive: true });
103
+ writeFileSync(join(home, "agents/visitor/hello.md"), "visiting");
104
+ assert.equal((await notes.read("@agents/visitor/hello"))?.body, "visiting");
105
+ await assert.rejects(() => notes.write("@agents/visitor/hello", "overwrite"), (error) => error instanceof NoteError && error.code === "invalid_scope");
106
+ });
107
+ test("list and search share scoped pattern scans and search offsets count Unicode code points", async (t) => {
108
+ const { notes } = fixture(t);
109
+ await notes.write("shared.md", "😀 needle in session");
110
+ await notes.write("@project/shared.md", "needle in project");
111
+ await notes.write("@human/shared.md", "needle in human");
112
+ await notes.write("@project/elsewhere.md", "unrelated");
113
+ const pattern = "**/shared.md";
114
+ const listed = await notes.list({ pattern });
115
+ const searched = await notes.search(["needle"], { pattern });
116
+ const listedAddresses = listed.map((row) => row.address).sort();
117
+ const searchedAddresses = searched.map((row) => row.address).sort();
118
+ assert.deepEqual(searchedAddresses, ["@human/shared.md", "@project/shared.md", "shared.md"]);
119
+ assert.deepEqual(searchedAddresses, listedAddresses, "list and search traverse the same filtered homes and files");
120
+ const sessionMatch = searched.find((row) => row.address === "shared.md").matches[0];
121
+ const body = (await notes.read("shared.md")).body;
122
+ assert.equal(body, "😀 needle in session");
123
+ assert.equal(Array.from(body).slice(sessionMatch.offsetChars).join(""), "needle in session", "the body offset counts the emoji as one code point and lands on the match");
124
+ });
125
+ test("search offsets address the body and never move when access metadata grows", async (t) => {
126
+ const { notes } = fixture(t);
127
+ await notes.write("counted.md", "needle here");
128
+ const offsetOf = async () => (await notes.search(["needle"])).find((row) => row.address === "counted.md").matches[0].offsetChars;
129
+ assert.equal(await offsetOf(), 0, "a match at the first body character has body offset 0");
130
+ // Walk the access counter across a digit boundary; an offset into the serialized file
131
+ // would shift by one character here, because the rewrite adds a digit to the frontmatter.
132
+ for (let read = 0; read < 12; read++)
133
+ await notes.read("counted.md");
134
+ assert.equal((await notes.list({ scope: "session" })).find((row) => row.address === "counted.md").meta.accessCount, 12);
135
+ assert.equal(await offsetOf(), 0, "reads that rewrite access metadata do not move the match");
136
+ await notes.write("front.md", `---\nbig: ${"x".repeat(200)}\n---\n\nneedle later`);
137
+ const frontMatch = (await notes.search(["needle"])).find((row) => row.address === "front.md").matches[0];
138
+ const frontBody = (await notes.read("front.md")).body;
139
+ assert.equal(frontBody, "needle later");
140
+ assert.equal(frontMatch.offsetChars, 0, "frontmatter length is not part of the body offset");
141
+ assert.equal(Array.from(frontBody).slice(frontMatch.offsetChars).join(""), "needle later");
142
+ assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
143
+ });
144
+ test("invalid addressing and failed edits leave stored bytes untouched without poisoning the queue", async (t) => {
145
+ const { home, context, notes } = fixture(t);
146
+ assert.throws(() => createNotesStore({ ...context, sessionId: "../escape" }));
147
+ await assert.rejects(() => notes.write("@project/../escape", "bad"), (error) => error instanceof NoteError && error.code === "invalid_address");
148
+ await assert.rejects(() => notes.list({ scope: "agent", who: "../escape" }));
149
+ // The typed API disallows this; JavaScript callers must still receive a refusal.
150
+ // @ts-expect-error who cannot accompany project scope
151
+ await assert.rejects(() => notes.list({ scope: "project", who: "root" }), (error) => error instanceof NoteError && error.code === "invalid_scope");
152
+ await notes.write("edit", "alpha\nbeta\nbeta");
153
+ const path = join(home, "pi/session/session-a/edit.md");
154
+ const before = readFileSync(path, "utf8");
155
+ await assert.rejects(() => notes.update("edit", [{ oldText: "beta", newText: "B" }]), (error) => error instanceof NoteError && error.code === "ambiguous_edit" && error.lineNumbers?.join(",") === "2,3");
156
+ await assert.rejects(() => notes.update("edit", [{ oldText: "alpha", newText: "A" }, { oldText: "absent", newText: "X" }]), (error) => error instanceof NoteError && error.code === "no_match" && error.editIndex === 1);
157
+ assert.equal(readFileSync(path, "utf8"), before);
158
+ await assert.rejects(() => notes.update("absent", undefined, { crumpled: true }), (error) => error instanceof NoteError && error.code === "not_found");
159
+ await notes.update("edit", [{ oldText: "alpha", newText: "A" }]);
160
+ assert.equal((await notes.read("edit"))?.body, "A\nbeta\nbeta", "failed operations do not poison later queue work");
161
+ });
162
+ test("rename moves a note with metadata intact across scopes and refuses live targets", async (t) => {
163
+ const { context, notes } = fixture(t);
164
+ const written = await notes.write("old-name", "body text", { origin: "user" });
165
+ await notes.read("old-name.md");
166
+ const moved = await notes.rename("old-name.md", "@project/new-name.md");
167
+ assert.equal(moved.meta.createdAt, written.meta.createdAt, "createdAt survives the move");
168
+ assert.equal(moved.meta.origin, "user");
169
+ assert.equal(moved.meta.accessCount, 1, "accessCount survives the move");
170
+ assert.ok(moved.meta.updatedAt >= written.meta.updatedAt, "updatedAt is bumped");
171
+ assert.equal(moved.meta.project, undefined, "leaving the session scope drops project ownership");
172
+ assert.equal(moved.replacedCrumpledTarget, false);
173
+ assert.equal(await notes.read("old-name.md"), undefined, "the old address is gone");
174
+ assert.equal((await notes.read("@project/new-name.md"))?.body, "body text");
175
+ const back = await notes.rename("@project/new-name.md", "back.md");
176
+ assert.equal(back.meta.project, context.projectKey, "entering the session scope stamps current project ownership");
177
+ assert.equal((await notes.read("back.md"))?.meta.createdAt, written.meta.createdAt);
178
+ const within = await notes.rename("back.md", "still-back.md");
179
+ assert.equal(within.meta.project, context.projectKey, "a same-scope rename keeps project ownership untouched");
180
+ await notes.write("occupied", "live target");
181
+ await assert.rejects(() => notes.rename("still-back.md", "occupied.md"), (error) => error instanceof NoteError && error.code === "already_exists");
182
+ await notes.update("occupied", undefined, { crumpled: true });
183
+ const replaced = await notes.rename("still-back.md", "occupied.md");
184
+ assert.equal(replaced.replacedCrumpledTarget, true, "a crumpled target is replaced");
185
+ assert.equal((await notes.read("occupied.md"))?.meta.createdAt, written.meta.createdAt, "the moved note keeps its identity, not the target's");
186
+ await assert.rejects(() => notes.rename("occupied", "occupied.md"), (error) => error instanceof NoteError && error.code === "nothing_to_do");
187
+ await assert.rejects(() => notes.rename("occupied.md", "@models/other-model/stolen.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
188
+ await assert.rejects(() => notes.rename("@agents/someone-else/private.md", "mine.md"), (error) => error instanceof NoteError && error.code === "invalid_scope");
189
+ await assert.rejects(() => notes.rename("absent.md", "anywhere.md"), (error) => error instanceof NoteError && error.code === "not_found");
190
+ });
191
+ test("ambiguous multiline anchors report each starting line", async (t) => {
192
+ const { notes } = fixture(t);
193
+ await notes.write("multiline", "a\nb\na\nb\na\nb");
194
+ await assert.rejects(() => notes.update("multiline", [{ oldText: "a\nb", newText: "x" }]), (error) => {
195
+ assert.ok(error instanceof NoteError);
196
+ assert.deepEqual(error.lineNumbers, [1, 3, 5]);
197
+ return true;
198
+ });
199
+ });
200
+ test("a massively ambiguous edit still reports every match line to a library caller", async (t) => {
201
+ const { notes } = fixture(t);
202
+ await notes.write("many", `${"beta\n".repeat(2000)}end`);
203
+ await assert.rejects(() => notes.update("many", [{ oldText: "beta", newText: "B" }]), (error) => {
204
+ assert.ok(error instanceof NoteError);
205
+ assert.equal(error.code, "ambiguous_edit");
206
+ assert.equal(error.lineNumbers?.length, 2000, "the domain keeps every match line rather than a sample");
207
+ assert.deepEqual(error.lineNumbers?.slice(0, 3), [1, 2, 3]);
208
+ assert.equal(error.lineNumbers?.[1999], 2000);
209
+ assert.match(error.message, /occurs 2000 times \(lines 1, 2, 3, 4, 5, 6, 7, 8, and 1992 more\)/, "the message names the exact total and a bounded sample");
210
+ assert.ok(Buffer.byteLength(error.message, "utf8") < 300, "the message stays small however many lines matched");
211
+ return true;
212
+ });
213
+ assert.equal((await notes.read("many"))?.body.startsWith("beta\nbeta"), true, "the refused edit left the body alone");
214
+ });
@@ -0,0 +1 @@
1
+ export {};