notesoup 0.0.0-stage → 0.40.0

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