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,404 @@
1
+ import assert from "node:assert/strict";
2
+ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { execFileSync } from "node:child_process";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import test from "node:test";
8
+ import { build } from "esbuild";
9
+ import { dispatch, handleLine } from "../src/claude/helper.js";
10
+ const identity = { home: mkdtempSync(join(tmpdir(), "claude-mod-")), sessionId: "session", cwd: process.cwd(), agent: "claude", model: "claude" };
11
+ async function callTool(tool, params) {
12
+ return await dispatch({ op: "tool", tool, identity, params });
13
+ }
14
+ /**
15
+ * Load the hooks module the way the engine loads it: its own directory decides where the helper is,
16
+ * which `import.meta.dir` expresses at run time. Node has no such global, so the transpiled copy
17
+ * gets the real one; nothing else about the module is changed.
18
+ */
19
+ async function loadHookModule(t) {
20
+ const hooksDir = join(process.cwd(), "mods/notesoup/hooks");
21
+ const transpiled = await build({
22
+ stdin: { contents: readFileSync(join(hooksDir, "register.ts"), "utf8"), loader: "ts", resolveDir: hooksDir, sourcefile: "register.ts" },
23
+ bundle: false, format: "esm", platform: "node", target: "node22", write: false,
24
+ banner: { js: `import.meta.dir = ${JSON.stringify(hooksDir)};` },
25
+ });
26
+ const loaded = mkdtempSync(join(tmpdir(), "claude-hook-module-"));
27
+ t.after(() => rmSync(loaded, { recursive: true, force: true }));
28
+ const module = join(loaded, "register.mjs");
29
+ writeFileSync(module, transpiled.outputFiles[0].text);
30
+ return await import(pathToFileURL(module).href);
31
+ }
32
+ /** An engine that answers the hook by running the real helper against a throwaway notes home. */
33
+ function fakeEngine(home) {
34
+ const registered = [];
35
+ const notifications = [];
36
+ return {
37
+ registered,
38
+ notifications,
39
+ host: {
40
+ env: { get: async (name) => name === "PI_NOTES_HOME" ? home : undefined },
41
+ session: { id: async () => "hook-session", messages: async () => [], usage: async () => ({ context: {} }), compact: async () => ({ skip: "test default" }) },
42
+ command: { register: async (spec) => ({ command: spec.name }) },
43
+ clock: { after: () => { throw new Error("test has no pending manual timer"); } },
44
+ prompt: { submit: async () => undefined },
45
+ tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
46
+ ui: { notify: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
47
+ process: { run: async (argv, init) => ({
48
+ exitCode: 0,
49
+ stdout: execFileSync(argv[0], argv.slice(1), { cwd: init?.cwd, input: init?.stdin, encoding: "utf8" }),
50
+ }) },
51
+ },
52
+ };
53
+ }
54
+ test("Claude helper exposes the five shared note schemas", async () => {
55
+ const schemas = await dispatch({ op: "schemas" });
56
+ assert.deepEqual(schemas.map((schema) => schema.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]);
57
+ assert.ok(schemas.every((schema) => schema.description.length > 20 && schema.inputSchema.type === "object"));
58
+ });
59
+ test("Claude helper delivers the shared text and the shared outcome it came from", async () => {
60
+ const write = await callTool("notes_write", { address: "checkpoint.md", content: "hello" });
61
+ assert.equal(write.outcome.ok, true);
62
+ assert.match(write.text, /checkpoint\.md/);
63
+ assert.equal(write.text.includes("READ WINDOW"), false, "Claude reads the same presentation as Pi");
64
+ const missing = await callTool("notes_read", { address: "absent.md" });
65
+ assert.equal(missing.outcome.ok, false);
66
+ assert.equal(missing.outcome.error?.code, "not_found");
67
+ assert.match(missing.text, /^error: not_found: /, "the refusal renders as the shared error line");
68
+ });
69
+ test("Claude helper rejects malformed or unknown requests", async () => {
70
+ const malformed = JSON.parse(await handleLine("not json"));
71
+ assert.equal(malformed.ok, false);
72
+ assert.match(malformed.error, /Unexpected|malformed/);
73
+ const unknown = JSON.parse(await handleLine(JSON.stringify({ op: "tool", tool: "history_read", identity, params: {} })));
74
+ assert.equal(unknown.ok, false);
75
+ assert.equal(unknown.error, "unknown tool");
76
+ });
77
+ test("Claude helper refuses schema-invalid parameters before any operation runs", async () => {
78
+ const address = "boundary.md";
79
+ const written = await callTool("notes_write", { address, content: "boundary body" });
80
+ assert.equal(written.outcome.ok, true, "the fixture note exists before anything is refused");
81
+ const cases = [
82
+ { name: "a string offset", params: { address, offset_chars: "0" } },
83
+ { name: "a fractional offset", params: { address, offset_chars: 0.5 } },
84
+ { name: "a zero limit", params: { address, max_chars: 0 } },
85
+ { name: "a limit past the maximum", params: { address, max_chars: 999_999_999 } },
86
+ ];
87
+ for (const { name, params } of cases) {
88
+ const refused = JSON.parse(await handleLine(JSON.stringify({ op: "tool", tool: "notes_read", identity, params })));
89
+ assert.equal(refused.ok, false, `${name} is refused at the boundary`);
90
+ assert.equal(refused.error, "invalid notes_read parameters", `${name} names the refused parameters`);
91
+ }
92
+ await assert.rejects(callTool("notes_read", { address, offset_chars: "0" }), /invalid notes_read parameters/);
93
+ // Refusal happens before execute: a rejected mutation leaves nothing on disk.
94
+ await assert.rejects(callTool("notes_write", { address: "rejected.md", content: 42 }), /invalid notes_write parameters/);
95
+ const absent = await callTool("notes_read", { address: "rejected.md" });
96
+ assert.equal(absent.outcome.ok, false);
97
+ assert.equal(absent.outcome.error?.code, "not_found", "the refused write never reached the store");
98
+ const valid = await callTool("notes_read", { address, offset_chars: 0, max_chars: 8 });
99
+ assert.equal(valid.outcome.ok, true, "a schema-valid window still reads");
100
+ assert.match(valid.text, /^boundary\.md/);
101
+ });
102
+ test("Claude helper boot uses actual Claude note tool bindings and a fresh snapshot", async () => {
103
+ const boot = await dispatch({ op: "boot", identity, openedAt: 1700000000000, tools: {
104
+ notes: "mcp__notesoup__notes_*", notesList: "mcp__notesoup__notes_list",
105
+ history: "history unavailable",
106
+ remaining: "remaining unavailable", wipe: "wipe unavailable",
107
+ } });
108
+ assert.match(boot, /mcp__notesoup__notes_\*/);
109
+ assert.match(boot, /claude:session/);
110
+ assert.doesNotMatch(boot, /memory cleared|continuation/);
111
+ });
112
+ test("Claude Mod helper runs from a standalone copied plugin directory", () => {
113
+ const fixture = mkdtempSync(join(tmpdir(), "claude-mod-install-"));
114
+ try {
115
+ const plugin = join(fixture, "notesoup");
116
+ cpSync(join(process.cwd(), "mods/notesoup"), plugin, { recursive: true });
117
+ const hook = readFileSync(join(plugin, "hooks/register.ts"), "utf8");
118
+ assert.ok(hook.includes('${import.meta.dir}/../dist/claude/helper.js'));
119
+ const helper = join(plugin, "dist/claude/helper.js");
120
+ const run = (input) => JSON.parse(execFileSync(process.execPath, [helper], {
121
+ cwd: fixture, input, encoding: "utf8",
122
+ }));
123
+ const schemas = run('{"op":"schemas"}');
124
+ assert.equal(schemas.ok, true);
125
+ assert.equal(schemas.result?.length, 5);
126
+ assert.equal(run("not json").ok, false);
127
+ }
128
+ finally {
129
+ rmSync(fixture, { recursive: true, force: true });
130
+ }
131
+ });
132
+ test("Claude Mod appends boot once and reuses persisted blocks after re-registration", async (t) => {
133
+ const home = mkdtempSync(join(tmpdir(), "claude-hook-home-"));
134
+ t.after(() => rmSync(home, { recursive: true, force: true }));
135
+ // Count the boot requests the hook actually sends while the real helper still answers every one.
136
+ let bootRequests = 0;
137
+ const { host, notifications } = fakeEngine(home);
138
+ const runProcess = host.process.run;
139
+ host.process.run = async (argv, init) => {
140
+ const request = JSON.parse(String(init?.stdin ?? ""));
141
+ if (request.op === "boot")
142
+ bootRequests += 1;
143
+ return await runProcess(argv, init);
144
+ };
145
+ // Each registration is a fresh hook closure, so any dedup it shows lives in the persisted result.
146
+ const registerSession = async () => {
147
+ const hooks = await loadHookModule(t);
148
+ const handlers = new Map();
149
+ hooks.register((event, handler) => handlers.set(event, handler));
150
+ await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async (event) => event);
151
+ return handlers;
152
+ };
153
+ let nextCalls = 0;
154
+ const promptContext = (handlers, result) => handlers.get("prompt.context")(host, { cwd: home }, async () => { nextCalls += 1; return result; });
155
+ const upstream = { blocks: [{ name: "claude:user-context", text: "unrelated upstream block" }], sentinel: "kept" };
156
+ const first = await promptContext(await registerSession(), structuredClone(upstream));
157
+ assert.equal(first.blocks.length, 2, "exactly one boot block joins the upstream blocks");
158
+ assert.deepEqual(first.blocks[0], upstream.blocks[0], "the upstream block is preserved untouched");
159
+ const boot = first.blocks[1];
160
+ assert.equal(boot.name, "notesoup:boot");
161
+ assert.ok(boot.text.length > 0, "the boot block carries real boot text");
162
+ assert.match(boot.text, /mcp__notesoup__notes_\*/, "the boot text names the actual Claude note tool binding");
163
+ assert.equal(first.sentinel, "kept", "unrelated result fields survive");
164
+ assert.equal(bootRequests, 1, "the first prompt makes exactly one boot helper request");
165
+ assert.equal(nextCalls, 1, "the upstream chain runs exactly once per prompt");
166
+ const second = await promptContext(await registerSession(), structuredClone(first));
167
+ assert.deepEqual(second, first, "the persisted result, boot block and sentinel included, is reused unchanged");
168
+ assert.equal(bootRequests, 1, "a persisted boot block needs no second boot helper request");
169
+ assert.equal(nextCalls, 2, "the upstream chain still runs exactly once per prompt");
170
+ assert.deepEqual(notifications, [], "successful boot never notifies");
171
+ });
172
+ test("Claude Mod boot failure preserves fallback with available, absent, or failing notifications", async (t) => {
173
+ for (const mode of ["available", "no ui", "no notify", "throws", "rejects"]) {
174
+ await t.test(mode, async (t) => {
175
+ const hooks = await loadHookModule(t);
176
+ const home = mkdtempSync(join(tmpdir(), "claude-hook-home-"));
177
+ t.after(() => rmSync(home, { recursive: true, force: true }));
178
+ const { host, notifications } = fakeEngine(home);
179
+ if (mode === "no ui")
180
+ delete host.ui;
181
+ else if (mode === "no notify")
182
+ host.ui = {};
183
+ else if (mode === "throws" || mode === "rejects") {
184
+ host.ui = { notify: (text) => {
185
+ notifications.push(text);
186
+ if (mode === "throws")
187
+ throw new Error("notification unavailable");
188
+ return Promise.reject(new Error("notification unavailable"));
189
+ } };
190
+ }
191
+ let bootRequests = 0;
192
+ const runProcess = host.process.run;
193
+ host.process.run = async (argv, init) => {
194
+ const request = JSON.parse(String(init?.stdin ?? ""));
195
+ if (request.op === "boot") {
196
+ bootRequests += 1;
197
+ return { exitCode: 1, stdout: "" };
198
+ }
199
+ return await runProcess(argv, init);
200
+ };
201
+ const handlers = new Map();
202
+ hooks.register((event, handler) => handlers.set(event, handler));
203
+ await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async (event) => event);
204
+ let nextCalls = 0;
205
+ const promptContext = (result) => handlers.get("prompt.context")(host, { cwd: home }, async () => { nextCalls += 1; return result; });
206
+ const upstream = { blocks: [{ name: "claude:user-context", text: "unrelated upstream block" }], sentinel: "kept" };
207
+ const failed = await promptContext(structuredClone(upstream));
208
+ assert.deepEqual(failed, {
209
+ ...upstream,
210
+ blocks: [...upstream.blocks, { name: "notesoup:boot", text: "# notesoup\nhelper exited unsuccessfully" }],
211
+ }, "boot failure keeps the original fallback and upstream fields even if notify is absent or fails");
212
+ const expectedNotifications = mode === "no ui" || mode === "no notify" ? [] : ["notesoup: Notes boot failed."];
213
+ assert.deepEqual(notifications, expectedNotifications, "one user-facing notification names notesoup and the notes boot failure");
214
+ assert.equal(bootRequests, 1);
215
+ assert.equal(nextCalls, 1);
216
+ assert.deepEqual(await promptContext(structuredClone(failed)), failed);
217
+ assert.deepEqual(notifications, expectedNotifications, "a persisted fallback does not notify again");
218
+ assert.equal(bootRequests, 1, "a persisted fallback needs no second boot request");
219
+ assert.equal(nextCalls, 2, "the upstream chain still runs exactly once per prompt");
220
+ });
221
+ }
222
+ });
223
+ test("Claude Mod hook delivers the helper's shared text, and marks only a refusal as an error", async (t) => {
224
+ const hooks = await loadHookModule(t);
225
+ const home = mkdtempSync(join(tmpdir(), "claude-hook-home-"));
226
+ t.after(() => rmSync(home, { recursive: true, force: true }));
227
+ const { host, registered } = fakeEngine(home);
228
+ const handlers = new Map();
229
+ hooks.register((event, handler) => handlers.set(event, handler));
230
+ await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async (event) => event);
231
+ assert.deepEqual(registered.map((spec) => spec.name), ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]);
232
+ for (const spec of registered) {
233
+ assert.equal(spec.isDeferred, false, `${spec.name} is available from the start without tool search`);
234
+ assert.ok(spec.description.length > 20);
235
+ assert.equal(spec.inputSchema.type, "object");
236
+ }
237
+ const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "hook-1", ...params }, async (event) => event);
238
+ const written = await call("notes_write", { address: "hook.md", content: "hook body" });
239
+ assert.equal(written.result, "created hook.md", "the hook hands back the shared text unchanged");
240
+ assert.equal("isError" in written, false, "a success carries no discriminator at all, not a false one");
241
+ const refused = await call("notes_read", { address: "absent.md" });
242
+ assert.equal(refused.isError, true, "a refusal carries the literal the public ToolCallResult declares");
243
+ assert.match(String(refused.result), /^error: not_found: /, "the refusal reads as the shared error line");
244
+ // A tool this plugin never registered is somebody else's answer, not a notesoup refusal.
245
+ const foreign = await call("other_tool", {});
246
+ assert.equal("result" in foreign, false, "an unregistered tool falls through to the engine's own handling");
247
+ });
248
+ test("Claude Mod resets at 85 after the turn, retains one fresh boot and deduplicates measure", async (t) => {
249
+ const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
250
+ t.after(() => rmSync(home, { recursive: true, force: true }));
251
+ const { host, registered, notifications } = fakeEngine(home);
252
+ const handlers = new Map();
253
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
254
+ const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
255
+ let percent = 84;
256
+ let compactions = 0;
257
+ let kept = [];
258
+ host.session.usage = async () => ({ context: { percent } });
259
+ host.session.compact = async ({ instructions }) => {
260
+ compactions++;
261
+ const result = await invoke("session.compact", { trigger: "plugin", instructions: `${instructions} (rewritten upstream)`, messages: [{ role: "user", text: "OLD_SECRET" }] });
262
+ kept = result.messages;
263
+ percent = undefined; // The real engine invalidates token usage after compact.
264
+ return result;
265
+ };
266
+ await invoke("session.start", { cwd: home, isInteractive: true });
267
+ assert.equal(registered.length, 5);
268
+ const initial = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
269
+ assert.match(initial.blocks[0].text, /Current context window id: claude:hook-session:0/);
270
+ await invoke("turn.start");
271
+ await invoke("session.measure");
272
+ await invoke("turn.complete");
273
+ assert.equal(compactions, 0, "84 is below the fixed threshold");
274
+ host.session.usage = async () => { throw new Error("usage unavailable"); };
275
+ await invoke("session.measure");
276
+ await invoke("turn.complete");
277
+ assert.equal(notifications.filter((text) => text.includes("context usage unavailable")).length, 1, "usage failure logs once per session");
278
+ host.session.usage = async () => ({ context: { percent } });
279
+ await dispatch({ op: "tool", tool: "notes_write", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, params: { address: "@human/MAP.md", content: "FRESH_NOTES_AT_RESET" } });
280
+ await invoke("turn.start");
281
+ percent = 85;
282
+ await invoke("session.measure");
283
+ assert.equal(compactions, 0, "measure cannot compact under a running turn");
284
+ assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" });
285
+ assert.equal(compactions, 1);
286
+ assert.equal(kept.length, 1);
287
+ assert.equal(kept[0].role, "user");
288
+ assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
289
+ assert.match(kept[0].text, /Previous context window id: claude:hook-session:0/);
290
+ assert.match(kept[0].text, /FRESH_NOTES_AT_RESET/);
291
+ assert.doesNotMatch(kept[0].text, /OLD_SECRET/);
292
+ await invoke("session.measure");
293
+ assert.equal(compactions, 1, "invalidated percent cannot immediately reset twice");
294
+ const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
295
+ assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => upstream), upstream, "the retained boot is not injected a second time");
296
+ });
297
+ test("Claude Mod headless detection skips compaction and logs once", async (t) => {
298
+ const home = mkdtempSync(join(tmpdir(), "claude-headless-home-"));
299
+ t.after(() => rmSync(home, { recursive: true, force: true }));
300
+ const { host, notifications } = fakeEngine(home);
301
+ const handlers = new Map();
302
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
303
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({ sentinel: name }));
304
+ let percent;
305
+ let attempts = 0;
306
+ host.session.usage = async () => ({ context: { percent } });
307
+ host.session.compact = async () => { attempts++; throw new Error("not available in a headless (-p / SDK) session yet"); };
308
+ await invoke("session.start", { cwd: home, isInteractive: false });
309
+ await invoke("turn.start");
310
+ await invoke("turn.complete");
311
+ await invoke("session.measure");
312
+ assert.equal(attempts, 0, "no counters means no automatic reset");
313
+ percent = 85;
314
+ await invoke("turn.start");
315
+ assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" }, "a rejection does not break the turn chain");
316
+ await invoke("session.measure");
317
+ await invoke("turn.complete");
318
+ assert.equal(attempts, 0, "headless sessions skip the unsupported capability from startup");
319
+ assert.deepEqual(notifications, ["notesoup: reset skipped in headless (-p / SDK) session."]);
320
+ const manual = await invoke("command.run", { command: "clear-memory" });
321
+ assert.match(manual.text, /reset skipped in headless/);
322
+ assert.equal(notifications.length, 1);
323
+ const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
324
+ assert.match(boot.blocks[0].text, /Current context window id: claude:hook-session:0/);
325
+ });
326
+ test("Claude Mod refuses to wipe on boot failure and can retry without advancing the window", async (t) => {
327
+ const home = mkdtempSync(join(tmpdir(), "claude-reset-failure-"));
328
+ t.after(() => rmSync(home, { recursive: true, force: true }));
329
+ const { host } = fakeEngine(home);
330
+ const handlers = new Map();
331
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
332
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
333
+ await invoke("session.start", { cwd: home, isInteractive: true });
334
+ const run = host.process.run;
335
+ let failBoot = true;
336
+ host.process.run = async (argv, init) => {
337
+ if (JSON.parse(init.stdin).op === "boot" && failBoot)
338
+ return { exitCode: 1, stdout: "" };
339
+ return run(argv, init);
340
+ };
341
+ host.session.usage = async () => ({ context: { percent: 85 } });
342
+ let result = {};
343
+ host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
344
+ await invoke("turn.start");
345
+ await invoke("turn.complete");
346
+ assert.match(result.skip, /Notes boot failed/);
347
+ assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
348
+ failBoot = false;
349
+ await invoke("turn.start");
350
+ await invoke("turn.complete");
351
+ assert.equal(result.skip, undefined);
352
+ assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
353
+ });
354
+ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its boot on reload", async (t) => {
355
+ const home = mkdtempSync(join(tmpdir(), "claude-manual-home-"));
356
+ t.after(() => rmSync(home, { recursive: true, force: true }));
357
+ const { host } = fakeEngine(home);
358
+ let handlers = new Map();
359
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
360
+ const timers = [];
361
+ const prompts = [];
362
+ let kept = [];
363
+ let compactions = 0;
364
+ host.clock.after = (_ms, callback) => { timers.push(callback); };
365
+ host.session.compact = async ({ instructions }) => {
366
+ compactions++;
367
+ const result = await invoke("session.compact", { trigger: "plugin", instructions });
368
+ kept = result.messages;
369
+ return result;
370
+ };
371
+ host.prompt.submit = async ({ text }) => {
372
+ prompts.push(text);
373
+ await invoke("turn.start");
374
+ await invoke("turn.complete");
375
+ };
376
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
377
+ await invoke("session.start", { cwd: home, isInteractive: true });
378
+ const command = await invoke("command.run", { command: "clear-memory" });
379
+ assert.match(command.text, /closing out/);
380
+ await Promise.resolve();
381
+ assert.equal(compactions, 0, "command.run must not call compact under its held turn");
382
+ assert.equal(timers.length, 1);
383
+ await timers.shift()();
384
+ assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
385
+ assert.equal(compactions, 1);
386
+ assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
387
+ host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
388
+ handlers = new Map();
389
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
390
+ await invoke("session.start", { cwd: home, isInteractive: true });
391
+ assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] })), { blocks: [] }, "reload does not duplicate the already-retained boot");
392
+ await invoke("turn.start");
393
+ await invoke("command.run", { command: "clear-memory" });
394
+ await invoke("turn.complete");
395
+ assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
396
+ assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
397
+ });
398
+ test("Claude dream skill projection stays byte-identical to canonical shared files", () => {
399
+ assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md")), readFileSync(join(process.cwd(), "skills/dream/SKILL.md")));
400
+ assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/playbook.md")), readFileSync(join(process.cwd(), "playbook.md")));
401
+ const skill = readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md"), "utf8");
402
+ assert.match(skill, /\.\.\/\.\.\/playbook\.md/);
403
+ assert.doesNotMatch(skill, /Claude.*runner|dream runner/i);
404
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,101 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import test from "node:test";
8
+ import ts from "typescript";
9
+ import { dependencyViolations, moduleReferences } from "./helpers/dependency-graph.js";
10
+ import * as entry from "../src/index.js";
11
+ import notesoup, { createNotesoup } from "../src/pi/extension.js";
12
+ function repository() {
13
+ let root = dirname(fileURLToPath(import.meta.url));
14
+ while (!existsSync(join(root, "tsconfig.json")))
15
+ root = dirname(root);
16
+ return root;
17
+ }
18
+ function sources(directory) {
19
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? sources(join(directory, entry.name)) : entry.name.endsWith(".ts") ? [join(directory, entry.name)] : []);
20
+ }
21
+ const options = { module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext, target: ts.ScriptTarget.ES2022 };
22
+ test("all shared domains resolve without any direct or transitive SDK, Pi adapter or root entry dependency", () => {
23
+ const root = repository();
24
+ const config = ts.readConfigFile(join(root, "tsconfig.json"), ts.sys.readFile);
25
+ assert.equal(config.error, undefined);
26
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root);
27
+ assert.deepEqual(parsed.errors, []);
28
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
29
+ const shared = sources(join(root, "src")).filter((file) => !file.startsWith(join(root, "src/pi/")) && file !== join(root, "src/index.ts"));
30
+ for (const domain of ["notes", "boot", "history", "budget", "tools", "dream"])
31
+ assert.ok(shared.some((file) => file.startsWith(join(root, "src", domain) + "/")), `${domain} is included`);
32
+ assert.deepEqual(dependencyViolations(root, shared, parsed.options, new Set(["typebox"])), []);
33
+ for (const name of ["@earendil-works/pi-agent-core", "@earendil-works/pi-ai", "@earendil-works/pi-coding-agent", "typebox"]) {
34
+ assert.equal(manifest.dependencies?.[name], undefined, `${name} is supplied by the host`);
35
+ assert.equal(manifest.peerDependencies[name], "*", `${name} follows Pi's host dependency contract`);
36
+ }
37
+ });
38
+ test("dependency guard follows indirect types, re-exports, dynamic imports and import-type edges through resolved aliases", (t) => {
39
+ const root = mkdtempSync(join(tmpdir(), "context-dependencies-"));
40
+ t.after(() => rmSync(root, { recursive: true, force: true }));
41
+ const put = (path, text) => { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), text); };
42
+ put("package.json", '{"type":"module"}');
43
+ put("src/pi/native.ts", "export type Native = string;");
44
+ put("src/index.ts", 'export * from "./pi/native.js";');
45
+ put("src/notes/bridge.ts", 'export type { Native } from "@native";');
46
+ put("src/notes/identity.ts", 'import type { Native } from "./bridge.js"; export type Identity = Native;');
47
+ put("src/dream/jail.ts", 'export const backend = () => import("../index.js");');
48
+ put("src/boot/snapshot.ts", 'export type Snapshot = import("../pi/native.js").Native;');
49
+ put("src/history/decoder.ts", 'import type { SessionEntry } from "@earendil-works/pi-coding-agent"; export type Entry = SessionEntry;');
50
+ put("src/history/query.ts", 'export type { Entry } from "./decoder.js";');
51
+ const fixtureOptions = { ...options, baseUrl: root, paths: { "@native": ["src/pi/native.ts"] } };
52
+ const violations = dependencyViolations(root, ["src/notes/identity.ts", "src/dream/jail.ts", "src/boot/snapshot.ts", "src/history/query.ts"], fixtureOptions, new Set());
53
+ assert.deepEqual(violations, [
54
+ "src/notes/identity.ts -> src/notes/bridge.ts -> src/pi/native.ts",
55
+ "src/dream/jail.ts -> src/index.ts",
56
+ "src/boot/snapshot.ts -> src/pi/native.ts",
57
+ "src/history/query.ts -> src/history/decoder.ts -> @earendil-works/pi-coding-agent",
58
+ ]);
59
+ put("src/notes/bridge.ts", 'export type { Value as Native } from "./safe.js";');
60
+ put("src/notes/safe.ts", "export type Value = string;");
61
+ assert.deepEqual(dependencyViolations(root, ["src/notes/identity.ts"], fixtureOptions, new Set()), [], "a host-neutral type/re-export chain is allowed");
62
+ });
63
+ test("AST guard sees every literal module edge, not import-like prose or comments", () => {
64
+ const source = ts.createSourceFile("edges.ts", `
65
+ // import("not-an-edge")
66
+ const prose = 'import("also-not-an-edge")';
67
+ import type { T } from "type-import";
68
+ export type { T } from "type-reexport";
69
+ export * from "reexport";
70
+ type T = import("import-type").T;
71
+ const load = () => import("dynamic-import");
72
+ import legacy = require("import-equals");
73
+ const other = require("require-call");
74
+ `, ts.ScriptTarget.Latest, true);
75
+ assert.deepEqual(moduleReferences(source), ["type-import", "type-reexport", "reexport", "import-type", "dynamic-import", "import-equals", "require-call"]);
76
+ });
77
+ test("the intentional root exports only the Pi extension and its settings-bound factory", () => {
78
+ assert.deepEqual(Object.keys(entry).sort(), ["createNotesoup", "default"]);
79
+ assert.equal(entry.default, notesoup);
80
+ assert.equal(entry.createNotesoup, createNotesoup);
81
+ assert.equal(typeof entry.createNotesoup(), "function");
82
+ });
83
+ test("configured extension source and moved dream CLI are executable current entries", async () => {
84
+ const root = repository();
85
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
86
+ const entrySource = resolve(root, manifest.pi.extensions[0]);
87
+ assert.ok(existsSync(entrySource), "the manifest entry exists as TypeScript source (Pi loads it directly; plain Node cannot)");
88
+ const built = await import(pathToFileURL(resolve(root, "dist/src/index.js")).href);
89
+ const tools = [];
90
+ const commands = [];
91
+ built.default({
92
+ on() { },
93
+ registerTool(tool) { tools.push(tool); },
94
+ registerCommand(name) { commands.push(name); },
95
+ });
96
+ assert.deepEqual(tools.map((tool) => tool.name).sort(), ["clear_memory", "get_context_remaining", "history_list", "history_read", "history_windows", "notes_list", "notes_read", "notes_search", "notes_update", "notes_write"]);
97
+ assert.deepEqual(commands.sort(), ["clear-memory", "cm", "notesoup"]);
98
+ const help = execFileSync(process.execPath, [resolve(root, manifest.bin.dream), "--help"], { cwd: root, encoding: "utf8" });
99
+ assert.ok(help.startsWith("dream doctor [--notes-home <dir>]"));
100
+ assert.ok(help.includes("Default playbook: <installed package root>/playbook.md"));
101
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ import assert from "node:assert/strict";
2
+ import { main } from "../src/pi/dream/cli.js";
3
+ import { doctor } from "../src/dream/doctor.js";
4
+ import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import test from "node:test";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ const note = "---\norigin: self\ncreatedAt: 2026-01-01T00:00:00Z\nupdatedAt: 2026-01-01T00:00:00Z\nlastAccessed: 2026-01-01T00:00:00Z\naccessCount: 0\n---\n\n";
9
+ test("doctor ignores unknown frontmatter keys while validating canonical metadata", (t) => {
10
+ const root = mkdtempSync(join(tmpdir(), "dream-doctor-extra-"));
11
+ t.after(() => rmSync(root, { recursive: true, force: true }));
12
+ mkdirSync(join(root, "human"));
13
+ writeFileSync(join(root, "human/extra.md"), note.replace("accessCount: 0", "accessCount: 0\ncreated_at: 2025-01-01\nupdated_at: 2025-01-01\nlast_accessed: 2025-01-01\naccess_count: 7\nsource_window: old\nrecurrence_count: 2\nrecurrence_windows: old"));
14
+ assert.deepEqual(doctor(root), [], "unknown fields have no special diagnostics");
15
+ });
16
+ test("doctor validates crumpledAt as an optional ISO timestamp", (t) => {
17
+ const root = mkdtempSync(join(tmpdir(), "dream-doctor-crumpled-"));
18
+ t.after(() => rmSync(root, { recursive: true, force: true }));
19
+ mkdirSync(join(root, "human"));
20
+ writeFileSync(join(root, "human/valid.md"), note.replace("accessCount: 0", "accessCount: 0\ncrumpledAt: 2026-01-02T00:00:00Z"));
21
+ writeFileSync(join(root, "human/bad.md"), note.replace("accessCount: 0", "accessCount: 0\ncrumpledAt: yesterday"));
22
+ assert.deepEqual(doctor(root), ["human/bad.md: missing/invalid crumpledAt; use an ISO timestamp"]);
23
+ });
24
+ test("doctor validates without repairing files or running the dreamer", async () => {
25
+ const root = mkdtempSync(join(tmpdir(), "dream-doctor-test-"));
26
+ mkdirSync(join(root, "human"));
27
+ writeFileSync(join(root, "human/a.md"), note);
28
+ writeFileSync(join(root, "human/MAP.md"), `${note}- \`a.md\``);
29
+ const before = readFileSync(join(root, "human/a.md"));
30
+ assert.deepEqual(doctor(root), []);
31
+ assert.equal(await main(["doctor", "--notes-home", root], { runDreamer: async () => { throw new Error("must not run"); } }), 0);
32
+ assert.deepEqual(readFileSync(join(root, "human/a.md")), before);
33
+ assert.deepEqual(readdirSync(root), ["human"]);
34
+ const missing = join(root, "absent");
35
+ assert.equal(await main(["doctor", "--notes-home", missing]), 1);
36
+ assert.equal(existsSync(missing), false);
37
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,72 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import test from "node:test";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { loadSkillsFromDir } from "@earendil-works/pi-coding-agent";
9
+ import { loadPlaybook } from "../src/dream/playbook.js";
10
+ function packageRoot() {
11
+ let dir = dirname(fileURLToPath(import.meta.url));
12
+ while (!existsSync(join(dir, "package.json"))) {
13
+ const parent = dirname(dir);
14
+ if (parent === dir)
15
+ throw new Error("could not locate package root");
16
+ dir = parent;
17
+ }
18
+ return dir;
19
+ }
20
+ function discoverSkill(skillsDir, name) {
21
+ const result = loadSkillsFromDir({ dir: skillsDir, source: "path" });
22
+ assert.deepEqual(result.diagnostics, []);
23
+ const skill = result.skills.find((candidate) => candidate.name === name);
24
+ assert.ok(skill, `Pi's public skill loader discovers ${name}`);
25
+ assert.ok(skill.description.length > 0);
26
+ return skill;
27
+ }
28
+ test("dream skill is publicly discoverable and resolves the CLI's shared playbook", () => {
29
+ const root = packageRoot();
30
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
31
+ assert.deepEqual(manifest.pi.skills, ["./skills"]);
32
+ assert.deepEqual(manifest.pi.extensions, ["./src/index.ts"]);
33
+ assert.equal(manifest.bin.dream, "dist/src/pi/dream/cli.js");
34
+ assert.ok(manifest.files.includes("skills"));
35
+ discoverSkill(join(root, "skills"), "memory");
36
+ const skill = discoverSkill(join(root, "skills"), "dream");
37
+ const skillPlaybook = resolve(skill.baseDir, "../../playbook.md");
38
+ const packagePlaybook = resolve(root, "playbook.md");
39
+ assert.equal(skillPlaybook, packagePlaybook);
40
+ const playbook = readFileSync(packagePlaybook, "utf8");
41
+ assert.equal(loadPlaybook(skillPlaybook), playbook);
42
+ });
43
+ test("npm tarball keeps the skill's relative playbook path portable after extraction", () => {
44
+ const root = packageRoot();
45
+ const fixture = mkdtempSync(join(tmpdir(), "dream-skill-pack-"));
46
+ try {
47
+ const packed = JSON.parse(execFileSync("npm", ["pack", "--offline", "--ignore-scripts", "--json", "--pack-destination", fixture], {
48
+ cwd: root,
49
+ encoding: "utf8",
50
+ stdio: ["ignore", "pipe", "pipe"],
51
+ }))[0];
52
+ const packedPaths = packed.files.map((file) => file.path);
53
+ assert.ok(packedPaths.includes("skills/dream/SKILL.md"));
54
+ assert.ok(packedPaths.includes("skills/memory/SKILL.md"));
55
+ assert.ok(packedPaths.includes("playbook.md"));
56
+ assert.ok(packedPaths.includes("src/index.ts"));
57
+ assert.ok(packedPaths.includes("dist/src/pi/dream/cli.js"));
58
+ const extracted = join(fixture, "extracted");
59
+ execFileSync("mkdir", ["-p", extracted]);
60
+ execFileSync("tar", ["-xzf", join(fixture, packed.filename), "-C", extracted]);
61
+ const installedRoot = join(extracted, "package");
62
+ discoverSkill(join(installedRoot, "skills"), "memory");
63
+ const installedSkill = discoverSkill(join(installedRoot, "skills"), "dream");
64
+ const referencedPlaybook = resolve(installedSkill.baseDir, "../../playbook.md");
65
+ assert.equal(referencedPlaybook, resolve(installedRoot, "playbook.md"));
66
+ assert.equal(loadPlaybook(referencedPlaybook), readFileSync(referencedPlaybook, "utf8"));
67
+ assert.equal(loadPlaybook(referencedPlaybook), readFileSync(join(root, "playbook.md"), "utf8"));
68
+ }
69
+ finally {
70
+ rmSync(fixture, { recursive: true, force: true });
71
+ }
72
+ });
@@ -0,0 +1 @@
1
+ export {};