notesoup 0.53.1 → 0.54.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 (153) hide show
  1. package/README.md +2 -2
  2. package/dist/plugins/claude/src/helper.js +2 -1
  3. package/dist/plugins/claude/src/history.js +2 -3
  4. package/dist/plugins/claude/src/thresholds.js +4 -2
  5. package/dist/plugins/codex/src/hooks.js +1 -1
  6. package/dist/plugins/codex/src/identity.d.ts +1 -1
  7. package/dist/plugins/codex/src/identity.js +3 -3
  8. package/dist/plugins/codex/src/mcp.js +2 -1
  9. package/dist/plugins/codex/src/text.d.ts +1 -1
  10. package/dist/plugins/codex/src/text.js +2 -2
  11. package/dist/plugins/dsh/engine.js +2 -2
  12. package/dist/plugins/dsh/tools.js +8 -7
  13. package/dist/plugins/dsh/window.d.ts +1 -0
  14. package/dist/plugins/dsh/window.js +7 -3
  15. package/dist/plugins/pi/entries.d.ts +1 -0
  16. package/dist/plugins/pi/entries.js +1 -0
  17. package/dist/plugins/pi/history-tools.d.ts +1 -1
  18. package/dist/plugins/pi/history-tools.js +4 -4
  19. package/dist/plugins/pi/marker.d.ts +9 -0
  20. package/dist/plugins/pi/marker.js +36 -0
  21. package/dist/plugins/pi/notes/tools.js +8 -6
  22. package/dist/plugins/pi/render.js +7 -4
  23. package/dist/plugins/pi/reset/artifacts.d.ts +2 -2
  24. package/dist/plugins/pi/reset/artifacts.js +2 -2
  25. package/dist/plugins/pi/runtime.js +11 -8
  26. package/dist/plugins/pi/text.d.ts +2 -0
  27. package/dist/plugins/pi/text.js +4 -0
  28. package/dist/plugins/pi/window.js +21 -7
  29. package/dist/src/boot/render.js +7 -7
  30. package/dist/src/boot/snapshot.d.ts +7 -7
  31. package/dist/src/boot/snapshot.js +17 -17
  32. package/dist/src/boot/text.d.ts +2 -2
  33. package/dist/src/boot/text.js +7 -5
  34. package/dist/src/dream/git.d.ts +2 -11
  35. package/dist/src/dream/git.js +6 -23
  36. package/dist/src/dream/lock.d.ts +2 -2
  37. package/dist/src/dream/lock.js +3 -3
  38. package/dist/src/index.d.ts +2 -1
  39. package/dist/src/index.js +3 -2
  40. package/dist/src/notes/address.d.ts +8 -8
  41. package/dist/src/notes/address.js +13 -13
  42. package/dist/src/notes/errors.d.ts +1 -1
  43. package/dist/src/notes/frontmatter.js +2 -2
  44. package/dist/src/notes/index.d.ts +1 -1
  45. package/dist/src/notes/index.js +1 -1
  46. package/dist/src/notes/paths.d.ts +6 -6
  47. package/dist/src/notes/paths.js +9 -9
  48. package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
  49. package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
  50. package/dist/src/notes/store.d.ts +4 -4
  51. package/dist/src/notes/store.js +55 -52
  52. package/dist/src/tools/dream.d.ts +21 -3
  53. package/dist/src/tools/dream.js +54 -16
  54. package/dist/src/tools/notes-context.d.ts +10 -0
  55. package/dist/src/tools/notes-context.js +27 -0
  56. package/dist/src/tools/notes.d.ts +69 -20
  57. package/dist/src/tools/notes.js +40 -31
  58. package/dist/test/agent-loop.test.js +8 -8
  59. package/dist/test/boot.integration.test.js +5 -5
  60. package/dist/test/claude-history.test.js +26 -0
  61. package/dist/test/claude-mod.test.js +257 -86
  62. package/dist/test/codex-plugin.test.js +18 -1
  63. package/dist/test/context-edit-budget.test.js +121 -0
  64. package/dist/test/dependencies.test.js +71 -4
  65. package/dist/test/dream-tools.test.js +153 -8
  66. package/dist/test/dsh.test.js +62 -15
  67. package/dist/test/helpers/dsh.d.ts +4 -1
  68. package/dist/test/helpers/dsh.js +20 -4
  69. package/dist/test/helpers/extension.d.ts +5 -0
  70. package/dist/test/helpers/extension.js +33 -2
  71. package/dist/test/host-neutral.test.js +17 -15
  72. package/dist/test/marker.test.js +78 -0
  73. package/dist/test/model-facing-text.test.js +12 -8
  74. package/dist/test/notes-cwd.test.d.ts +1 -0
  75. package/dist/test/notes-cwd.test.js +114 -0
  76. package/dist/test/notes-library.test.js +4 -4
  77. package/dist/test/notes-query-namespaces.test.d.ts +1 -0
  78. package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
  79. package/dist/test/notes.integration.test.js +72 -23
  80. package/dist/test/notes.test.js +50 -20
  81. package/dist/test/pi-render.test.js +33 -1
  82. package/dist/test/project-namespace.test.d.ts +1 -0
  83. package/dist/test/project-namespace.test.js +324 -0
  84. package/dist/test/reset-lifecycle.test.js +12 -0
  85. package/docs/architecture.md +13 -8
  86. package/docs/claude-code-mod.md +7 -7
  87. package/docs/codex.md +4 -4
  88. package/docs/dsh.md +8 -8
  89. package/docs/notes-library.md +9 -5
  90. package/docs/skills.md +3 -3
  91. package/docs/tool-results.md +6 -2
  92. package/package.json +4 -6
  93. package/playbook.md +6 -6
  94. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  95. package/plugins/claude/dist/claude/helper.js +681 -617
  96. package/plugins/claude/hooks/register.ts +61 -65
  97. package/plugins/claude/playbook.md +6 -6
  98. package/plugins/claude/skills/memory/SKILL.md +4 -4
  99. package/plugins/claude/src/helper.ts +3 -2
  100. package/plugins/claude/src/history.ts +2 -3
  101. package/plugins/claude/src/thresholds.ts +4 -2
  102. package/plugins/codex/README.md +1 -1
  103. package/plugins/codex/dist/codex/notesoup.js +877 -815
  104. package/plugins/codex/src/hooks.ts +1 -1
  105. package/plugins/codex/src/identity.ts +3 -3
  106. package/plugins/codex/src/mcp.ts +2 -1
  107. package/plugins/codex/src/text.ts +2 -2
  108. package/plugins/dsh/engine.ts +2 -2
  109. package/plugins/dsh/tools.ts +8 -7
  110. package/plugins/dsh/window.ts +8 -3
  111. package/plugins/paseo/OVERVIEW.md +4 -4
  112. package/plugins/paseo/README.md +1 -1
  113. package/plugins/paseo/client/brain-empty-card.tsx +3 -4
  114. package/plugins/paseo/client/markdown.tsx +179 -0
  115. package/plugins/paseo/client/notes-op-card.tsx +35 -34
  116. package/plugins/paseo/client/notes-op-transformer.ts +17 -68
  117. package/plugins/paseo/client/paper-card.tsx +8 -19
  118. package/plugins/paseo/client/paper-palette.ts +40 -0
  119. package/plugins/paseo/client/sticky-card.tsx +6 -4
  120. package/plugins/paseo/package.json +3 -0
  121. package/plugins/paseo/paseo-plugin.json +2 -2
  122. package/plugins/paseo/shared/notes-op.ts +13 -9
  123. package/plugins/paseo/test/notes-op.test.ts +52 -73
  124. package/plugins/paseo/test/paper-palette.test.ts +54 -0
  125. package/plugins/pi/entries.ts +1 -0
  126. package/plugins/pi/history-tools.ts +4 -4
  127. package/plugins/pi/marker.ts +39 -0
  128. package/plugins/pi/notes/tools.ts +8 -6
  129. package/plugins/pi/render.ts +6 -4
  130. package/plugins/pi/reset/artifacts.ts +2 -2
  131. package/plugins/pi/runtime.ts +9 -8
  132. package/plugins/pi/text.ts +5 -0
  133. package/plugins/pi/window.ts +22 -7
  134. package/skills/memory/SKILL.md +4 -4
  135. package/src/boot/render.ts +8 -8
  136. package/src/boot/snapshot.ts +20 -20
  137. package/src/boot/text.ts +7 -5
  138. package/src/dream/git.ts +7 -24
  139. package/src/dream/lock.ts +3 -3
  140. package/src/index.ts +4 -3
  141. package/src/notes/address.ts +13 -13
  142. package/src/notes/errors.ts +1 -1
  143. package/src/notes/frontmatter.ts +2 -2
  144. package/src/notes/index.ts +1 -1
  145. package/src/notes/paths.ts +9 -9
  146. package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
  147. package/src/notes/store.ts +61 -58
  148. package/src/tools/dream.ts +63 -16
  149. package/src/tools/notes-context.ts +29 -0
  150. package/src/tools/notes.ts +39 -29
  151. package/dist/test/project-home.test.js +0 -134
  152. /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
  153. /package/dist/test/{project-home.test.d.ts → marker.test.d.ts} +0 -0
@@ -162,7 +162,7 @@ test("a copied plugin without src or node_modules still initializes and lists al
162
162
  assert.match(refusal, /child post-compact boot/);
163
163
  });
164
164
  /* ---------------------------------------------------------------- MCP tools */
165
- test("notes tools use the hook thread as the session home and the current turn model as @model", async (t) => {
165
+ test("notes tools use the hook thread as the session notebook and the current turn model as @model", async (t) => {
166
166
  const f = await fixture(t);
167
167
  await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
168
168
  await bind(f.data, { threadId: ROOT, rootSessionId: ROOT, home: f.home, cwd: f.cwd, transcriptPath: f.transcript });
@@ -185,6 +185,23 @@ test("notes tools use the hook thread as the session home and the current turn m
185
185
  const listed = await call(client, { name: "notes_list", arguments: { glob: "@model/**" }, _meta: meta });
186
186
  assert.match(textOf(listed), /@model\/model\.md/);
187
187
  });
188
+ test("Codex resolves relative cwd against the verified binding, not the MCP process", async (t) => {
189
+ const f = await fixture(t);
190
+ await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
191
+ const base = join(f.home, "base"), other = join(f.home, "other");
192
+ await mkdir(base);
193
+ await mkdir(other);
194
+ await bind(f.data, { threadId: ROOT, rootSessionId: ROOT, home: f.home, cwd: base, transcriptPath: f.transcript });
195
+ const client = await connect(t, f.data, CLI, f.home);
196
+ const meta = metaFor(ROOT, ROOT);
197
+ const written = await call(client, { name: "notes_write", arguments: { address: "@project/selected", content: "from Codex", cwd: "../other" }, _meta: meta });
198
+ assert.equal(written.isError, undefined, textOf(written));
199
+ assert.equal(written.structuredContent.project_key, "other");
200
+ assert.match(readFileSync(join(f.home, "project", "other", "selected.md"), "utf8"), /from Codex/);
201
+ const read = await call(client, { name: "notes_read", arguments: { address: "@project/selected", cwd: "../other" }, _meta: meta });
202
+ assert.equal(read.isError, undefined, textOf(read));
203
+ assert.equal(read.structuredContent.text, "from Codex");
204
+ });
188
205
  test("refusals precede reads and writes: unknown thread, stale root, bad model, bad params", async (t) => {
189
206
  const f = await fixture(t);
190
207
  await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
4
+ import { registerBudget } from "../plugins/pi/budget.js";
5
+ import { BOOT_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
6
+ import { currentReset, isCheckpointBackedReset, windowUsage } from "../plugins/pi/window.js";
7
+ import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, nativeUsageContext, resultJson, runHandlers, } from "./helpers/extension.js";
8
+ import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
9
+ installExtensionTestHooks("notesoup-context-edit");
10
+ function appendUsage(sm, tokens, timestamp = Date.now()) {
11
+ const message = {
12
+ role: "assistant", content: [{ type: "text", text: "response" }],
13
+ api: "openai-responses", provider: "openai", model: "usage-fixture",
14
+ stopReason: "stop", timestamp,
15
+ usage: {
16
+ input: tokens, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: tokens,
17
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
18
+ },
19
+ };
20
+ return sm.appendMessage(message);
21
+ }
22
+ function appendWindow(sm, checkpoint) {
23
+ if (checkpoint)
24
+ sm.appendCompaction("", null, 0);
25
+ sm.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:edited" });
26
+ sm.appendCustomMessageEntry(BOOT_TYPE, "boot", false, { windowId: "pcw:edited" });
27
+ }
28
+ for (const kind of ["root", "checkpoint", "legacy"]) {
29
+ test(`${kind} budget rejects assistant usage invalidated by a real context edit`, async (t) => {
30
+ const sm = manager();
31
+ if (kind !== "root")
32
+ appendWindow(sm, kind === "checkpoint");
33
+ const target = appendText(sm, "user", "long context ".repeat(25_000));
34
+ appendUsage(sm, 100_000);
35
+ const settings = SettingsManager.inMemory({ compaction: { enabled: true, reserveTokens: 16_384 } });
36
+ const native = await nativeUsageContext(sm, settings);
37
+ t.after(native.dispose);
38
+ const { ctx } = native;
39
+ const captured = makeExtension(sm, settings);
40
+ const budget = registerBudget({ on() { }, registerTool() { } }, () => true, settings);
41
+ assert.equal(budget.hardReserveDue(ctx), true, "the original provider usage really reaches hard reserve");
42
+ sm.appendContextEdit(target, { content: "short" });
43
+ const leaf = sm.getLeafId();
44
+ const rawEntries = sm.getBranch();
45
+ const nativeUsage = ctx.getContextUsage();
46
+ const usage = windowUsage(ctx);
47
+ assert.ok(nativeUsage && nativeUsage.tokens !== null && usage && usage.tokens !== null);
48
+ if (kind === "legacy") {
49
+ // Legacy uses the vendored chars/3.5 estimator; native Pi uses chars/4.
50
+ assert.ok(usage.tokens >= nativeUsage.tokens);
51
+ assert.ok(usage.tokens <= Math.ceil(nativeUsage.tokens * 4 / 3.5) + sm.buildSessionProjection().messages.length);
52
+ }
53
+ else {
54
+ assert.deepEqual(usage, nativeUsage, "native projection remains the usage authority");
55
+ }
56
+ assert.equal(budget.hardReserveDue(ctx), false);
57
+ const room = resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
58
+ assert.equal(room, usage.contextWindow - usage.tokens - settings.getCompactionSettings().reserveTokens);
59
+ assert.ok(room !== null && room > 0, "shrinking the transcript restores spendable budget");
60
+ assert.equal(sm.getLeafId(), leaf, "accounting never repairs itself by resetting");
61
+ assert.deepEqual(sm.getBranch(), rawEntries, "usage selection does not mutate persisted history");
62
+ const boundary = await commitTurnEndBoundary(captured, sm, ctx);
63
+ assert.deepEqual(boundary.entries, [], "the real registered turn-end hook does not trigger a hard wipe");
64
+ assert.equal(sm.getLeafId(), leaf);
65
+ assert.equal(isCheckpointBackedReset(ctx), kind === "checkpoint");
66
+ });
67
+ }
68
+ test("legacy estimation excludes prior windows and trusts only usage appended after the edit", async (t) => {
69
+ const sm = manager();
70
+ appendText(sm, "user", "old window ".repeat(40_000));
71
+ appendUsage(sm, 300_000);
72
+ appendWindow(sm, false);
73
+ const target = appendText(sm, "user", "long current window ".repeat(15_000));
74
+ appendUsage(sm, 100_000);
75
+ const settings = SettingsManager.inMemory();
76
+ const native = await nativeUsageContext(sm, settings);
77
+ t.after(native.dispose);
78
+ const { ctx } = native;
79
+ sm.appendContextEdit(target, { content: "short" });
80
+ const usage = windowUsage(ctx);
81
+ assert.ok(usage && usage.tokens !== null);
82
+ assert.equal(usage.tokens, ["boot", "short", "response"].reduce((sum, text) => sum + Math.ceil(text.length / 3.5), 0));
83
+ assert.ok(ctx.getContextUsage().tokens > usage.tokens, "native legacy projection still contains the old window");
84
+ const freshTokens = 42_000;
85
+ appendUsage(sm, freshTokens, Date.now() + 1);
86
+ assert.equal(windowUsage(ctx)?.tokens, freshTokens, "fresh usage is not discarded with the stale responses");
87
+ sm.appendContextEdit(target, { content: "tiny" });
88
+ assert.ok(windowUsage(ctx).tokens < freshTokens, "a second edit invalidates that usage too");
89
+ });
90
+ test("checkpoint usage preserves native unknown/unavailable values; legacy retains context-window fallback", async (t) => {
91
+ const sm = manager();
92
+ appendUsage(sm, 100_000);
93
+ appendWindow(sm, true);
94
+ const native = await nativeUsageContext(sm, SettingsManager.inMemory());
95
+ t.after(native.dispose);
96
+ assert.equal(native.ctx.getContextUsage()?.tokens, null, "Pi has no post-compaction provider usage yet");
97
+ assert.deepEqual(windowUsage(native.ctx), native.ctx.getContextUsage(), "unknown is not replaced with a made-up estimate");
98
+ const captured = makeExtension(sm, SettingsManager.inMemory());
99
+ assert.equal(resultJson(await call(captured, "get_context_remaining", {}, native.ctx)).remaining_tokens, null);
100
+ native.ctx.getContextUsage = () => undefined;
101
+ assert.equal(windowUsage(native.ctx), undefined, "even a known model window cannot invent native usage");
102
+ const legacy = manager();
103
+ appendWindow(legacy, false);
104
+ const fallback = context(legacy, undefined, { tokens: null, percent: null, contextWindow: 100_000 });
105
+ assert.equal(windowUsage(fallback)?.contextWindow, 100_000, "legacy can read the window size without a model");
106
+ fallback.getContextUsage = () => undefined;
107
+ assert.equal(windowUsage(fallback), undefined, "without either window size, legacy usage stays unavailable");
108
+ });
109
+ test("an incomplete legacy reset remains unknown until the existing startup repair supplies its boot", async () => {
110
+ const sm = manager();
111
+ appendUsage(sm, 100_000);
112
+ sm.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:partial" });
113
+ const ctx = context(sm, undefined, { tokens: 100_000, percent: 100, contextWindow: 100_000 });
114
+ const marker = currentReset(ctx)?.id;
115
+ assert.equal(windowUsage(ctx), undefined);
116
+ const captured = makeExtension(sm, SettingsManager.inMemory());
117
+ await runHandlers(captured, "session_start", { reason: "startup" }, ctx);
118
+ assert.equal(currentReset(ctx)?.id, marker, "repair does not create a replacement reset");
119
+ const usage = windowUsage(ctx);
120
+ assert.ok(usage && usage.tokens !== null && usage.tokens < usage.contextWindow);
121
+ });
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
+ import { execFileSync, spawn } from "node:child_process";
3
+ import { createHash } from "node:crypto";
2
4
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
5
+ import { createServer } from "node:http";
3
6
  import { tmpdir } from "node:os";
4
7
  import { dirname, join, resolve } from "node:path";
5
8
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -18,6 +21,17 @@ function repository() {
18
21
  function sources(directory) {
19
22
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? sources(join(directory, entry.name)) : entry.name.endsWith(".ts") ? [join(directory, entry.name)] : []);
20
23
  }
24
+ function run(command, args, cwd) {
25
+ return new Promise((resolve, reject) => {
26
+ const child = spawn(command, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
27
+ let stdout = "";
28
+ let stderr = "";
29
+ child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; });
30
+ child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; });
31
+ child.on("error", reject);
32
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
33
+ });
34
+ }
21
35
  const options = { module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext, target: ts.ScriptTarget.ES2022 };
22
36
  test("the host-neutral core resolves without any SDK or plugin dependency", () => {
23
37
  const root = repository();
@@ -29,12 +43,65 @@ test("the host-neutral core resolves without any SDK or plugin dependency", () =
29
43
  const shared = sources(join(root, "src"));
30
44
  for (const domain of ["notes", "boot", "history", "budget", "tools", "dream"])
31
45
  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"]) {
46
+ const sharedRuntime = new Set(["typebox"]);
47
+ assert.deepEqual(dependencyViolations(root, shared, parsed.options, sharedRuntime), []);
48
+ for (const name of sharedRuntime) {
49
+ assert.equal(typeof manifest.dependencies?.[name], "string", `${name} is a declared runtime dependency`);
50
+ assert.equal(manifest.devDependencies?.[name], undefined, `${name} is not a development-only dependency`);
51
+ assert.equal(manifest.peerDependencies?.[name], undefined, `${name} is not a host-supplied peer`);
52
+ assert.equal(manifest.peerDependenciesMeta?.[name], undefined, `${name} has no peer metadata`);
53
+ }
54
+ for (const name of ["@earendil-works/pi-agent-core", "@earendil-works/pi-ai", "@earendil-works/pi-coding-agent"]) {
34
55
  assert.equal(manifest.dependencies?.[name], undefined, `${name} is supplied by the host`);
35
56
  assert.equal(manifest.peerDependencies[name], "*", `${name} follows Pi's host dependency contract`);
57
+ assert.equal(manifest.peerDependenciesMeta[name]?.optional, true, `${name} stays an optional peer`);
36
58
  }
37
59
  });
60
+ test("a clean production tarball install loads both public entries", async (t) => {
61
+ const root = repository();
62
+ const work = mkdtempSync(join(tmpdir(), "notesoup-install-"));
63
+ t.after(() => rmSync(work, { recursive: true, force: true }));
64
+ const pack = (directory) => {
65
+ const name = execFileSync("npm", ["pack", "--pack-destination", work, "--ignore-scripts", "--silent"], { cwd: directory, encoding: "utf8" }).trim().split(/\r?\n/).at(-1);
66
+ assert.ok(name, `npm pack produced a tarball in ${directory}`);
67
+ return name;
68
+ };
69
+ const notesoupTarball = pack(root);
70
+ // `npm test` builds `dist` before any test runs; skipping prepack avoids rebuilding it while other test files import it.
71
+ const typeboxDirectory = join(root, "node_modules/typebox");
72
+ const typeboxManifest = JSON.parse(readFileSync(join(typeboxDirectory, "package.json"), "utf8"));
73
+ const typeboxTarball = readFileSync(join(work, pack(typeboxDirectory)));
74
+ const integrity = `sha512-${createHash("sha512").update(typeboxTarball).digest("base64")}`;
75
+ const shasum = createHash("sha1").update(typeboxTarball).digest("hex");
76
+ // A loopback registry serves the pinned TypeBox tarball so the install needs no external network.
77
+ let base = "";
78
+ const server = createServer((request, response) => {
79
+ if (request.url === "/typebox") {
80
+ const version = { ...typeboxManifest, dist: { tarball: `${base}/typebox/-/typebox-${typeboxManifest.version}.tgz`, integrity, shasum } };
81
+ response.writeHead(200, { "content-type": "application/json" });
82
+ response.end(JSON.stringify({ name: "typebox", "dist-tags": { latest: typeboxManifest.version }, versions: { [typeboxManifest.version]: version } }));
83
+ return;
84
+ }
85
+ if (request.url === `/typebox/-/typebox-${typeboxManifest.version}.tgz`) {
86
+ response.writeHead(200, { "content-type": "application/octet-stream" });
87
+ response.end(typeboxTarball);
88
+ return;
89
+ }
90
+ response.writeHead(404);
91
+ response.end();
92
+ });
93
+ await new Promise((listening) => server.listen(0, "127.0.0.1", listening));
94
+ t.after(() => server.close());
95
+ base = `http://127.0.0.1:${server.address().port}`;
96
+ const consumer = join(work, "consumer");
97
+ mkdirSync(consumer);
98
+ writeFileSync(join(consumer, "package.json"), JSON.stringify({ name: "notesoup-consumer", version: "1.0.0", private: true }));
99
+ const install = await run("npm", ["install", "--registry", base, "--no-audit", "--no-fund", "--ignore-scripts", join(work, notesoupTarball)], consumer);
100
+ assert.equal(install.status, 0, `npm install failed:\n${install.stdout}\n${install.stderr}`);
101
+ assert.ok(existsSync(join(consumer, "node_modules/typebox/package.json")), "TypeBox is installed as a production dependency");
102
+ const imported = await run(process.execPath, ["--input-type=module", "--eval", 'const root = await import("notesoup"); const notes = await import("notesoup/notes"); if (!("notesRead" in root) || typeof notes.createNotesStore !== "function") throw new Error("public entries are incomplete");'], consumer);
103
+ assert.equal(imported.status, 0, `importing the installed entries failed:\n${imported.stdout}\n${imported.stderr}`);
104
+ });
38
105
  test("each plugin resolves only its own host, the core, and the public notes entry", () => {
39
106
  const root = repository();
40
107
  const plugins = [
@@ -145,7 +212,7 @@ test("AST guard sees every literal module edge, not import-like prose or comment
145
212
  test("the core entry is host-neutral and the Pi plugin entry owns the extension", () => {
146
213
  assert.deepEqual(Object.keys(core).sort(), [
147
214
  "DEFAULT_BOOT_TOOL_NAMES", "NoteError", "createNotesStore", "deriveThresholds", "historyList", "historyRead", "historyWindows",
148
- "loadNotesSnapshot", "noteIdentity", "notesList", "notesRead", "notesSearch", "notesUpdate", "notesWrite", "projectHistory",
215
+ "loadNotesSnapshot", "noteIdentity", "notesIdentityForCall", "notesList", "notesRead", "notesSearch", "notesToolContext", "notesUpdate", "notesWrite", "projectHistory",
149
216
  "projectKey", "remainingBudget", "renderBootBlock", "renderProtocolBlock", "selectContinuation", "slugify",
150
217
  "tokenBudgetGuidance", "unavailableNotesSnapshot", "warningPrompt", "WARNING_BODY",
151
218
  ].sort(), "the core exports a curated host-neutral surface and no extension");
@@ -169,7 +236,7 @@ test("the configured extension source is the executable current entry", async ()
169
236
  registerCommand(name) { commands.push(name); },
170
237
  });
171
238
  assert.deepEqual(tools.map((tool) => tool.name).sort(), ["dream_begin", "dream_end", "dream_forget", "empty_brain", "get_context_remaining", "history_list", "history_read", "history_windows", "notes_list", "notes_read", "notes_search", "notes_update", "notes_write"]);
172
- assert.deepEqual(tools.filter((tool) => tool.exposure === "deferred").map((tool) => tool.name).sort(), ["dream_begin", "dream_end", "dream_forget"], "dream tools stay hidden until searched");
239
+ assert.deepEqual(tools.filter((tool) => tool.exposure === "deferred").map((tool) => tool.name).sort(), ["dream_begin", "dream_end", "dream_forget", "history_list", "history_read", "history_windows"], "dream and history tools stay hidden until searched");
173
240
  assert.deepEqual(commands.sort(), ["empty", "fresh-window", "notesoup"]);
174
241
  });
175
242
  test("NOTESOUP_DISABLED turns the Pi extension fully off", async () => {
@@ -1,12 +1,16 @@
1
1
  import assert from "node:assert/strict";
2
- import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import { syncBuiltinESMExports } from "node:module";
3
5
  import { tmpdir } from "node:os";
4
6
  import { join } from "node:path";
5
7
  import test from "node:test";
6
8
  import { execFileSync } from "node:child_process";
9
+ import { Check } from "typebox/value";
7
10
  import { createNotesStore } from "../src/notes/index.js";
8
- import { dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../src/tools/dream.js";
11
+ import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../src/tools/dream.js";
9
12
  import { notesRead, notesUpdate, notesWrite } from "../src/tools/notes.js";
13
+ import { notesToolContext } from "../src/tools/notes-context.js";
10
14
  function fixture(t) {
11
15
  const home = mkdtempSync(join(tmpdir(), "dream-tools-"));
12
16
  t.after(() => rmSync(home, { recursive: true, force: true }));
@@ -29,8 +33,8 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
29
33
  await createNotesStore(as("a1", "alpha")).write("mine", "alpha only");
30
34
  const me = as("now", "alpha");
31
35
  const state = {};
32
- const ident = () => dreamingIdentity(me, state);
33
- // Closed: named homes are read-only and forget refuses.
36
+ const ident = () => notesToolContext(dreamingIdentity(me, state), "/work/alpha");
37
+ // Closed: named notebooks are read-only and forget refuses.
34
38
  assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false);
35
39
  assert.equal((await dreamForget.execute({ address: "@sessions/b2/trash" }, me, state)).ok, false);
36
40
  const begun = await dreamBegin.execute({ project: "beta" }, me, state);
@@ -39,7 +43,7 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
39
43
  assert.ok(begun.data.files.every(f => typeof f.last_accessed === "string"), "the dream's list shows each note's last access");
40
44
  assert.match(dreamBegin.render(begun), /\| accessed /);
41
45
  assert.equal((await dreamBegin.execute({}, me, state)).ok, false, "only one dream at a time");
42
- assert.ok(existsSync(join(home, ".dream.lock.beta")), "the project lock is held");
46
+ assert.ok(existsSync(join(home, ".dream.lock")), "the notes-home lock is held");
43
47
  assert.equal((await dreamBegin.execute({ project: "beta" }, as("other", "alpha"), {})).ok, false, "another session can't dream the same project");
44
48
  assert.ok((await notesWrite.execute({ address: "@projects/beta/rule", content: "merged" }, ident())).ok);
45
49
  assert.ok((await notesUpdate.execute({ address: "@sessions/b1/checkpoint", edits: [{ oldText: "old", newText: "new" }] }, ident(), () => "")).ok);
@@ -56,21 +60,88 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
56
60
  assert.equal(existsSync(join(home, "pi", "session", "b2", "trash.md")), false);
57
61
  const ended = await dreamEnd.execute({}, me, state);
58
62
  assert.ok(ended.ok && ended.data.commit && ended.data.commit !== begun.data.baseline, "dream_end commits the changes");
59
- assert.equal(existsSync(join(home, ".dream.lock.beta")), false, "the lock is released");
63
+ assert.equal(existsSync(join(home, ".dream.lock")), false, "the lock is released");
60
64
  assert.equal(execFileSync("git", ["status", "--porcelain"], { cwd: home, encoding: "utf8" }), "", "the audit leaves a clean tree");
61
65
  assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false, "closed again");
62
66
  assert.equal((await dreamEnd.execute({}, me, state)).ok, false);
63
67
  });
68
+ test("pending openings exclude concurrent begins and stale cleanup preserves a newer generation", async (t) => {
69
+ const { home, as } = fixture(t);
70
+ const me = as("s", "alpha");
71
+ const state = {};
72
+ const old = dreamBegin.execute({}, me, state);
73
+ const pending = state.pending;
74
+ assert.ok(pending, "ownership is visible before the first await");
75
+ assert.equal(state.project, undefined, "opening does not publish dream permissions yet");
76
+ assert.equal(dreamingIdentity(me, state), me);
77
+ const concurrent = await dreamBegin.execute({ project: "beta" }, me, state);
78
+ assert.ok(!concurrent.ok && concurrent.error.code === "already_dreaming");
79
+ assert.equal(state.pending, pending);
80
+ abandonDream(state);
81
+ assert.equal(existsSync(join(home, ".dream.lock")), false);
82
+ const newer = dreamBegin.execute({ project: "beta" }, me, state);
83
+ const newerPending = state.pending;
84
+ assert.ok(newerPending && newerPending.generation > pending.generation);
85
+ const token = readFileSync(join(home, ".dream.lock"), "utf8");
86
+ const cancelled = await old;
87
+ assert.ok(!cancelled.ok && cancelled.error.code === "cancelled");
88
+ assert.equal(readFileSync(join(home, ".dream.lock"), "utf8"), token);
89
+ const begun = await newer;
90
+ assert.ok(begun.ok);
91
+ assert.equal(state.project, "beta");
92
+ assert.equal(state.pending, undefined);
93
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
94
+ assert.equal(existsSync(join(home, ".dream.lock")), false);
95
+ });
96
+ test("a thrown scan releases pending ownership before propagating the defect", async (t) => {
97
+ const { home, as } = fixture(t);
98
+ const state = {};
99
+ const sentinel = new TypeError("scan defect");
100
+ const original = fs.readdir;
101
+ t.mock.method(fs, "readdir", async (...args) => {
102
+ if (args[0] === join(home, "project", "alpha"))
103
+ throw sentinel;
104
+ return original(...args);
105
+ });
106
+ syncBuiltinESMExports();
107
+ t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });
108
+ await assert.rejects(dreamBegin.execute({}, as("s", "alpha"), state), error => error === sentinel);
109
+ assert.equal(existsSync(join(home, ".dream.lock")), false);
110
+ assert.equal(state.pending, undefined);
111
+ assert.equal(state.project, undefined);
112
+ assert.equal(state.lock, undefined);
113
+ t.mock.restoreAll();
114
+ syncBuiltinESMExports();
115
+ assert.ok((await dreamBegin.execute({}, as("s", "alpha"), state)).ok, "the same state can retry after a failed scan");
116
+ assert.ok((await dreamEnd.execute({}, as("s", "alpha"), state)).ok);
117
+ });
118
+ test("baseline failure releases pending ownership and permits a retry", async (t) => {
119
+ const { home, as } = fixture(t);
120
+ const me = as("s", "alpha");
121
+ const state = {};
122
+ writeFileSync(join(home, ".git"), "not a Git repository");
123
+ const failed = await dreamBegin.execute({}, me, state);
124
+ assert.ok(!failed.ok && failed.error.code === "audit_failed");
125
+ assert.equal(existsSync(join(home, ".dream.lock")), false);
126
+ assert.equal(state.pending, undefined);
127
+ assert.equal(state.project, undefined);
128
+ assert.equal(state.lock, undefined);
129
+ const ended = await dreamEnd.execute({}, me, state);
130
+ assert.ok(!ended.ok && ended.error.code === "not_dreaming");
131
+ rmSync(join(home, ".git"));
132
+ assert.ok((await dreamBegin.execute({}, me, state)).ok);
133
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
134
+ });
64
135
  test("notes_read reports the access before itself, so reading never makes an unread note look fresh", async (t) => {
65
136
  const { home, as } = fixture(t);
66
137
  const me = as("s", "alpha");
67
138
  const old = "2026-01-01T08:00:00.000+08:00";
68
139
  mkdirSync(join(home, "human"), { recursive: true });
69
140
  writeFileSync(join(home, "human", "stale.md"), `---\norigin: self\ncreatedAt: ${old}\nupdatedAt: ${old}\nlastAccessed: ${old}\naccessCount: 0\n---\n\nbody`);
70
- const first = await notesRead.execute({ address: "@human/stale" }, me);
141
+ const first = await notesRead.execute({ address: "@human/stale" }, notesToolContext(me, "/work/alpha"));
71
142
  assert.ok(first.ok);
72
143
  assert.equal(Date.parse(first.data.metadata.last_accessed), Date.parse(old), "the first read shows the old access");
73
- const second = await notesRead.execute({ address: "@human/stale" }, me);
144
+ const second = await notesRead.execute({ address: "@human/stale" }, notesToolContext(me, "/work/alpha"));
74
145
  assert.ok(second.ok);
75
146
  assert.ok(Date.parse(second.data.metadata.last_accessed) > Date.parse(old), "the first read still counted as an access");
76
147
  });
@@ -80,3 +151,77 @@ test("dream_begin refuses an unknown project", async (t) => {
80
151
  assert.equal((await dreamBegin.execute({ project: "nope" }, as("s", "alpha"), state)).ok, false);
81
152
  assert.equal(state.project, undefined);
82
153
  });
154
+ test("dream_forget resolves address aliases before authorizing deletion", async (t) => {
155
+ const { home, as } = fixture(t);
156
+ const alpha = as("alpha-session", "alpha");
157
+ await createNotesStore(alpha).write("@project/precious", "keep alpha");
158
+ await createNotesStore(alpha).update("@project/precious", undefined, { crumpled: true });
159
+ await createNotesStore(alpha).write("local", "keep alpha session");
160
+ await createNotesStore(alpha).update("local", undefined, { crumpled: true });
161
+ await createNotesStore(as("beta-session", "beta")).write("@project/trash", "delete beta");
162
+ await createNotesStore(as("beta-session", "beta")).update("@project/trash", undefined, { crumpled: true });
163
+ const state = {};
164
+ assert.ok((await dreamBegin.execute({ project: "beta" }, alpha, state)).ok);
165
+ for (const address of ["@projects/alpha/precious", "@project/precious", "local"]) {
166
+ const refused = await dreamForget.execute({ address }, alpha, state);
167
+ assert.equal(refused.ok, false, `${address} is outside the beta dream`);
168
+ assert.ok(!refused.ok && refused.error.code === "invalid_scope");
169
+ }
170
+ assert.equal(await createNotesStore(alpha).read("@project/precious").then(note => note?.body), "keep alpha");
171
+ assert.equal(await createNotesStore(alpha).read("local").then(note => note?.body), "keep alpha session");
172
+ assert.ok((await dreamForget.execute({ address: "@projects/beta/trash" }, alpha, state)).ok, "the named note in the dreamed project remains deletable");
173
+ assert.equal(existsSync(join(home, "project", "beta", "trash.md")), false);
174
+ assert.ok((await dreamEnd.execute({}, alpha, state)).ok);
175
+ });
176
+ test("named-project mutation receipts carry their project metadata and fit their own schemas", async (t) => {
177
+ const { home, as } = fixture(t);
178
+ // A same-basename checkout makes the dreamed notebook carry a sibling hint.
179
+ mkdirSync(join(home, "project", "beta-1"), { recursive: true });
180
+ writeFileSync(join(home, "project", "beta-1", ".project"), JSON.stringify({ id: "host/two/beta", path: "/work/two/beta" }));
181
+ const me = as("now", "alpha");
182
+ const state = {};
183
+ const ident = () => notesToolContext(dreamingIdentity(me, state), "/work/alpha");
184
+ assert.equal((await notesWrite.execute({ address: "@projects/beta-1/rule", content: "x" }, ident())).ok, false, "named projects stay read-only outside a dream");
185
+ assert.ok((await dreamBegin.execute({ project: "beta-1" }, me, state)).ok);
186
+ const written = await notesWrite.execute({ address: "@projects/beta-1/rule", content: "merged" }, ident());
187
+ assert.ok(written.ok);
188
+ assert.equal(written.data.project_root, "/work/two/beta");
189
+ assert.deepEqual(written.data.project_siblings, [{ name: "beta", path: "/work/beta" }]);
190
+ assert.equal(Check(notesWrite.outputSchema, written.data), true, "notes_write accepts its own named-project receipt");
191
+ const updated = await notesUpdate.execute({ address: "@projects/beta-1/rule", edits: [{ oldText: "merged", newText: "done" }] }, ident(), () => "");
192
+ assert.ok(updated.ok);
193
+ assert.equal(updated.data.project_root, "/work/two/beta");
194
+ assert.deepEqual(updated.data.project_siblings, [{ name: "beta", path: "/work/beta" }]);
195
+ assert.equal(Check(notesUpdate.outputSchema, updated.data), true, "notes_update accepts its own named-project receipt");
196
+ assert.ok((await notesUpdate.execute({ address: "@projects/beta-1/rule", crumpled: true }, ident(), () => "")).ok);
197
+ const forgotten = await dreamForget.execute({ address: "@projects/beta-1/rule" }, me, state);
198
+ assert.ok(forgotten.ok);
199
+ assert.equal(forgotten.data.project_root, "/work/two/beta");
200
+ assert.deepEqual(forgotten.data.project_siblings, [{ name: "beta", path: "/work/beta" }]);
201
+ assert.equal(Check(dreamForget.outputSchema, forgotten.data), true, "dream_forget accepts its own named-project receipt");
202
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
203
+ });
204
+ test("a notes-home lock prevents interleaved dream Git audits", async (t) => {
205
+ const { home, as } = fixture(t);
206
+ const alpha = as("alpha-session", "alpha"), beta = as("beta-session", "beta");
207
+ await createNotesStore(alpha).write("@project/note", "before alpha");
208
+ await createNotesStore(beta).write("@project/note", "before beta");
209
+ const alphaState = {}, betaState = {};
210
+ const begun = await dreamBegin.execute({ project: "alpha" }, alpha, alphaState);
211
+ assert.ok(begun.ok);
212
+ assert.ok((await notesWrite.execute({ address: "@project/note", content: "after alpha" }, notesToolContext(dreamingIdentity(alpha, alphaState), "/work/alpha"))).ok);
213
+ const refused = await dreamBegin.execute({ project: "beta" }, beta, betaState);
214
+ assert.equal(refused.ok, false, "a different project cannot share the home's Git audit");
215
+ assert.ok(!refused.ok && refused.error.code === "already_dreaming");
216
+ assert.deepEqual(betaState, {}, "a refused dream publishes no state");
217
+ assert.equal(execFileSync("git", ["rev-parse", "HEAD"], { cwd: home, encoding: "utf8" }).trim(), begun.data.baseline, "a refused begin creates no baseline");
218
+ const ended = await dreamEnd.execute({}, alpha, alphaState);
219
+ assert.ok(ended.ok && ended.data.commit !== undefined);
220
+ assert.notEqual(ended.data.commit, begun.data.baseline);
221
+ const changed = execFileSync("git", ["show", "--format=", "--name-only", ended.data.commit], { cwd: home, encoding: "utf8" });
222
+ assert.match(changed, /project\/alpha\/note\.md/);
223
+ assert.doesNotMatch(changed, /project\/beta\/note\.md/);
224
+ assert.equal(execFileSync("git", ["status", "--porcelain"], { cwd: home, encoding: "utf8" }), "");
225
+ assert.ok((await dreamBegin.execute({ project: "beta" }, beta, betaState)).ok, "the next dream can start after the home lock is released");
226
+ assert.ok((await dreamEnd.execute({}, beta, betaState)).ok);
227
+ });