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
@@ -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: [],
@@ -10,6 +10,7 @@ import { renderBootBlock } from "../src/boot/render.js";
10
10
  import { HistoryPageItemSchema, HistoryRoleSchema, projectHistory } from "../src/history/history.js";
11
11
  import { createNotesStore } from "../src/notes/store.js";
12
12
  import { notesWrite, notesUpdate, notesRead } from "../src/tools/notes.js";
13
+ import { notesToolContext } from "../src/tools/notes-context.js";
13
14
  import { historyWindows, historyList, historyRead } from "../src/tools/history.js";
14
15
  import { historyRoles } from "../src/tools/schema.js";
15
16
  import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
@@ -181,51 +182,52 @@ test("structuredBytes has no size for a value with no JSON representation", () =
181
182
  });
182
183
  test("shared note operations return canonical outcomes with a body-only read window", async (t) => {
183
184
  const notesIdentity = identity(t);
184
- const written = data(await notesWrite.execute({ address: "@project/test.md", content: "alpha\nbeta" }, notesIdentity));
185
+ const toolContext = notesToolContext(notesIdentity, "/work/explicit");
186
+ const written = data(await notesWrite.execute({ address: "@project/test.md", content: "alpha\nbeta" }, toolContext));
185
187
  assert.equal(written.address, "@project/test.md");
186
188
  assert.equal(written.project_key, notesIdentity.projectKey);
187
189
  assert.equal(written.outcome, "created");
188
- const updated = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "alpha", newText: "gamma" }] }, notesIdentity, (change) => {
190
+ const updated = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "alpha", newText: "gamma" }] }, toolContext, (change) => {
189
191
  assert.equal(change.kind, "body");
190
192
  return "caller-rendered-diff";
191
193
  }));
192
194
  assert.equal(updated.change_kind, "body");
193
195
  assert.equal(updated.diff, "caller-rendered-diff");
194
- const defaultReceipt = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "gamma", newText: "delta" }] }, notesIdentity));
196
+ const defaultReceipt = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "gamma", newText: "delta" }] }, toolContext));
195
197
  assert.equal(defaultReceipt.diff, "note body");
196
- await notesWrite.execute({ address: "owned.md", content: "first", origin: "user" }, notesIdentity);
197
- await notesWrite.execute({ address: "owned.md", content: "rewritten" }, notesIdentity);
198
- assert.equal(data(await notesRead.execute({ address: "owned.md" }, notesIdentity)).metadata.origin, "user", "tool overwrites preserve an omitted origin");
199
- const invalid = refusal(await notesUpdate.execute({ address: "owned.md", edits: [{ oldText: "", newText: "x" }] }, notesIdentity));
198
+ await notesWrite.execute({ address: "owned.md", content: "first", origin: "user" }, toolContext);
199
+ await notesWrite.execute({ address: "owned.md", content: "rewritten" }, toolContext);
200
+ assert.equal(data(await notesRead.execute({ address: "owned.md" }, toolContext)).metadata.origin, "user", "tool overwrites preserve an omitted origin");
201
+ const invalid = refusal(await notesUpdate.execute({ address: "owned.md", edits: [{ oldText: "", newText: "x" }] }, toolContext));
200
202
  assert.equal(invalid.code, "invalid_edit");
201
- const moved = data(await notesUpdate.execute({ address: "owned.md", rename_to: "@project/renamed.md", edits: [{ oldText: "rewritten", newText: "final" }], origin: "external" }, notesIdentity));
203
+ const moved = data(await notesUpdate.execute({ address: "owned.md", rename_to: "@project/renamed.md", edits: [{ oldText: "rewritten", newText: "final" }], origin: "external" }, toolContext));
202
204
  assert.equal(moved.change_kind, "moved");
203
205
  assert.equal(moved.rename_from, "owned.md");
204
206
  assert.match(moved.diff, /rename owned\.md -> @project\/renamed\.md/);
205
- const renamed = data(await notesRead.execute({ address: moved.address }, notesIdentity));
207
+ const renamed = data(await notesRead.execute({ address: moved.address }, toolContext));
206
208
  assert.equal(renamed.text, "final");
207
209
  assert.equal(renamed.metadata.origin, "external");
208
- const unchanged = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "delta", newText: "delta" }] }, notesIdentity));
210
+ const unchanged = data(await notesUpdate.execute({ address: "@project/test.md", edits: [{ oldText: "delta", newText: "delta" }] }, toolContext));
209
211
  assert.equal(unchanged.change_kind, "none");
210
212
  assert.equal(unchanged.diff, "");
211
213
  // Frontmatter is metadata, not body: the window addresses the body and counts only the body.
212
214
  const stored = await createNotesStore(notesIdentity).read("@project/test.md");
213
215
  assert.ok(stored, "the note is on disk");
214
216
  const body = Array.from(stored.body);
215
- const read = data(await notesRead.execute({ address: "@project/test.md" }, notesIdentity));
217
+ const read = data(await notesRead.execute({ address: "@project/test.md" }, toolContext));
216
218
  assert.equal(read.text, stored.body, "a complete read is the whole body and nothing else");
217
219
  assert.equal(read.total_chars, body.length);
218
220
  assert.equal(read.next_offset_chars, null);
219
221
  assert.equal(read.metadata.origin, "self");
220
222
  assert.equal(notesRead.render(success(read)).includes("READ WINDOW"), false, "a read presents no metadata block");
221
223
  // A negative offset resolves against the body, never against the serialized file.
222
- const tail = data(await notesRead.execute({ address: "@project/test.md", offset_chars: -4 }, notesIdentity));
224
+ const tail = data(await notesRead.execute({ address: "@project/test.md", offset_chars: -4 }, toolContext));
223
225
  assert.equal(tail.text, body.slice(-4).join(""));
224
226
  assert.equal(tail.total_chars, body.length, "metadata length never enters the body cursor");
225
227
  assert.equal(tail.next_offset_chars, null);
226
- assert.equal(refusal(await notesRead.execute({ address: "@project/missing.md" }, notesIdentity)).code, "not_found");
227
- assert.equal(refusal(await notesWrite.execute({ address: "../escape", content: "x" }, notesIdentity)).code, "invalid_address");
228
- assert.equal(refusal(await notesRead.execute({ address: "@project/test.md", offset_chars: 99_999 }, notesIdentity)).code, "invalid_offset");
228
+ assert.equal(refusal(await notesRead.execute({ address: "@project/missing.md" }, toolContext)).code, "not_found");
229
+ assert.equal(refusal(await notesWrite.execute({ address: "../escape", content: "x" }, toolContext)).code, "invalid_address");
230
+ assert.equal(refusal(await notesRead.execute({ address: "@project/test.md", offset_chars: 99_999 }, toolContext)).code, "invalid_offset");
229
231
  });
230
232
  test("shared history operations read typed events through the addresses the adapter allocated", async () => {
231
233
  const projection = projectHistory([{ windowId: "root", items: [
@@ -0,0 +1,78 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { BOOT_TYPE, CONTINUATION_TYPE, MARKER_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
5
+ import { nextHistorySeq } from "../plugins/pi/history.js";
6
+ import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
7
+ import { appendText, context, installExtensionTestEnvironment, makeExtension, runCommand, runHandlers, sentOf } from "./helpers/extension.js";
8
+ const env = installExtensionTestEnvironment("notesoup-marker-test");
9
+ test.beforeEach(env.beforeEach);
10
+ test.afterEach(env.afterEach);
11
+ test.after(env.dispose);
12
+ function turnStart(captured, ctx) {
13
+ return runHandlers(captured, "turn_start", { type: "turn_start" }, ctx);
14
+ }
15
+ test("marker stamps its own seq once the interval is reached, then holds", async () => {
16
+ const sessionManager = managerWithMessages(49);
17
+ const captured = makeExtension(sessionManager);
18
+ const ctx = context(sessionManager);
19
+ await turnStart(captured, ctx);
20
+ const sent = sentOf(captured, MARKER_TYPE);
21
+ assert.equal(sent.length, 1);
22
+ assert.deepEqual(sent[0].message.details, { seq: 50 });
23
+ assert.equal(sent[0].message.display, false);
24
+ assert.equal(sent[0].options?.triggerTurn, false);
25
+ assert.equal(sent[0].message.content, '<notesoup:marker seq="50" />');
26
+ assert.equal(nextHistorySeq(ctx), 51, "the marker occupies the seq it names");
27
+ // An immediate second turn is only one seq later: no new marker.
28
+ await turnStart(captured, ctx);
29
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 1);
30
+ // The next marker lands exactly one interval after the last.
31
+ appendText(sessionManager, "user", "x".repeat(1));
32
+ for (let i = 0; i < 48; i++)
33
+ appendText(sessionManager, "assistant", "y");
34
+ await turnStart(captured, ctx);
35
+ const all = sentOf(captured, MARKER_TYPE);
36
+ assert.equal(all.length, 2);
37
+ assert.deepEqual(all[1].message.details, { seq: 100 });
38
+ });
39
+ test("no marker before the interval", async () => {
40
+ const sessionManager = managerWithMessages(48);
41
+ const captured = makeExtension(sessionManager);
42
+ await turnStart(captured, context(sessionManager));
43
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
44
+ assert.equal(MARKER_INTERVAL, 50);
45
+ });
46
+ test("a reset tail awaiting repair closes the road to markers, then reopens it", async () => {
47
+ const sessionManager = managerWithMessages(49);
48
+ const captured = makeExtension(sessionManager);
49
+ const ctx = context(sessionManager);
50
+ // A marker with neither boot nor continuation still expects repair; stay out of its tail.
51
+ sessionManager.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:test:w1" });
52
+ await turnStart(captured, ctx);
53
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
54
+ // Boot alone is still an open tail.
55
+ sessionManager.appendCustomMessageEntry(BOOT_TYPE, "boot", false, { windowId: "pcw:test:w1" });
56
+ await turnStart(captured, ctx);
57
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
58
+ // Once the shape is closed, the odometer continues across the reset: seq never restarted.
59
+ sessionManager.appendCustomMessageEntry(CONTINUATION_TYPE, "continued", false);
60
+ await turnStart(captured, ctx);
61
+ const sent = sentOf(captured, MARKER_TYPE);
62
+ assert.equal(sent.length, 1);
63
+ assert.deepEqual(sent[0].message.details, { seq: 52 });
64
+ });
65
+ test("notesoup off silences the odometer", async () => {
66
+ const sessionManager = managerWithMessages(49);
67
+ const captured = makeExtension(sessionManager);
68
+ const ctx = context(sessionManager);
69
+ await runCommand(captured, "notesoup", "off", ctx);
70
+ await turnStart(captured, ctx);
71
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
72
+ });
73
+ function managerWithMessages(count) {
74
+ const sessionManager = SessionManager.inMemory("/private/tmp/notesoup-marker-test");
75
+ for (let i = 0; i < count; i++)
76
+ appendText(sessionManager, i % 2 === 0 ? "user" : "assistant", `m${i}`);
77
+ return sessionManager;
78
+ }
@@ -44,7 +44,7 @@ const GOLDEN_FORCED_CONTINUATIONS = [
44
44
  "Oh, there you are. Somebody took your memories. Just like that. Here are your notes — hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate.",
45
45
  ];
46
46
  const GOLDEN_MAPS = `<notesoup:maps>
47
- Every home's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
47
+ Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
48
48
  Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
49
49
  wakes up next reads them, and next is you. So keep them short, and keep them true.
50
50
 
@@ -52,9 +52,10 @@ wakes up next reads them, and next is you. So keep them short, and keep them tru
52
52
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
53
53
  and everybody pays for it.
54
54
  - **\`MAP.md\`** is only the note index. One line per durable note: the address, then a gist short
55
- enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, not here.
55
+ enough to tell whether the thing is worth opening. Rules belong in \`CHEATSHEET.md\`, and note
56
+ contents belong in their own notes — *taps the sign* not inline here.
56
57
 
57
- Each home keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
58
+ Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
58
59
  no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
59
60
  line. And when a line stops being true, kill it — every window after you reads that page as fact.
60
61
  </notesoup:maps>`;
@@ -70,7 +71,7 @@ function note(scope, path, address, body) {
70
71
  meta: { scope, origin: "self", createdAt: openedAt, updatedAt: openedAt, lastAccessed: openedAt, accessCount: 0 },
71
72
  };
72
73
  }
73
- /** Render one boot with only the named homes carrying rows. */
74
+ /** Render one boot with only the named notebooks carrying rows. */
74
75
  async function boot(agentName, rows) {
75
76
  const notes = await loadNotesSnapshot({ ...identity, agent: agentName }, openedAt, (scope) => rows.get(scope) ?? []);
76
77
  return renderBootBlock({
@@ -141,7 +142,7 @@ test("a rendered boot carries the new tags, its own MAP section, and no pre-rena
141
142
  assert.ok(rendered.includes(`\n${NOTES_PROTOCOL_CLOSE_TAG}\n\n${MAPS_BLOCK}\n\nYOUR NOTES`), "the MAP block sits between the protocol and the shelves");
142
143
  assert.equal(/context_window/.test(rendered), false, "the boot is free of the old spelling");
143
144
  assert.ok(rendered.includes("@self — root only"), "a named agent's shelf says it is theirs alone");
144
- assert.ok(rendered.includes("map\n\n AGENT_MAP_BODY"), "the pinned MAP is headed by its own label");
145
+ assert.ok(rendered.includes("@agents/root/MAP.md\n\n AGENT_MAP_BODY"), "the pinned MAP heading is its exact tool address");
145
146
  assert.equal(rendered.includes("MAP — "), false, "the old MAP heading is gone");
146
147
  });
147
148
  test("cheatsheets and maps are independently pinned, bounded, and excluded from recent pages", async () => {
@@ -163,9 +164,12 @@ test("cheatsheets and maps are independently pinned, bounded, and excluded from
163
164
  }]],
164
165
  ]);
165
166
  const rendered = (await boot("root", rows)).split("YOUR NOTES")[1];
166
- assert.ok(rendered.includes("cheatsheet\n\n SESSION_RULE"));
167
- assert.ok(rendered.includes("cheatsheet\n\n PROJECT_RULE\n\nmap\n\n PROJECT_INDEX"));
168
- assert.ok(rendered.includes("map\n\n HUMAN_INDEX"));
167
+ assert.ok(rendered.includes("CHEATSHEET.md\n\n SESSION_RULE"));
168
+ assert.ok(rendered.includes("@project/CHEATSHEET.md\n\n PROJECT_RULE\n\n@project/MAP.md\n\n PROJECT_INDEX"));
169
+ assert.ok(rendered.includes("@human/MAP.md\n\n HUMAN_INDEX"));
170
+ assert.ok(rendered.includes("@self/CHEATSHEET.md\n\n 🐑"));
171
+ assert.ok(rendered.includes("@self/MAP.md\n\n M"));
172
+ assert.equal(/^(?:map|cheatsheet)$/m.test(rendered), false, "pinned headings never suggest lowercase aliases");
169
173
  assert.ok(rendered.includes("@project/n2.md ·"));
170
174
  assert.equal(rendered.includes("TITLE_3"), false);
171
175
  assert.equal(/(?:MAP|CHEATSHEET)\.md ·/.test(rendered), false);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,114 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { Check } from "typebox/value";
7
+ import { createNotesStore, projectKey, snapshotNotesIdentity } from "../src/notes/index.js";
8
+ import { parseNote } from "../src/notes/frontmatter.js";
9
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../src/tools/notes.js";
10
+ import { notesToolContext } from "../src/tools/notes-context.js";
11
+ function fixture(t) {
12
+ const root = mkdtempSync(join(tmpdir(), "notesoup-notes-cwd-"));
13
+ t.after(() => rmSync(root, { recursive: true, force: true }));
14
+ const home = join(root, "notes");
15
+ const alpha = join(root, "alpha");
16
+ const beta = join(root, "beta");
17
+ const nested = join(alpha, "one", "two");
18
+ mkdirSync(nested, { recursive: true });
19
+ mkdirSync(beta);
20
+ const identity = (cwd, sessionId = "session") => snapshotNotesIdentity({
21
+ home, sessionId, projectKey: projectKey(cwd, home), agent: "agent", model: "model",
22
+ });
23
+ return { root, home, alpha, beta, nested, identity };
24
+ }
25
+ function data(result) {
26
+ if (!result.ok)
27
+ assert.fail(result.error.message);
28
+ return result.data;
29
+ }
30
+ function refusal(result) {
31
+ if (result.ok)
32
+ assert.fail("expected refusal");
33
+ return result.error;
34
+ }
35
+ test("all five notes schemas accept one optional non-empty cwd", () => {
36
+ for (const operation of [notesWrite, notesUpdate, notesRead, notesList, notesSearch]) {
37
+ const base = operation === notesWrite ? { address: "a", content: "x" }
38
+ : operation === notesUpdate ? { address: "a", edits: [{ oldText: "x", newText: "y" }] }
39
+ : operation === notesSearch ? { query: "x" }
40
+ : operation === notesRead ? { address: "a" } : {};
41
+ assert.equal(Check(operation.parameters, { ...base, cwd: "../other" }), true, operation.name);
42
+ assert.equal(Check(operation.parameters, { ...base, cwd: "" }), false, `${operation.name} rejects empty cwd`);
43
+ }
44
+ });
45
+ test("one relative cwd retargets every operation without changing later calls", async (t) => {
46
+ const f = fixture(t);
47
+ const alpha = f.identity(f.alpha);
48
+ const beta = f.identity(f.beta);
49
+ await createNotesStore(alpha).write("@project/decision", "alpha needle");
50
+ await createNotesStore(beta).write("@project/decision", "beta before");
51
+ const context = notesToolContext(alpha, f.nested);
52
+ const cwd = "../../../beta";
53
+ const written = data(await notesWrite.execute({ address: "@project/other", content: "beta other needle", cwd }, context));
54
+ assert.equal(written.project_key, beta.projectKey);
55
+ assert.equal((await createNotesStore(alpha).read("@project/other")), undefined);
56
+ assert.equal(data(await notesRead.execute({ address: "@project/other", cwd }, context)).text, "beta other needle");
57
+ assert.equal(data(await notesRead.execute({ address: "@project/decision", cwd }, context)).text, "beta before");
58
+ const moved = data(await notesUpdate.execute({ address: "@project/decision", rename_to: "@project/renamed", edits: [{ oldText: "before", newText: "after" }], cwd }, context));
59
+ assert.equal(moved.project_key, beta.projectKey);
60
+ assert.equal(moved.address, "@project/renamed.md");
61
+ assert.equal((await createNotesStore(beta).read("@project/renamed"))?.body, "beta after");
62
+ assert.equal((await createNotesStore(alpha).read("@project/decision"))?.body, "alpha needle");
63
+ const defaultListed = data(await notesList.execute({ cwd }, context));
64
+ assert.deepEqual(defaultListed.files.map(file => file.address).sort(), ["@project/other.md", "@project/renamed.md"], "an omitted glob selects the override's current notebooks");
65
+ assert.ok(defaultListed.files.every(file => file.project_key === beta.projectKey));
66
+ const listed = data(await notesList.execute({ glob: "@project/**", cwd }, context));
67
+ assert.deepEqual(listed.files.map(file => file.address).sort(), ["@project/other.md", "@project/renamed.md"]);
68
+ assert.ok(listed.files.every(file => file.project_key === beta.projectKey));
69
+ const searched = data(await notesSearch.execute({ query: "needle", glob: "@project/**", cwd }, context));
70
+ assert.deepEqual(searched.files.map(file => file.address), ["@project/other.md"]);
71
+ // The captured context is unchanged: omitting cwd still means alpha.
72
+ assert.equal(data(await notesRead.execute({ address: "@project/decision" }, context)).text, "alpha needle");
73
+ assert.deepEqual(data(await notesList.execute({ glob: "@project/**" }, context)).files.map(file => file.address), ["@project/decision.md"]);
74
+ assert.equal(context.identity.projectKey, alpha.projectKey);
75
+ });
76
+ test("a cwd override changes only new session-note ownership, not its physical session", async (t) => {
77
+ const f = fixture(t);
78
+ const alpha = f.identity(f.alpha);
79
+ const beta = f.identity(f.beta);
80
+ const context = notesToolContext(alpha, f.alpha);
81
+ data(await notesWrite.execute({ address: "checkpoint", content: "first", cwd: f.beta }, context));
82
+ const file = join(f.home, "pi", "session", alpha.sessionId, "checkpoint.md");
83
+ assert.equal(parseNote(readFileSync(file, "utf8")).meta.project, beta.projectKey);
84
+ data(await notesWrite.execute({ address: "checkpoint", content: "second" }, context));
85
+ assert.equal(parseNote(readFileSync(file, "utf8")).meta.project, beta.projectKey, "an overwrite preserves existing ownership");
86
+ });
87
+ test("invalid explicit cwd refuses before a write", async (t) => {
88
+ const f = fixture(t);
89
+ const context = notesToolContext(f.identity(f.alpha), f.alpha);
90
+ const file = join(f.root, "file");
91
+ writeFileSync(file, "not a directory");
92
+ for (const cwd of [join(f.root, "missing"), file]) {
93
+ const result = refusal(await notesWrite.execute({ address: "@project/refused", content: "no", cwd }, context));
94
+ assert.equal(result.code, "invalid_cwd");
95
+ assert.match(result.message, /resolved to/);
96
+ }
97
+ assert.equal((await createNotesStore(f.identity(f.alpha)).read("@project/refused")), undefined);
98
+ });
99
+ test("cwd cannot escape or erase the active dream jail", async (t) => {
100
+ const f = fixture(t);
101
+ const alpha = f.identity(f.alpha);
102
+ const beta = f.identity(f.beta);
103
+ const gammaCwd = join(f.root, "gamma");
104
+ mkdirSync(gammaCwd);
105
+ const gamma = f.identity(gammaCwd);
106
+ await createNotesStore(beta).write("@project/rule", "beta");
107
+ const context = notesToolContext({ ...alpha, dreaming: beta.projectKey }, f.alpha);
108
+ const escaped = refusal(await notesWrite.execute({ address: "@project/rule", content: "gamma", cwd: gammaCwd }, context));
109
+ assert.equal(escaped.code, "invalid_scope");
110
+ assert.equal((await createNotesStore(gamma).read("@project/rule")), undefined);
111
+ const dreamed = await notesWrite.execute({ address: `@projects/${beta.projectKey}/rule`, content: "edited", cwd: gammaCwd }, context);
112
+ assert.equal(dreamed.ok, true, "the original dreamed project remains writable through its named address");
113
+ assert.equal((await createNotesStore(beta).read("@project/rule"))?.body, "edited");
114
+ });