notesoup 0.53.2 → 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 (131) hide show
  1. package/README.md +2 -2
  2. package/dist/plugins/claude/src/helper.js +2 -1
  3. package/dist/plugins/codex/src/hooks.js +1 -1
  4. package/dist/plugins/codex/src/identity.d.ts +1 -1
  5. package/dist/plugins/codex/src/identity.js +3 -3
  6. package/dist/plugins/codex/src/mcp.js +2 -1
  7. package/dist/plugins/codex/src/text.d.ts +1 -1
  8. package/dist/plugins/codex/src/text.js +2 -2
  9. package/dist/plugins/dsh/engine.js +2 -2
  10. package/dist/plugins/dsh/tools.js +8 -7
  11. package/dist/plugins/dsh/window.d.ts +1 -0
  12. package/dist/plugins/dsh/window.js +7 -3
  13. package/dist/plugins/pi/history-tools.d.ts +1 -1
  14. package/dist/plugins/pi/history-tools.js +4 -4
  15. package/dist/plugins/pi/notes/tools.js +8 -6
  16. package/dist/plugins/pi/render.js +7 -4
  17. package/dist/plugins/pi/runtime.js +2 -2
  18. package/dist/plugins/pi/window.js +21 -7
  19. package/dist/src/boot/render.js +7 -7
  20. package/dist/src/boot/snapshot.d.ts +7 -7
  21. package/dist/src/boot/snapshot.js +17 -17
  22. package/dist/src/boot/text.d.ts +2 -2
  23. package/dist/src/boot/text.js +7 -5
  24. package/dist/src/dream/git.d.ts +2 -11
  25. package/dist/src/dream/git.js +6 -23
  26. package/dist/src/dream/lock.d.ts +2 -2
  27. package/dist/src/dream/lock.js +3 -3
  28. package/dist/src/index.d.ts +2 -1
  29. package/dist/src/index.js +3 -2
  30. package/dist/src/notes/address.d.ts +8 -8
  31. package/dist/src/notes/address.js +13 -13
  32. package/dist/src/notes/errors.d.ts +1 -1
  33. package/dist/src/notes/frontmatter.js +2 -2
  34. package/dist/src/notes/index.d.ts +1 -1
  35. package/dist/src/notes/index.js +1 -1
  36. package/dist/src/notes/paths.d.ts +6 -6
  37. package/dist/src/notes/paths.js +9 -9
  38. package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
  39. package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
  40. package/dist/src/notes/store.d.ts +4 -4
  41. package/dist/src/notes/store.js +55 -52
  42. package/dist/src/tools/dream.d.ts +21 -3
  43. package/dist/src/tools/dream.js +54 -16
  44. package/dist/src/tools/notes-context.d.ts +10 -0
  45. package/dist/src/tools/notes-context.js +27 -0
  46. package/dist/src/tools/notes.d.ts +69 -20
  47. package/dist/src/tools/notes.js +40 -31
  48. package/dist/test/boot.integration.test.js +1 -1
  49. package/dist/test/claude-mod.test.js +89 -43
  50. package/dist/test/codex-plugin.test.js +18 -1
  51. package/dist/test/context-edit-budget.test.js +121 -0
  52. package/dist/test/dependencies.test.js +71 -4
  53. package/dist/test/dream-tools.test.js +153 -8
  54. package/dist/test/dsh.test.js +62 -15
  55. package/dist/test/helpers/dsh.d.ts +4 -1
  56. package/dist/test/helpers/dsh.js +20 -4
  57. package/dist/test/helpers/extension.d.ts +5 -0
  58. package/dist/test/helpers/extension.js +33 -2
  59. package/dist/test/host-neutral.test.js +17 -15
  60. package/dist/test/model-facing-text.test.js +12 -8
  61. package/dist/test/notes-cwd.test.js +114 -0
  62. package/dist/test/notes-library.test.js +4 -4
  63. package/dist/test/notes-query-namespaces.test.d.ts +1 -0
  64. package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
  65. package/dist/test/notes.integration.test.js +72 -23
  66. package/dist/test/notes.test.js +50 -20
  67. package/dist/test/pi-render.test.js +33 -1
  68. package/dist/test/project-namespace.test.d.ts +1 -0
  69. package/dist/test/project-namespace.test.js +324 -0
  70. package/docs/architecture.md +12 -7
  71. package/docs/codex.md +4 -4
  72. package/docs/dsh.md +8 -8
  73. package/docs/notes-library.md +9 -5
  74. package/docs/skills.md +3 -3
  75. package/docs/tool-results.md +6 -2
  76. package/package.json +4 -6
  77. package/playbook.md +6 -6
  78. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  79. package/plugins/claude/dist/claude/helper.js +677 -615
  80. package/plugins/claude/hooks/register.ts +19 -11
  81. package/plugins/claude/playbook.md +6 -6
  82. package/plugins/claude/skills/memory/SKILL.md +4 -4
  83. package/plugins/claude/src/helper.ts +3 -2
  84. package/plugins/codex/README.md +1 -1
  85. package/plugins/codex/dist/codex/notesoup.js +877 -815
  86. package/plugins/codex/src/hooks.ts +1 -1
  87. package/plugins/codex/src/identity.ts +3 -3
  88. package/plugins/codex/src/mcp.ts +2 -1
  89. package/plugins/codex/src/text.ts +2 -2
  90. package/plugins/dsh/engine.ts +2 -2
  91. package/plugins/dsh/tools.ts +8 -7
  92. package/plugins/dsh/window.ts +8 -3
  93. package/plugins/paseo/OVERVIEW.md +4 -4
  94. package/plugins/paseo/README.md +1 -1
  95. package/plugins/paseo/client/brain-empty-card.tsx +3 -4
  96. package/plugins/paseo/client/markdown.tsx +179 -0
  97. package/plugins/paseo/client/notes-op-card.tsx +35 -34
  98. package/plugins/paseo/client/notes-op-transformer.ts +17 -68
  99. package/plugins/paseo/client/paper-card.tsx +8 -19
  100. package/plugins/paseo/client/paper-palette.ts +40 -0
  101. package/plugins/paseo/client/sticky-card.tsx +6 -4
  102. package/plugins/paseo/package.json +3 -0
  103. package/plugins/paseo/paseo-plugin.json +2 -2
  104. package/plugins/paseo/shared/notes-op.ts +13 -9
  105. package/plugins/paseo/test/notes-op.test.ts +52 -73
  106. package/plugins/paseo/test/paper-palette.test.ts +54 -0
  107. package/plugins/pi/history-tools.ts +4 -4
  108. package/plugins/pi/notes/tools.ts +8 -6
  109. package/plugins/pi/render.ts +6 -4
  110. package/plugins/pi/runtime.ts +2 -2
  111. package/plugins/pi/window.ts +22 -7
  112. package/skills/memory/SKILL.md +4 -4
  113. package/src/boot/render.ts +8 -8
  114. package/src/boot/snapshot.ts +20 -20
  115. package/src/boot/text.ts +7 -5
  116. package/src/dream/git.ts +7 -24
  117. package/src/dream/lock.ts +3 -3
  118. package/src/index.ts +4 -3
  119. package/src/notes/address.ts +13 -13
  120. package/src/notes/errors.ts +1 -1
  121. package/src/notes/frontmatter.ts +2 -2
  122. package/src/notes/index.ts +1 -1
  123. package/src/notes/paths.ts +9 -9
  124. package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
  125. package/src/notes/store.ts +61 -58
  126. package/src/tools/dream.ts +63 -16
  127. package/src/tools/notes-context.ts +29 -0
  128. package/src/tools/notes.ts +39 -29
  129. package/dist/test/project-home.test.js +0 -134
  130. /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
  131. /package/dist/test/{project-home.test.d.ts → notes-cwd.test.d.ts} +0 -0
@@ -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
+ });
@@ -6,11 +6,12 @@ import { allItems, contentText } from "../src/history/history.js";
6
6
  import { mkdtemp, readFile, rm } from "node:fs/promises";
7
7
  import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
- import { resolveProjectHome } from "../src/notes/project-home.js";
9
+ import { resolveProjectNamespace } from "../src/notes/project-namespace.js";
10
10
  import { renderBootBlock } from "../src/boot/render.js";
11
11
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
12
12
  import { WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
13
  import { notesRead } from "../src/tools/notes.js";
14
+ import { notesToolContext } from "../src/tools/notes-context.js";
14
15
  import { success } from "../src/tools/result.js";
15
16
  import { createNotesStore } from "../src/notes/index.js";
16
17
  import { dshFixture } from "./helpers/dsh.js";
@@ -58,20 +59,20 @@ test("dsh boot freezes across note writes, rotates before the next wire request,
58
59
  assert.ok(mock.requests[0].tools?.some((tool) => tool.name === "history_list"));
59
60
  assert.equal(mock.requests[0].tools?.some((tool) => tool.name === "dream"), false);
60
61
  });
61
- test("dsh reload adopts persisted bytes before first assembly; missing records reconstruct from checkpoints and root system", async (t) => {
62
- const { engine, create, mock } = await dshFixture(t);
62
+ test("dsh same-session reload adopts persisted bytes before first assembly; missing records reconstruct from checkpoints and root system", async (t) => {
63
+ const { engine, create, reload, mock } = await dshFixture(t);
63
64
  const agent = await create();
64
65
  mock.script.push({ tool: "empty_brain", input: {} }, { text: "after" });
65
66
  await run(agent, "before");
66
67
  const snapshot = engine.windows.get(agent.session).snapshot;
67
68
  await createNotesStore(notesIdentity(agent, engine.config)).write("@self/later", "not in the frozen boot");
68
69
  const seed = agent.session.snapshotEvents();
69
- const resumed = await create(seed, "session-reloaded");
70
+ const resumed = await reload(agent, seed);
70
71
  await run(resumed, "continue");
71
72
  assert.equal(engine.windows.get(resumed.session).snapshot.boot, snapshot.boot);
72
73
  assert.equal(system(mock.requests[2]), system(mock.requests[1]));
73
74
  const missing = withoutRecords(seed);
74
- const reconstructed = await create(missing, "session-without-record");
75
+ const reconstructed = await reload(resumed, missing);
75
76
  await run(reconstructed, "continue again");
76
77
  assert.equal(engine.windows.get(reconstructed.session).snapshot.window, 1);
77
78
  assert.equal(engine.windows.get(reconstructed.session).snapshot.boot, snapshot.boot);
@@ -80,13 +81,53 @@ test("dsh reload adopts persisted bytes before first assembly; missing records r
80
81
  await run(root, "root stays");
81
82
  const rootBoot = engine.windows.get(root.session).snapshot.boot;
82
83
  await createNotesStore(notesIdentity(root, engine.config)).write("@self/later", "changed again");
83
- const rootReloaded = await create(withoutRecords(root.session.snapshotEvents()), "session-root-reloaded");
84
+ const rootReloaded = await reload(root, withoutRecords(root.session.snapshotEvents()));
84
85
  await run(rootReloaded, "resume root");
85
86
  assert.equal(engine.windows.get(rootReloaded.session).snapshot.boot, rootBoot);
86
87
  assert.equal(engine.windows.get(rootReloaded.session).snapshot.window, 0);
87
88
  });
88
- test("dsh reload keeps its window ordinal from a boot written before the tag rename", async (t) => {
89
- const { engine, create, mock } = await dshFixture(t);
89
+ test("dsh native fork rebinds boot and notes tools to the child without changing inherited history", async (t) => {
90
+ const { ctx, engine, create, fork, mock } = await dshFixture(t);
91
+ const parent = await create();
92
+ const parentNotes = createNotesStore(notesIdentity(parent, engine.config));
93
+ await parentNotes.write("MAP.md", "- parent-handoff.md — parent's session note");
94
+ await parentNotes.write("parent-handoff.md", "parent-only recovery");
95
+ mock.script.push({ tool: "empty_brain", input: {} }, { text: "after" });
96
+ await run(parent, "inherited conversation before reset");
97
+ const parentSnapshot = engine.windows.get(parent.session).snapshot;
98
+ assert.equal(parentSnapshot.window, 1);
99
+ assert.ok(parentSnapshot.boot.includes("parent-handoff.md"));
100
+ const parentEvents = structuredClone(parent.session.snapshotEvents());
101
+ const childId = "session-native-child";
102
+ const childNotes = createNotesStore({ ...notesIdentity(parent, engine.config), sessionId: childId });
103
+ await childNotes.write("MAP.md", "- child-handoff.md — child's session note");
104
+ await childNotes.write("child-handoff.md", "child-only recovery");
105
+ const child = await fork(parent, childId);
106
+ assert.equal(child.session.header.parentSession, parent.session.id);
107
+ assert.equal(child.session.inheritedEventCount, parentEvents.length);
108
+ const snapshot = engine.windows.get(child.session).snapshot;
109
+ assert.equal(snapshot.window, parentSnapshot.window);
110
+ assert.equal(snapshot.windowId, `dsh:${childId}:1`);
111
+ assert.ok(snapshot.boot.includes(`\ndsh:${childId}\n`));
112
+ assert.ok(snapshot.boot.includes("- child-handoff.md — child's session note"));
113
+ assert.equal(snapshot.boot.includes("parent-handoff.md"), false);
114
+ assert.equal(recoverSnapshot(child.session.ownEvents())?.windowId, snapshot.windowId, "the rebound snapshot is persisted in the child");
115
+ assert.deepEqual(child.session.snapshotEvents().slice(0, parentEvents.length), parentEvents);
116
+ const read = await ctx.tools.execute({ name: "notes_read", arguments: { address: "child-handoff.md" }, agent: child, callId: ToolCallId("fork-note"), signal: new AbortController().signal });
117
+ assert.equal(read.isError, false);
118
+ if (!read.isError)
119
+ assert.equal(read.value.text, "child-only recovery");
120
+ const history = await ctx.tools.execute({ name: "history_list", arguments: { query: "inherited conversation before reset", roles: ["user"] }, agent: child, callId: ToolCallId("fork-history"), signal: new AbortController().signal });
121
+ assert.equal(history.isError, false);
122
+ if (!history.isError)
123
+ assert.equal(history.value.items.length, 1);
124
+ await run(child, "continue in child");
125
+ assert.ok(system(mock.requests.at(-1)).includes(snapshot.boot));
126
+ assert.equal(engine.windows.get(parent.session).snapshot, parentSnapshot);
127
+ assert.deepEqual(parent.session.snapshotEvents(), parentEvents);
128
+ });
129
+ test("dsh same-session reload keeps frozen bytes and ordinal from a boot written before the tag rename", async (t) => {
130
+ const { engine, create, reload, mock } = await dshFixture(t);
90
131
  const agent = await create();
91
132
  mock.script.push({ tool: "empty_brain", input: {} }, { text: "after" });
92
133
  await run(agent, "before");
@@ -94,8 +135,10 @@ test("dsh reload keeps its window ordinal from a boot written before the tag ren
94
135
  assert.ok(snapshot.boot.includes(WINDOW_IDENTITY_OPEN_TAG), "the current boot carries the renamed tag");
95
136
  const legacy = withLegacyIdentityTags(withoutRecords(agent.session.snapshotEvents()));
96
137
  assert.ok(JSON.stringify(legacy).includes("<context_window>\\nAgent name: dsh"), "the seed reproduces an old-spelling boot");
97
- const resumed = await create(legacy, "session-legacy-tags");
138
+ await createNotesStore(notesIdentity(agent, engine.config)).write("@self/later", "not in the legacy frozen boot");
139
+ const resumed = await reload(agent, legacy);
98
140
  await run(resumed, "continue");
141
+ assert.equal(engine.windows.get(resumed.session).snapshot.boot, snapshot.boot.replaceAll(WINDOW_IDENTITY_OPEN_TAG, "<context_window>").replaceAll(WINDOW_IDENTITY_CLOSE_TAG, "</context_window>"));
99
142
  assert.equal(engine.windows.get(resumed.session).snapshot.window, 1, "an old-tag boot still yields its window ordinal");
100
143
  assert.equal(engine.windows.get(resumed.session).snapshot.windowId, snapshot.windowId, "and its window id");
101
144
  });
@@ -109,9 +152,10 @@ function withLegacyIdentityTags(events) {
109
152
  .replaceAll(WINDOW_IDENTITY_CLOSE_TAG, "</context_window>");
110
153
  return events.map((event) => {
111
154
  const copy = structuredClone(event);
112
- if (copy.type !== "user/message")
155
+ const message = copy.type === "system/message" ? copy.data.message : copy.type === "user/message" ? copy.data : undefined;
156
+ if (!message)
113
157
  return copy;
114
- const data = copy.data;
158
+ const data = message;
115
159
  if (typeof data.content === "string")
116
160
  data.content = legacy(data.content);
117
161
  else if (Array.isArray(data.content))
@@ -179,7 +223,7 @@ test("dsh transaction keeps node zero, resets tiny spans, refuses partial spans,
179
223
  assert.equal(engine.windows.get(session).snapshot.window, 2);
180
224
  session.append("turn/end", { turn: 2, reason: { kind: "completed" } });
181
225
  });
182
- test("dsh cancellation preserves the notebook; a close failure leaves a durable lock and landed boot recoverable", async (t) => {
226
+ test("dsh cancellation preserves the page; a close failure leaves a durable lock and landed boot recoverable", async (t) => {
183
227
  const { engine, create } = await dshFixture(t);
184
228
  const agent = await create();
185
229
  await run(agent, "one");
@@ -314,12 +358,12 @@ test("dsh explicit resets survive auto:false; shared tool reads and expected err
314
358
  if (!note.isError)
315
359
  assert.equal(note.value.text, "decision");
316
360
  const identity = notesIdentity(agent, engine.config);
317
- assert.equal(identity.projectKey, resolveProjectHome(agent.session.header.cwd, identity.home).name);
361
+ assert.equal(identity.projectKey, resolveProjectNamespace(agent.session.header.cwd, identity.home).name);
318
362
  const marker = JSON.parse(await readFile(join(identity.home, "project", identity.projectKey, ".project"), "utf8"));
319
363
  assert.equal(typeof marker.id, "string");
320
364
  const foreignRoot = await mkdtemp(join(tmpdir(), "ns-dsh-foreign-"));
321
365
  t.after(() => rm(foreignRoot, { recursive: true, force: true }));
322
- const foreign = resolveProjectHome(foreignRoot, identity.home);
366
+ const foreign = resolveProjectNamespace(foreignRoot, identity.home);
323
367
  await createNotesStore({ ...identity, projectKey: foreign.name }).write("@project/reference", "foreign paper");
324
368
  const foreignFile = join(foreign.dir, "reference.md");
325
369
  const before = await readFile(foreignFile, "utf8");
@@ -328,13 +372,16 @@ test("dsh explicit resets survive auto:false; shared tool reads and expected err
328
372
  assert.equal(foreignRead.isError, false);
329
373
  if (!foreignRead.isError) {
330
374
  assert.equal(foreignRead.value.project_root, foreign.path);
331
- const shared = await notesRead.execute({ address }, identity);
375
+ const shared = await notesRead.execute({ address }, notesToolContext(identity, agent.session.header.cwd));
332
376
  assert.ok(shared.ok);
333
377
  assert.deepEqual(foreignRead.value, shared.data);
334
378
  assert.equal(foreignRead.content[0]?.type, "text");
335
379
  assert.equal(foreignRead.content[0].text, notesRead.render(success(shared.data)));
336
380
  }
337
381
  assert.equal(await readFile(foreignFile, "utf8"), before);
382
+ const overridden = await call("notes_write", { address: "@project/from-override", content: "selected by dsh", cwd: foreignRoot });
383
+ assert.equal(overridden.isError, false);
384
+ assert.equal((await createNotesStore({ ...identity, projectKey: foreign.name }).read("@project/from-override"))?.body, "selected by dsh");
338
385
  const refused = await call("notes_write", { address, content: "no overwrite" });
339
386
  assert.equal(refused.isError, true);
340
387
  if (refused.isError)
@@ -1,5 +1,6 @@
1
1
  import type { TestContext } from "node:test";
2
2
  import { Context } from "@deepseek-ai/cordis";
3
+ import { type Agent } from "@deepseek-ai/dsh-agent";
3
4
  import { type SessionEvent } from "@deepseek-ai/dsh-session";
4
5
  import NotesoupEngine, { type EngineConfig } from "../../plugins/dsh/engine.js";
5
6
  export declare function dshFixture(t: TestContext, config?: EngineConfig): Promise<{
@@ -13,5 +14,7 @@ export declare function dshFixture(t: TestContext, config?: EngineConfig): Promi
13
14
  url: string;
14
15
  close: () => Promise<void>;
15
16
  };
16
- create: (seed?: readonly SessionEvent[], id?: string) => Promise<import("@deepseek-ai/dsh-agent").Agent>;
17
+ create: (seed?: readonly SessionEvent[], id?: string) => Promise<Agent>;
18
+ reload: (agent: Agent, seed?: readonly SessionEvent[]) => Promise<Agent>;
19
+ fork: (agent: Agent, id?: string) => Promise<Agent>;
17
20
  }>;
@@ -7,7 +7,7 @@ import Agents from "@deepseek-ai/dsh-agent";
7
7
  import AgentLoop from "@deepseek-ai/dsh-agent-loop";
8
8
  import Llm from "@deepseek-ai/dsh-llm";
9
9
  import * as DeepSeek from "@deepseek-ai/dsh-llm-deepseek-api-key";
10
- import Sessions, { SessionId } from "@deepseek-ai/dsh-session";
10
+ import Sessions, { buildForkSeed, SessionId, SessionLogOffset } from "@deepseek-ai/dsh-session";
11
11
  import Projections from "@deepseek-ai/dsh-session-projection";
12
12
  import SystemPrompt from "@deepseek-ai/dsh-system-prompt";
13
13
  import Tools from "@deepseek-ai/dsh-tools";
@@ -41,10 +41,26 @@ export async function dshFixture(t, config = {}) {
41
41
  fibers.push(await ctx.plugin(notesoup));
42
42
  fibers.push(await ctx.plugin(AgentLoop, { agents: [], maxParallelToolCalls: 10 }));
43
43
  let count = 0;
44
- const create = async (seed, id = `session-test-${++count}`) => {
45
- const handle = await ctx.agents.create({ sessionId: SessionId(id), meta: { cwd: directory }, agentOptions: { provider: "deepseek-official", model: "mock-flash" }, ...(seed ? { seed } : {}) });
44
+ const handles = new Map();
45
+ const make = async (options) => {
46
+ const handle = await ctx.agents.create({ agentOptions: { provider: "deepseek-official", model: "mock-flash" }, ...options });
46
47
  fibers.push(handle);
48
+ handles.set(handle.agent, handle);
47
49
  return handle.agent;
48
50
  };
49
- return { ctx, engine, engineFiber, directory, mock, create };
51
+ const create = (seed, id = `session-test-${++count}`) => make({ sessionId: SessionId(id), meta: { cwd: directory }, ...(seed ? { seed } : {}) });
52
+ const reload = async (agent, seed = agent.session.snapshotEvents()) => {
53
+ await handles.get(agent).dispose();
54
+ return create(seed, agent.session.id);
55
+ };
56
+ const fork = (agent, id = `session-test-${++count}`) => {
57
+ const events = agent.session.snapshotEvents();
58
+ return make({
59
+ sessionId: SessionId(id),
60
+ meta: { cwd: directory, parentSession: agent.session.id, isSeeded: true },
61
+ seed: buildForkSeed(events, events.at(-1).seq),
62
+ inheritedEventCount: SessionLogOffset(events.length),
63
+ });
64
+ };
65
+ return { ctx, engine, engineFiber, directory, mock, create, reload, fork };
50
66
  }
@@ -75,6 +75,11 @@ export declare function context(sessionManager: SessionManager, compact?: Extens
75
75
  provider: string;
76
76
  id: string;
77
77
  }): ExtensionContext;
78
+ /** Real Pi usage accounting over the supplied manager; never issues a model request. */
79
+ export declare function nativeUsageContext(sessionManager: SessionManager, settingsManager: SettingsManager, contextWindow?: number): Promise<{
80
+ ctx: ExtensionContext;
81
+ dispose: () => void;
82
+ }>;
78
83
  export declare function noticesOf(ctx: ExtensionContext): Notice[];
79
84
  export declare function sentOf(captured: Captured, customType: string): SentMessage[];
80
85
  export declare function call(captured: Captured, name: string, params: Record<string, unknown>, ctx: ExtensionContext): Promise<AgentToolResult<unknown>>;
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
- import { SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
+ import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
9
9
  import notesoup, { createNotesoup } from "../../plugins/pi/extension.js";
10
10
  import { loadNotesSnapshot } from "../../src/boot/snapshot.js";
11
11
  import { renderBootBlock } from "../../src/boot/render.js";
@@ -190,6 +190,33 @@ export function context(sessionManager, compact, usage, idle = true, cwd = defau
190
190
  // Only the members the extension reads; the rest of the ExtensionContext surface is unused.
191
191
  return Object.assign(fake, { notices, compactionRequests });
192
192
  }
193
+ /** Real Pi usage accounting over the supplied manager; never issues a model request. */
194
+ export async function nativeUsageContext(sessionManager, settingsManager, contextWindow = 100_000) {
195
+ const agentDir = process.env.PI_CODING_AGENT_DIR;
196
+ assert.ok(agentDir, "install the isolated extension test environment first");
197
+ const runtime = await ModelRuntime.create({
198
+ authPath: join(agentDir, "auth.json"), modelsPath: null,
199
+ modelsStorePath: join(agentDir, "models"), refreshOnCreate: false,
200
+ });
201
+ const base = runtime.getModels("openai")[0];
202
+ assert.ok(base, "the installed SDK exposes a model for usage accounting");
203
+ const model = { ...base, contextWindow, maxTokens: 4096 };
204
+ const loader = new DefaultResourceLoader({
205
+ cwd: defaultCwd, agentDir, settingsManager,
206
+ noExtensions: true, noSkills: true, noThemes: true, noPromptTemplates: true,
207
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
208
+ });
209
+ await loader.reload();
210
+ const { session } = await createAgentSession({
211
+ cwd: defaultCwd, agentDir, modelRuntime: runtime, model,
212
+ settingsManager, sessionManager, resourceLoader: loader, tools: [],
213
+ });
214
+ session.agent.streamFunction = async () => { throw new Error("usage fixtures must not request a model"); };
215
+ const ctx = context(sessionManager);
216
+ ctx.model = model;
217
+ ctx.getContextUsage = () => session.getContextUsage();
218
+ return { ctx, dispose: () => session.dispose() };
219
+ }
193
220
  export function noticesOf(ctx) {
194
221
  return ctx.notices;
195
222
  }
@@ -353,7 +380,11 @@ export async function commitTurnEndBoundary(captured, sessionManager, ctx) {
353
380
  context: { contextEntries: [], contextMessages: [], llmMessages: [], pendingMessages: [], canContinue: true },
354
381
  outcome: "completed",
355
382
  turnIndex: 0,
356
- message: { role: "assistant", content: [], stopReason: "stop", timestamp: Date.now() },
383
+ message: {
384
+ role: "assistant", content: [], stopReason: "stop", timestamp: Date.now(),
385
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
386
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
387
+ },
357
388
  toolResults: [],
358
389
  messageEntryId: "assistant-entry",
359
390
  toolResultEntryIds: [],