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,497 @@
1
+ import { notesIdentityFromPi } from "../src/pi/notes/adapter.js";
2
+ import { PI_TOOL_NAMES } from "../src/pi/tool-names.js";
3
+ import assert from "node:assert/strict";
4
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import test from "node:test";
7
+ import { loadNotesSnapshot } from "../src/boot/snapshot.js";
8
+ import { renderBootBlock } from "../src/boot/render.js";
9
+ import { localIso } from "../src/notes/frontmatter.js";
10
+ import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
11
+ import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
12
+ import { MAX_METADATA_ENTRY_BYTES, notesUpdate } from "../src/tools/notes.js";
13
+ import { assertWithinBudget, call, context, explicitBoot, makeExtension, manager, resultData, resultError, resultRead, } from "./helpers/extension.js";
14
+ import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
15
+ const testEnvironment = installExtensionTestHooks("notesoup-integration");
16
+ /** The model-facing text of one tool result. */
17
+ function textOf(result) {
18
+ const first = result.content[0];
19
+ return first && first.type === "text" ? first.text : "";
20
+ }
21
+ test("notes_list and notes_search are recent-first snapshots with narrowing hints", async () => {
22
+ const session = manager();
23
+ const captured = makeExtension(session);
24
+ const ctx = context(session);
25
+ const base = 1_700_000_000_000;
26
+ const put = (address, updated, content = "needle") => {
27
+ const project = address.startsWith("@project/");
28
+ const path = physicalPath(project ? "project" : "session", address.replace(/^@project\//, ""), ctx);
29
+ mkdirSync(dirname(path), { recursive: true });
30
+ writeFileSync(path, `---\nscope: ${project ? "project" : "session"}\norigin: self\ncreatedAt: ${localIso(updated - 1000)}\nupdatedAt: ${localIso(updated)}\nlastAccessed: ${localIso(updated)}\naccessCount: 0\n---\n\n${content}`);
31
+ };
32
+ put("old.md", base + 1);
33
+ put("new.md", base + 3);
34
+ put("@project/design.md", base + 2);
35
+ const listed = resultData(await call(captured, "notes_list", { limit: 2 }, ctx));
36
+ assert.deepEqual(listed.files.map((file) => file.address), ["new.md", "@project/design.md"]);
37
+ assert.equal(listed.more, 1);
38
+ assert.deepEqual(Object.keys(listed).sort(), ["crumpled_excluded", "files", "homes_unavailable", "more"]);
39
+ const searched = resultData(await call(captured, "notes_search", { query: "needle", limit: 2 }, ctx));
40
+ assert.deepEqual(searched.files.map((file) => file.address), ["new.md", "@project/design.md"]);
41
+ assert.equal(searched.more, 1);
42
+ const narrowed = resultData(await call(captured, "notes_list", { pattern: "@project/**" }, ctx));
43
+ assert.deepEqual(narrowed.files.map((file) => file.address), ["@project/design.md"]);
44
+ assert.equal(narrowed.more, 0);
45
+ });
46
+ test("notes_list reports omitted files when the wire budget truncates the snapshot", async () => {
47
+ const session = manager();
48
+ const captured = makeExtension(session);
49
+ const ctx = context(session);
50
+ const timestamp = 1_700_000_000_000;
51
+ const total = 1500;
52
+ for (let index = 0; index < total; index++) {
53
+ const address = `bulk/note-${String(index).padStart(4, "0")}.md`;
54
+ const path = physicalPath("session", address, ctx);
55
+ mkdirSync(dirname(path), { recursive: true });
56
+ writeFileSync(path, `---\nscope: session\norigin: self\ncreatedAt: ${localIso(timestamp)}\nupdatedAt: ${localIso(timestamp + index)}\nlastAccessed: ${localIso(timestamp)}\naccessCount: 0\n---\n\nbody`);
57
+ }
58
+ const result = await call(captured, "notes_list", {}, ctx);
59
+ assertWithinBudget(result, "oversized listing");
60
+ const listed = resultData(result);
61
+ assert.ok(listed.files.length > 0 && listed.files.length < total, "the snapshot is cut short instead of overflowing either surface");
62
+ assert.equal(listed.more, total - listed.files.length, "omitted rows are named, not silently dropped");
63
+ assert.equal(listed.files[0]?.address, `bulk/note-${String(total - 1).padStart(4, "0")}.md`, "the snapshot retains the newest rows first");
64
+ });
65
+ test("notes_list is most-recently-updated first across merged scopes", async () => {
66
+ const session = manager();
67
+ const captured = makeExtension(session);
68
+ const ctx = context(session);
69
+ const put = (scope, path, updated) => {
70
+ const file = physicalPath(scope, path, ctx);
71
+ mkdirSync(dirname(file), { recursive: true });
72
+ writeFileSync(file, `---\nscope: ${scope}\norigin: self\ncreatedAt: ${localIso(updated - 1000)}\nupdatedAt: ${localIso(updated)}\nlastAccessed: ${localIso(updated)}\naccessCount: 0\n---\n\nbody`);
73
+ };
74
+ const base = 1_700_000_000_000;
75
+ put("session", "b.md", base + 10);
76
+ put("session", "a.md", base + 10);
77
+ put("project", "c.md", base + 5);
78
+ put("human", "e.md", base + 20);
79
+ const files = async (params) => resultData(await call(captured, "notes_list", params, ctx)).files;
80
+ assert.deepEqual((await files({})).map((file) => file.address), ["@human/e.md", "a.md", "b.md", "@project/c.md"], "updated_at descending with address ascending as the tiebreak");
81
+ // A same-path pair in two scopes keeps both rows; equal timestamps tie-break by scope name.
82
+ put("human", "a.md", base + 10);
83
+ assert.deepEqual((await files({})).filter((file) => file.address.endsWith("a.md")).map((file) => file.address), ["@human/a.md", "a.md"], "equal timestamps tie-break by full address");
84
+ assert.deepEqual((await files({ pattern: "*.md" })).map((file) => file.address), ["a.md", "b.md"], "a bare pattern narrows to the session home");
85
+ });
86
+ test("notes are real files that persist across sessions and round-trip Unicode", async () => {
87
+ const original = manager();
88
+ const captured = makeExtension(original);
89
+ const ctx = context(original);
90
+ await call(captured, "notes_write", { address: "@human/checkpoint/进度.md", content: "第一行\nneedle Café" }, ctx);
91
+ // A brand-new session over the same physical root sees the human note: nothing is replayed
92
+ // from session entries, the file itself is the durable artifact.
93
+ const restored = manager();
94
+ const restoredCaptured = makeExtension(restored);
95
+ const restoredCtx = context(restored);
96
+ const rawRead = await call(restoredCaptured, "notes_read", { address: "@human/checkpoint/进度.md", offset_chars: -4 }, restoredCtx);
97
+ const read = resultRead(rawRead);
98
+ assert.equal(read.address, "@human/checkpoint/进度.md");
99
+ assert.equal(read.content, "Café", "a negative offset reads the body tail in one call");
100
+ const searched = resultData(await call(restoredCaptured, "notes_search", { pattern: "@human/**", query: "Café" }, restoredCtx));
101
+ assert.equal(searched.files[0]?.matches[0]?.line, 2);
102
+ const listedFiles = resultData(await call(restoredCaptured, "notes_list", { pattern: "@human/checkpoint/**" }, restoredCtx));
103
+ assert.equal(listedFiles.files.length, 1, "glob ** crosses into the checkpoint directory");
104
+ assert.equal(listedFiles.files[0]?.address, "@human/checkpoint/进度.md");
105
+ // A single-segment * never crosses `/`, so a nested-only store matches nothing at the root.
106
+ const rootOnly = resultData(await call(restoredCaptured, "notes_list", { pattern: "@human/*" }, restoredCtx));
107
+ assert.equal(rootOnly.files.length, 0, "glob * stays within one segment");
108
+ assert.equal(searched.files[0]?.updated_at, listedFiles.files[0]?.updated_at);
109
+ assert.equal(resultError(await call(captured, "notes_write", { address: "../escape", content: "x" }, ctx)).code, "invalid_address");
110
+ });
111
+ test("crumple lifecycle: metadata-only edits close and smooth a note without touching updatedAt", async () => {
112
+ const sm = manager();
113
+ const captured = makeExtension(sm);
114
+ const ctx = context(sm);
115
+ await call(captured, "notes_write", { address: "journal.md", content: "log line" }, ctx);
116
+ const updatedBefore = (await listNotes(ctx, { scope: "session" }))[0].meta.updatedAt;
117
+ // metadata-only: content unchanged, applied 0, and the recorded time is the original one
118
+ const markOnly = resultData(await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx));
119
+ assert.equal(markOnly.applied, 0);
120
+ assert.match(markOnly.diff, /^\+\s*\d+\s+crumpledAt: \d{4}-\d{2}-\d{2}T/m);
121
+ assert.deepEqual(await listNotes(ctx, { scope: "session" }), [], "a crumpled note leaves the live list");
122
+ const basket = (await listNotes(ctx, { scope: "session", wastebasket: true }))[0];
123
+ assert.ok(basket.meta.crumpledAt);
124
+ assert.equal(basket.meta.updatedAt, updatedBefore, "crumpling does not change updatedAt");
125
+ assert.equal(resultRead(await call(captured, "notes_read", { address: "journal.md" }, ctx)).content.endsWith("log line"), true, "read still reaches a crumpled note");
126
+ // re-crumpling keeps the first time; smoothing empties the basket
127
+ await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx);
128
+ assert.equal((await listNotes(ctx, { scope: "session", wastebasket: true }))[0]?.meta.crumpledAt, basket.meta.crumpledAt);
129
+ await call(captured, "notes_update", { address: "journal.md", crumpled: false }, ctx);
130
+ assert.deepEqual(await listNotes(ctx, { scope: "session", wastebasket: true }), []);
131
+ assert.equal((await listNotes(ctx, { scope: "session" }))[0]?.meta.crumpledAt, undefined);
132
+ // writing to a crumpled address always produces an uncrumpled note
133
+ await call(captured, "notes_update", { address: "journal.md", crumpled: true }, ctx);
134
+ await call(captured, "notes_write", { address: "journal.md", content: "reopened" }, ctx);
135
+ assert.equal((await listNotes(ctx, { scope: "session" }))[0]?.meta.crumpledAt, undefined, "writing always produces an uncrumpled note");
136
+ // metadata-only on a missing path is the typed not-found arm
137
+ const missing = resultError(await call(captured, "notes_update", { address: "missing.md", crumpled: true }, ctx));
138
+ assert.equal(missing.message, "note not found");
139
+ });
140
+ test("the filesystem notes loader treats an absent home as empty but surfaces a real directory read failure", async () => {
141
+ const sm = manager();
142
+ const ctx = context(sm);
143
+ assert.deepEqual(await listNotes(ctx, { scope: "human" }), [], "a home that has not been created is empty");
144
+ const blockedHome = scopeDir("human", ctx);
145
+ writeFileSync(blockedHome, "not a directory");
146
+ await assert.rejects(() => listNotes(ctx, { scope: "human" }), (error) => error.code === "ENOTDIR", "a non-ENOENT directory failure is not swallowed as an empty home");
147
+ });
148
+ test("boot note acquisition is one closed snapshot and isolates one or all failed homes", async () => {
149
+ const sm = manager();
150
+ const ctx = context(sm);
151
+ const updated = Date.now();
152
+ const note = (scope, path, address, body) => ({
153
+ address,
154
+ scope,
155
+ path,
156
+ body,
157
+ sizeBytes: Buffer.byteLength(body, "utf8"),
158
+ meta: {
159
+ scope,
160
+ origin: "self",
161
+ createdAt: updated,
162
+ updatedAt: updated,
163
+ lastAccessed: updated,
164
+ accessCount: 0,
165
+ },
166
+ });
167
+ const rows = new Map([
168
+ ["session", [note("session", "MAP.md", "MAP.md", "SESSION_MAP_BODY"), note("session", "session.md", "session.md", "# Session note\n\nSESSION_POCKET_BODY")]],
169
+ ["project", [note("project", "MAP.md", "@project/MAP.md", "PROJECT_MAP_BODY")]],
170
+ ["human", [note("human", "MAP.md", "@human/MAP.md", "HUMAN_MAP_BODY"), note("human", "human.md", "@human/human.md", "# Human note\n\nHUMAN_POCKET_BODY")]],
171
+ ["agent", [note("agent", "MAP.md", "@agents/root/MAP.md", "AGENT_MAP_BODY")]],
172
+ ["model", [note("model", "model.md", "@models/default/model.md", "# Model note\n\nMODEL_POCKET_BODY")]],
173
+ ]);
174
+ const calls = new Map();
175
+ const snapshot = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
176
+ calls.set(scope, (calls.get(scope) ?? 0) + 1);
177
+ return rows.get(scope) ?? [];
178
+ });
179
+ assert.deepEqual([...calls.entries()], [["session", 1], ["project", 1], ["human", 1], ["agent", 1], ["model", 1]], "each selected home is loaded exactly once");
180
+ const renderData = {
181
+ tools: PI_TOOL_NAMES,
182
+ agentName: "root",
183
+ modelName: "default",
184
+ firstWindowId: "pcw:test:root",
185
+ currentWindowId: "pcw:test:next",
186
+ previousWindowId: "pcw:test:root",
187
+ notes: snapshot,
188
+ };
189
+ const rendered = renderBootBlock(renderData);
190
+ assert.equal(renderBootBlock(renderData), rendered, "rendering the same boot data twice is deterministic");
191
+ assert.ok(rendered.includes("HUMAN_MAP_BODY") && rendered.includes("PROJECT_MAP_BODY") && rendered.includes("AGENT_MAP_BODY") && rendered.includes("SESSION_MAP_BODY"), "all home maps, including session, are pinned");
192
+ assert.ok(rendered.includes("session.md") && rendered.includes("@human/human.md"), "the fresh page carries rows from every home");
193
+ assert.equal(rendered.includes("SESSION_POCKET_BODY"), false, "fresh-page bodies stay excluded");
194
+ assert.equal(rendered.includes("- MAP.md"), false, "a pinned session map does not take a feed seat");
195
+ assert.match(rendered, / {2}Session note\n {2}session\.md · (?:just now|\d+s ago)/, "a feed entry is the note's own title over its locator");
196
+ assert.equal(rendered.includes("UTF-8 bytes"), false, "fresh rows omit implementation-oriented byte counts");
197
+ assert.ok(rendered.indexOf("<context_window_protocol>") < rendered.indexOf("YOUR NOTES"), "the protocol explains the notes before presenting them");
198
+ assert.match(rendered, /THIS PROJECT · @project\n─+/, "shelves carry underlined headers");
199
+ assert.ok(rendered.includes("New pages"), "shelves label their fresh pages");
200
+ assert.ok(rendered.indexOf("THIS SESSION") < rendered.indexOf("New pages"), "the first shelf opens the index");
201
+ const headings = ["THIS SESSION · no @", "THIS PROJECT · @project", "YOU · @self", "THE HUMAN · @human"];
202
+ for (let i = 1; i < headings.length; i++)
203
+ assert.ok(rendered.indexOf(headings[i - 1]) < rendered.indexOf(headings[i]), "shelves proceed from current hands to durable");
204
+ const expanded = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
205
+ if (scope === "project" || scope === "human" || scope === "agent" || scope === "model") {
206
+ return Array.from({ length: 6 }, (_, i) => note(scope, `note-${i}.md`, `@${scope === "agent" ? "agents/root" : scope === "model" ? "models/default" : scope}/note-${i}.md`, `body ${i}`));
207
+ }
208
+ return rows.get(scope) ?? [];
209
+ });
210
+ const expandedText = renderBootBlock({ ...renderData, notes: expanded });
211
+ const freshRows = expandedText.match(/^ {2}\S[^\n]* · (?:just now|\d+s ago)$/gm) ?? [];
212
+ assert.equal(freshRows.length, 13, "each shelf keeps three of its own pages; the session shelf keeps its one");
213
+ assert.ok(expandedText.includes("@project/note-2.md"), "the project shelf's third page");
214
+ assert.equal(expandedText.includes("@project/note-3.md"), false, "the project shelf's fourth page stays shelved");
215
+ assert.ok(expandedText.includes("@models/default/note-2.md"), "the model shelf also gets three");
216
+ assert.equal(expandedText.includes("You find"), false, "the old pocket heading is gone");
217
+ const empty = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => []);
218
+ assert.match(renderBootBlock({ ...renderData, notes: empty }), /YOUR NOTES\n──────────\n\nNone yet\. A blank slate is a fine place to start — just don't finish there\./);
219
+ const crumpledNote = note("session", "crumpled.md", "crumpled.md", "SHOULD_NOT_SHOW");
220
+ const mapAndUnicode = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => scope === "session" ? [
221
+ note("session", "MAP.md", "MAP.md", "SESSION_MAP_BODY"),
222
+ note("session", "unicode.md", "unicode.md", "🐑字"),
223
+ { ...crumpledNote, meta: { ...crumpledNote.meta, crumpledAt: localIso(updated) } },
224
+ ] : []);
225
+ const mapAndUnicodeText = renderBootBlock({ ...renderData, notes: mapAndUnicode });
226
+ assert.match(mapAndUnicodeText, / {2}🐑字\n {2}unicode\.md · (?:just now|\d+s ago)/, "a headingless note is announced by its first line");
227
+ assert.ok(mapAndUnicodeText.includes("THIS SESSION · no @\n───────────────────\n\nMAP — MAP.md\n\n SESSION_MAP_BODY\n\nNew pages\n\n 🐑字\n unicode.md · just now"), "the session shelf keeps its typography");
228
+ assert.equal(mapAndUnicodeText.includes("crumpled.md"), false);
229
+ assert.equal(/MAP\.md ·/.test(mapAndUnicodeText), false, "maps never take feed seats");
230
+ assert.equal(mapAndUnicodeText.includes("THE HUMAN"), false, "empty shelves are omitted");
231
+ const readFailure = (code) => Object.assign(new Error("scripted read failure"), { code });
232
+ const oneFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
233
+ if (scope === "human")
234
+ throw readFailure("EIO");
235
+ return rows.get(scope) ?? [];
236
+ });
237
+ assert.deepEqual(oneFailed.unavailable.map((home) => home.label), ["@human"]);
238
+ const oneFailedText = renderBootBlock({
239
+ tools: PI_TOOL_NAMES,
240
+ agentName: "root",
241
+ modelName: "default",
242
+ firstWindowId: "pcw:test:root",
243
+ currentWindowId: "pcw:test:next",
244
+ notes: oneFailed,
245
+ });
246
+ assert.ok(oneFailedText.includes("PROJECT_MAP_BODY") && oneFailedText.includes("THE HUMAN · @human\n──────────────────\n\n This drawer wouldn't open — ask notes_list to try again."), "healthy homes and a per-section recovery notice survive one failure");
247
+ assert.equal(oneFailedText.includes("HUMAN_POCKET_BODY"), false, "the failed home's index is omitted");
248
+ assert.equal(oneFailedText.includes("Human note"), false, "the failed home takes no feed seats");
249
+ const allFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
250
+ throw readFailure(scope === "session" ? "EACCES" : "EIO");
251
+ });
252
+ assert.equal(allFailed.unavailable.length, 5);
253
+ const allFailedText = renderBootBlock({
254
+ tools: PI_TOOL_NAMES,
255
+ agentName: "root",
256
+ modelName: "default",
257
+ firstWindowId: "pcw:test:root",
258
+ currentWindowId: "pcw:test:next",
259
+ previousWindowId: "pcw:test:root",
260
+ notes: allFailed,
261
+ });
262
+ assert.ok(allFailedText.includes("pcw:test:root") && allFailedText.includes("pcw:test:next"), "identity survives an all-home failure");
263
+ assert.ok(allFailedText.includes("Your memory gets wiped when this window ends"), "protocol survives an all-home failure");
264
+ assert.equal(allFailedText.includes("scripted read failure"), false, "the model-facing notice does not expose OS/error details");
265
+ await assert.rejects(() => loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => { throw new TypeError("programmer failure"); }), (error) => error instanceof TypeError, "unrelated TypeError construction failures remain visible");
266
+ await assert.rejects(() => loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => { throw Object.assign(new Error("invalid argument"), { code: "ERR_INVALID_ARG_TYPE" }); }), (error) => error.code === "ERR_INVALID_ARG_TYPE", "Node ERR_* failures are not treated as filesystem errno failures");
267
+ });
268
+ test("the boot block gives awake agents the notes-home file layout", async () => {
269
+ const session = manager();
270
+ const rendered = await explicitBoot(context(session), "pcw:test:root", undefined);
271
+ assert.equal(rendered.includes(process.env.PI_NOTES_HOME ?? ""), false, "the absolute notes home is never exposed");
272
+ assert.match(rendered, /<path>, no @[\s\S]*@project\/<path>[\s\S]*@human\/<path>/);
273
+ });
274
+ test("an over-budget note is delivered as a bounded prefix and resumed by next_offset_chars", async () => {
275
+ const session = manager();
276
+ const captured = makeExtension(session);
277
+ const ctx = context(session);
278
+ const huge = `H${"x".repeat(TOOL_OUTPUT_MAX_BYTES * 2)}`;
279
+ const text = `${huge}\ntail line`;
280
+ await call(captured, "notes_write", { address: "huge.md", content: text }, ctx);
281
+ const rawFirst = await call(captured, "notes_read", { address: "huge.md" }, ctx);
282
+ assertWithinBudget(rawFirst, "single oversized note");
283
+ const first = resultRead(rawFirst);
284
+ assert.ok(first.content.length > 0, "the page is not empty");
285
+ assert.equal(first.content.includes("…"), false, "the window text is a plain prefix with no marker");
286
+ assert.ok(first.content.startsWith("H"), "the body is delivered first, with no frontmatter in the way");
287
+ assert.equal(first.offset_chars, 0, "the default window starts at the resolved offset 0");
288
+ assert.equal(first.total_chars, Array.from(text).length, "the window counts the body, not the serialized file");
289
+ assert.equal(first.limited_by, "limit", "the requested window ended this page, not the byte budget");
290
+ assert.equal(first.content.length, 12000, "the default window is the full requested count");
291
+ assert.deepEqual(Object.keys(resultData(rawFirst)).sort(), ["address", "limited_by", "metadata", "next_offset_chars", "offset_chars", "text", "total_chars"], "read fields are flat");
292
+ assert.equal("access_count" in resultData(rawFirst).metadata, false, "access bookkeeping stays in storage");
293
+ assert.equal(textOf(rawFirst).endsWith(`\n\n[${first.total_chars - first.content.length} more characters. Use offset_chars=${first.next_offset_chars} to continue.]`), true, "the footer names the resume cursor in the new read style");
294
+ // Asking for the largest legal window still cannot exceed the byte budget, and says so.
295
+ const rawWide = await call(captured, "notes_read", { address: "huge.md", limit_chars: MAX_READ_WINDOW_CHARS }, ctx);
296
+ assertWithinBudget(rawWide, "widest requested window");
297
+ const wide = resultRead(rawWide);
298
+ assert.equal(wide.limited_by, "bytes", "the byte budget stopped this window");
299
+ assert.ok(Array.from(wide.content).length < MAX_READ_WINDOW_CHARS, "the widest request is cut short");
300
+ assert.match(textOf(rawWide), /\(32KB limit\)\. Use offset_chars=\d+ to continue\.\]$/, "a byte-stopped window names the budget that stopped it");
301
+ // Following the cursor reconstructs the body by plain concatenation.
302
+ const parts = [first.content];
303
+ let offset = first.next_offset_chars;
304
+ while (offset !== null) {
305
+ const rawChunk = await call(captured, "notes_read", { address: "huge.md", offset_chars: offset }, ctx);
306
+ assertWithinBudget(rawChunk, `huge note chunk at ${offset}`);
307
+ const chunk = resultRead(rawChunk);
308
+ assert.equal(chunk.offset_chars, offset, "the response echoes the resolved absolute offset");
309
+ parts.push(chunk.content);
310
+ offset = chunk.next_offset_chars;
311
+ }
312
+ assert.equal(parts.join(""), text, "the cursors reconstruct the body exactly");
313
+ // Both surfaces stay inside the budget, and a refusal carries no window at all.
314
+ const missingResult = await call(captured, "notes_read", { address: "no-such.md" }, ctx);
315
+ assertWithinBudget(missingResult, "refused read");
316
+ const root = process.env.PI_NOTES_HOME;
317
+ for (const result of [
318
+ await call(captured, "notes_write", { address: "@project/receipt", content: "body" }, ctx),
319
+ await call(captured, "notes_update", { address: "@project/receipt", edits: [{ oldText: "body", newText: "changed" }] }, ctx),
320
+ await call(captured, "notes_list", { pattern: "@project/**" }, ctx),
321
+ await call(captured, "notes_search", { query: "changed", pattern: "@project/**" }, ctx),
322
+ await call(captured, "notes_read", { address: "@project/receipt" }, ctx),
323
+ ]) {
324
+ assert.equal(JSON.stringify(result).includes(root), false, "notes receipts never expose the absolute home");
325
+ assertWithinBudget(result, "ordinary notes receipt");
326
+ }
327
+ assert.equal(JSON.stringify(missingResult).includes(root), false, "failure receipts never expose the absolute home");
328
+ const missing = resultError(missingResult);
329
+ assert.deepEqual(Object.keys(missing).sort(), ["code", "message"], "the refusal carries a precise code and message");
330
+ assert.equal(missing.message, "note not found");
331
+ assert.equal(missing.code, "not_found");
332
+ assert.equal(missingResult.details, undefined, "a refusal carries no details metadata");
333
+ });
334
+ test("an over-budget note search match is a named prefix with an honest line address", async () => {
335
+ const session = manager();
336
+ const captured = makeExtension(session);
337
+ const ctx = context(session);
338
+ // The query sits behind a prefix, so its address is a real body-absolute offset, not line 1.
339
+ const hugeLine = `${'p'.repeat(500)}needle ${"y".repeat(TOOL_OUTPUT_MAX_BYTES * 2)}`;
340
+ await call(captured, "notes_write", { address: "a.md", content: "needle small" }, ctx);
341
+ await call(captured, "notes_write", { address: "search.md", content: hugeLine }, ctx);
342
+ const pages = [];
343
+ const found = resultData(await call(captured, "notes_search", { query: "needle", limit: 10 }, ctx));
344
+ assert.ok(Buffer.byteLength(JSON.stringify(found), "utf8") <= TOOL_OUTPUT_MAX_BYTES, "the structured match result stays within budget");
345
+ pages.push(...found.files);
346
+ assert.equal(found.more, 1, "the oversized result names the omitted matching file");
347
+ assert.deepEqual(pages.map((file) => file.address), ["search.md"], "the snapshot keeps the most recently updated match");
348
+ const oversized = pages[0];
349
+ assert.equal(oversized.matches_total, 1, "the file's full match count is named even though the line was cut");
350
+ assert.equal(oversized.matches.length, 1);
351
+ const match = oversized.matches[0];
352
+ assert.equal(match.truncated, true, "the oversized match line is flagged as truncated");
353
+ assert.ok(hugeLine.startsWith(match.text), "the match text is a plain prefix of the line");
354
+ assert.equal(match.text.includes("…"), false, "no marker is appended to the match text");
355
+ assert.equal(match.line, 1, "the informational line number survives");
356
+ assert.equal(match.offset_chars, 500, "the offset addresses the body directly, so the query's real position survives");
357
+ const atMatch = resultRead(await call(captured, "notes_read", { address: "search.md", offset_chars: match.offset_chars }, ctx));
358
+ assert.ok(atMatch.content.startsWith("needle"), "the search offset starts a read at the matched substring");
359
+ // The body is reconstructible by following notes_read's cursor from the start of the file.
360
+ const parts = [];
361
+ let offset = 0;
362
+ while (offset !== null) {
363
+ const rawChunk = await call(captured, "notes_read", { address: "search.md", offset_chars: offset }, ctx);
364
+ assertWithinBudget(rawChunk, `search.md chunk at ${offset}`);
365
+ const chunk = resultRead(rawChunk);
366
+ assert.equal(chunk.offset_chars, offset, "the read echoes the resolved address");
367
+ parts.push(chunk.content);
368
+ offset = chunk.next_offset_chars;
369
+ }
370
+ assert.ok(parts.join("").endsWith(hugeLine), "resuming across pages reconstructs the matched body line");
371
+ });
372
+ test("notes_search ignores case, treats queries literally, and preserves original Unicode offsets", async () => {
373
+ const session = manager();
374
+ const captured = makeExtension(session);
375
+ const ctx = context(session);
376
+ await call(captured, "notes_write", { address: "case-match.md", content: "😀İ NeEdLe.* tail" }, ctx);
377
+ const found = resultData(await call(captured, "notes_search", { query: ["missing", "needle.*"], pattern: "case-match.md" }, ctx));
378
+ assert.equal(found.files.length, 1);
379
+ assert.equal(found.files[0].matches.length, 1);
380
+ const hit = found.files[0];
381
+ const read = resultRead(await call(captured, "notes_read", { address: hit.address, offset_chars: hit.matches[0].offset_chars }, ctx));
382
+ assert.equal(read.content, "NeEdLe.* tail");
383
+ const absent = resultData(await call(captured, "notes_search", { query: "needle.+", pattern: "case-match.md" }, ctx));
384
+ assert.deepEqual(absent.files, []);
385
+ });
386
+ test("notes_search scopes by glob pattern; a non-matching pattern is an empty page, not an error", async () => {
387
+ const session = manager();
388
+ const captured = makeExtension(session);
389
+ const ctx = context(session);
390
+ await call(captured, "notes_write", { address: "deep/nested/a.md", content: "needle here" }, ctx);
391
+ await call(captured, "notes_write", { address: "top.md", content: "needle there" }, ctx);
392
+ const scoped = resultData(await call(captured, "notes_search", { query: "needle", pattern: "deep/**" }, ctx));
393
+ assert.deepEqual(scoped.files.map((file) => file.address), ["deep/nested/a.md"], "a glob scopes the search to the subtree");
394
+ const none = resultData(await call(captured, "notes_search", { query: "needle", pattern: "absent/**" }, ctx));
395
+ assert.deepEqual(none.files, [], "a non-matching pattern is an empty page, not a refusal");
396
+ });
397
+ test("an over-budget mutation diff is shortened on both surfaces, and the edit still lands whole", async () => {
398
+ const session = manager();
399
+ const captured = makeExtension(session);
400
+ const ctx = context(session);
401
+ const line = `${"a".repeat(300)}\n`;
402
+ await call(captured, "notes_write", { address: "bulk-edit.md", content: line.repeat(1500) }, ctx);
403
+ const raw = await call(captured, "notes_update", { address: "bulk-edit.md", edits: [{ oldText: "a".repeat(300), newText: "b".repeat(300) }], replace_all: true }, ctx);
404
+ assertWithinBudget(raw, "oversized diff receipt");
405
+ const update = resultData(raw);
406
+ assert.equal(update.change_kind, "body");
407
+ assert.equal(update.applied, 1);
408
+ assert.equal(update.diff_truncated, true, "the receipt names that its own diff was shortened");
409
+ assert.ok(update.diff.length > 0, "a shortened diff is still delivered, not emptied");
410
+ assert.match(textOf(raw), /update itself was applied/, "a shortened receipt never claims the note is unchanged");
411
+ assert.equal(textOf(raw).includes(`+${"b".repeat(300)}`), false, "the delivered diff prefix stops inside the first change");
412
+ const body = resultRead(await call(captured, "notes_read", { address: "bulk-edit.md", limit_chars: 300 }, ctx)).content;
413
+ assert.equal(body, "b".repeat(300), "every one of the 1500 replacements was applied, not just the ones that fit the receipt");
414
+ });
415
+ test("oversized note metadata is counted out of a read instead of quietly dropped", async () => {
416
+ const session = manager();
417
+ const captured = makeExtension(session);
418
+ const ctx = context(session);
419
+ const path = physicalPath("session", "fat-meta.md", ctx);
420
+ mkdirSync(dirname(path), { recursive: true });
421
+ const stamp = localIso(Date.now());
422
+ writeFileSync(path, `---\norigin: external\ncreatedAt: ${stamp}\nupdatedAt: ${stamp}\nlastAccessed: ${stamp}\naccessCount: 4\nsmall: kept\nfat: "${"x".repeat(8000)}"\n---\n\nbody text`);
423
+ const raw = await call(captured, "notes_read", { address: "fat-meta.md" }, ctx);
424
+ assertWithinBudget(raw, "read with oversized metadata");
425
+ const read = resultRead(raw);
426
+ const metadata = resultData(raw).metadata;
427
+ assert.equal(read.content, "body text", "metadata size never enters the body window");
428
+ assert.equal(metadata.origin, "external");
429
+ assert.equal("access_count" in metadata, false, "access bookkeeping stays in storage");
430
+ assert.equal(metadata.extra.small, "kept", "a small unrecognized key is delivered");
431
+ assert.equal(metadata.extra.fat, undefined, "an oversized value is not delivered in part");
432
+ assert.deepEqual(metadata.omitted_extra, { keys: 1, bytes: JSON.stringify("fat").length + 1 + JSON.stringify("x".repeat(8000)).length }, "the withheld entry is summarized, never listed, and its key bytes are counted");
433
+ assert.match(textOf(raw), /too large to show/, "the model-facing text says metadata was withheld");
434
+ assert.equal(read.total_chars, 9, "the window counts the body only, whatever the front weighs");
435
+ });
436
+ test("a giant frontmatter key is counted out of a read instead of riding along in the envelope", async () => {
437
+ const session = manager();
438
+ const captured = makeExtension(session);
439
+ const ctx = context(session);
440
+ const path = physicalPath("session", "fat-key.md", ctx);
441
+ mkdirSync(dirname(path), { recursive: true });
442
+ const stamp = localIso(Date.now());
443
+ const giantKey = `k${"x".repeat(40_000)}`;
444
+ writeFileSync(path, `---\norigin: self\ncreatedAt: ${stamp}\nupdatedAt: ${stamp}\nlastAccessed: ${stamp}\naccessCount: 0\n${giantKey}: "v"\nsmall: kept\n---\n\n`);
445
+ const raw = await call(captured, "notes_read", { address: "fat-key.md" }, ctx);
446
+ assertWithinBudget(raw, "read beside a giant frontmatter key");
447
+ const read = resultRead(raw);
448
+ const metadata = resultData(raw).metadata;
449
+ assert.equal(read.content, "", "an empty body stays empty: nothing was borrowed to pay for the key");
450
+ assert.equal(read.total_chars, 0);
451
+ assert.equal(metadata.extra.small, "kept", "a small key beside a giant one is still delivered");
452
+ assert.equal(Object.prototype.hasOwnProperty.call(metadata.extra, giantKey), false, "the giant key is never partially delivered");
453
+ assert.deepEqual(metadata.omitted_extra, { keys: 1, bytes: JSON.stringify(giantKey).length + 1 + JSON.stringify("v").length }, "the accounting covers the key and the value, not the value alone");
454
+ assert.equal(metadata.omitted_extra.bytes > MAX_METADATA_ENTRY_BYTES, true, "one oversized entry is counted in full, key included");
455
+ });
456
+ test("an unexpected notes defect propagates with its own identity while real filesystem refusals stay structured", async () => {
457
+ const session = manager();
458
+ const captured = makeExtension(session);
459
+ const ctx = context(session);
460
+ const identity = notesIdentityFromPi(ctx);
461
+ await call(captured, "notes_write", { address: "propagate.md", content: "before" }, ctx);
462
+ // The injected renderer is this layer's own collaborator: a defect there is a defect in the
463
+ // program, and it must reach the operator as the same Error, not as a fabricated refusal.
464
+ // Its message deliberately opens with "query " — the wording a refusal classification once
465
+ // matched on, which turned any such defect into a wrong invalid_query.
466
+ const sentinel = new TypeError("query renderer invariant broken");
467
+ await assert.rejects(() => notesUpdate.execute({ address: "propagate.md", edits: [{ oldText: "before", newText: "after" }] }, identity, () => { throw sentinel; }), (error) => error === sentinel, "an unexpected failure escapes with the identical Error, message and stack");
468
+ assert.equal(resultRead(await call(captured, "notes_read", { address: "propagate.md" }, ctx)).content, "after", "the edit was applied before the receipt failed; the throw claims no rollback");
469
+ const assertion = Object.assign(new Error("assertion failed"), { code: "ERR_ASSERTION" });
470
+ await assert.rejects(() => notesUpdate.execute({ address: "propagate.md", edits: [{ oldText: "after", newText: "later" }] }, identity, () => { throw assertion; }), (error) => error.code === "ERR_ASSERTION", "a Node ERR_ code is a programmer failure, never an io_error");
471
+ // A genuine filesystem refusal is still an expected outcome, and still says nothing about paths.
472
+ rmSync(scopeDir("session", ctx), { recursive: true, force: true });
473
+ writeFileSync(scopeDir("session", ctx), "not a directory");
474
+ const refusal = resultError(await call(captured, "notes_write", { address: "blocked.md", content: "x" }, ctx));
475
+ assert.equal(refusal.code, "io_error");
476
+ assert.equal(refusal.message, "notes operation failed");
477
+ });
478
+ test("a body that repeats one anchor thousands of times refuses with bounded, counted facts", async () => {
479
+ const session = manager();
480
+ const captured = makeExtension(session);
481
+ const ctx = context(session);
482
+ const repeats = 5000;
483
+ await call(captured, "notes_write", { address: "many.md", content: `${"beta\n".repeat(repeats)}end` }, ctx);
484
+ const raw = await call(captured, "notes_update", { address: "many.md", edits: [{ oldText: "beta", newText: "B" }] }, ctx);
485
+ assertWithinBudget(raw, "refusal with thousands of match lines");
486
+ const refusal = resultError(raw);
487
+ assert.equal(refusal.code, "ambiguous_edit");
488
+ assert.match(refusal.message, /occurs 5000 times \(lines 1, 2, 3, 4, 5, 6, 7, 8, and 4992 more\)/, "the message names a bounded sample and the exact total");
489
+ assert.match(refusal.message, /names 20 of 5000 match lines/, "the receipt says its own line list is partial");
490
+ assert.deepEqual(refusal.details?.line_numbers, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
491
+ assert.equal(refusal.details?.line_numbers_total, repeats, "the full count travels with the sample, so nothing is silently dropped");
492
+ assert.equal(refusal.details?.edit_index, 0);
493
+ assert.equal(resultRead(await call(captured, "notes_read", { address: "many.md", limit_chars: 15 }, ctx)).content, "beta\n".repeat(3), "the refused edit changed nothing");
494
+ const replaced = resultData(await call(captured, "notes_update", { address: "many.md", edits: [{ oldText: "beta", newText: "B" }], replace_all: true }, ctx));
495
+ assertWithinBudget(await call(captured, "notes_read", { address: "many.md" }, ctx), "read after replace_all");
496
+ assert.equal(replaced.applied, 1);
497
+ });
@@ -0,0 +1 @@
1
+ export {};