notesoup 0.41.0 → 0.43.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 (127) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -7,6 +7,10 @@ import { pathToFileURL } from "node:url";
7
7
  import test from "node:test";
8
8
  import { build } from "esbuild";
9
9
  import { dispatch, handleLine } from "../src/claude/helper.js";
10
+ import { DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, resolveClaudeLimits } from "../src/claude/thresholds.js";
11
+ import { WARNING_RUNWAY_TOKENS } from "../src/budget/constants.js";
12
+ import { PROTOCOL_WIPE_SENTENCE, CLAUDE_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js";
13
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../src/budget/text.js";
10
14
  const identity = { home: mkdtempSync(join(tmpdir(), "claude-mod-")), sessionId: "session", cwd: process.cwd(), agent: "claude", model: "claude" };
11
15
  async function callTool(tool, params) {
12
16
  return await dispatch({ op: "tool", tool, identity, params });
@@ -38,12 +42,13 @@ function fakeEngine(home) {
38
42
  notifications,
39
43
  host: {
40
44
  env: { get: async (name) => name === "PI_NOTES_HOME" ? home : undefined },
41
- session: { id: async () => "hook-session", messages: async () => [], usage: async () => ({ context: {} }), compact: async () => ({ skip: "test default" }) },
45
+ session: { id: async () => "hook-session", cwd: async () => home, model: async () => "claude", messages: async () => [], usage: async () => ({ context: {} }), compact: async () => ({ skip: "test default" }) },
46
+ settings: { read: async () => ({}) },
42
47
  command: { register: async (spec) => ({ command: spec.name }) },
43
48
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
44
49
  prompt: { submit: async () => undefined },
45
50
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
46
- ui: { notify: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
51
+ ui: { toast: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
47
52
  process: { run: async (argv, init) => ({
48
53
  exitCode: 0,
49
54
  stdout: execFileSync(argv[0], argv.slice(1), { cwd: init?.cwd, input: init?.stdin, encoding: "utf8" }),
@@ -87,7 +92,7 @@ test("Claude helper refuses schema-invalid parameters before any operation runs"
87
92
  for (const { name, params } of cases) {
88
93
  const refused = JSON.parse(await handleLine(JSON.stringify({ op: "tool", tool: "notes_read", identity, params })));
89
94
  assert.equal(refused.ok, false, `${name} is refused at the boundary`);
90
- assert.equal(refused.error, "invalid notes_read parameters", `${name} names the refused parameters`);
95
+ assert.match(refused.error ?? "", /^invalid notes_read parameters: (offset_chars|max_chars) /, `${name} names the refused parameter`);
91
96
  }
92
97
  await assert.rejects(callTool("notes_read", { address, offset_chars: "0" }), /invalid notes_read parameters/);
93
98
  // Refusal happens before execute: a rejected mutation leaves nothing on disk.
@@ -109,6 +114,89 @@ test("Claude helper boot uses actual Claude note tool bindings and a fresh snaps
109
114
  assert.match(boot, /claude:session/);
110
115
  assert.doesNotMatch(boot, /memory cleared|continuation/);
111
116
  });
117
+ test("Claude helper serves the shared reset prose and the host's wipe sentence", async () => {
118
+ const texts = await dispatch({ op: "texts" });
119
+ assert.equal(texts.warning, CLAUDE_WARNING_PROMPT, "the helper owns the one warning text the mod shows");
120
+ assert.equal(texts.continuation, CONTINUATION, "the reset message is Pi's, verbatim");
121
+ assert.equal(texts.wipeSentence, CLAUDE_WIPE_SENTENCE);
122
+ assert.match(texts.warning, /end your turn; the reset runs after it\.$/);
123
+ });
124
+ /** The point values the resolver produced, without the margin bookkeeping. */
125
+ function limitPoints(facts) {
126
+ const limits = resolveClaudeLimits(facts);
127
+ return { source: limits.source, unit: limits.unit, autoCompact: limits.autoCompact, native: limits.native, reset: limits.reset, warn: limits.warn };
128
+ }
129
+ // Claude compacts at min(floor((W-20000)*pct/100), W-20000-13000); notesoup resets 8192 below
130
+ // that and warns 16384 earlier. These are the numbers, not prose.
131
+ const CLAUDE_200K = { native: 167_000, reset: 158_808, warn: 142_424 };
132
+ test("Claude limits derive from Claude's own auto-compact point, never a fixed percent", () => {
133
+ // (a) Claude's own threshold is the most faithful source, and the percent override can only lower it.
134
+ const fromBreakdown = { usage: { tokens: 166_000, window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: true } };
135
+ assert.deepEqual(limitPoints(fromBreakdown), { source: "auto-compact", unit: "tokens", autoCompact: true, ...CLAUDE_200K });
136
+ assert.deepEqual(limitPoints({ ...fromBreakdown, env: { pctOverride: "50" } }), { source: "auto-compact", unit: "tokens", autoCompact: true, native: 90_000, reset: 81_808, warn: 65_424 }, "floor((167000+13000)*50/100)");
137
+ assert.deepEqual(limitPoints({ ...fromBreakdown, env: { pctOverride: "96" } }), { source: "auto-compact", unit: "tokens", autoCompact: true, ...CLAUDE_200K }, "an override above the default cannot raise the point");
138
+ for (const pctOverride of ["0", "101", "abc", ""])
139
+ assert.deepEqual(limitPoints({ ...fromBreakdown, env: { pctOverride } }), { source: "auto-compact", unit: "tokens", autoCompact: true, ...CLAUDE_200K }, `pct ${pctOverride} is ignored`);
140
+ // (b) The same point computed from the reported window, settings and environment.
141
+ assert.deepEqual(limitPoints({ usage: { tokens: 960_000, window: 1_000_000 } }), { source: "window", unit: "tokens", autoCompact: true, native: 967_000, reset: 958_808, warn: 942_424 });
142
+ assert.equal(limitPoints({ usage: { window: 1_000_000 }, settings: { autoCompactWindow: 500_000 } }).native, 467_000);
143
+ assert.equal(limitPoints({
144
+ usage: { window: 1_000_000 },
145
+ breakdown: { model: "claude-opus-4-6" },
146
+ env: { autoCompactWindow: "400000" },
147
+ settings: { autoCompactWindow: 500_000, modelSettings: { "claude-opus-4-6": { autoCompactWindow: 300_000 } } },
148
+ }).native, 267_000, "the smallest configured window wins");
149
+ // Auto-compact off: the point moves to the hard window, and the margins stay.
150
+ const offSettings = { usage: { tokens: 171_808, window: 200_000 }, settings: { autoCompactEnabled: false } };
151
+ assert.deepEqual(limitPoints(offSettings), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
152
+ assert.deepEqual(limitPoints({ usage: { window: 200_000 }, env: { disableAutoCompact: "1" } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
153
+ assert.deepEqual(limitPoints({ usage: { window: 200_000 }, breakdown: { isAutoCompactEnabled: false } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
154
+ assert.deepEqual(limitPoints({ usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: false } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 }, "an off session ignores a stale threshold");
155
+ // (c) No window, no breakdown: the same reserves expressed on the classic 200K window.
156
+ const percent = limitPoints({});
157
+ assert.equal(percent.source, "percent");
158
+ assert.equal(percent.unit, "percent");
159
+ assert.ok(Math.abs(percent.native - 83.5) < 1e-9 && Math.abs(percent.reset - 79.404) < 1e-9 && Math.abs(percent.warn - 71.212) < 1e-9, "83.5 / 79.4 / 71.2 on 200K");
160
+ assert.equal(limitPoints({ env: { pctOverride: "50" } }).native, 50);
161
+ // A real window is never re-expressed on the assumed 200K window, and no point is zero:
162
+ // the mod treats `measured >= reset` as due, so a zero point would clear memory every turn.
163
+ const tiny = limitPoints({ usage: { window: 8_000 } });
164
+ assert.deepEqual({ source: tiny.source, unit: tiny.unit }, { source: "window", unit: "tokens" }, "a real window answers even below the reserves");
165
+ assert.ok(tiny.reset >= 1 && tiny.warn >= 1, "a window smaller than the reserves still has a point");
166
+ const absurdMargin = limitPoints({ settings: { notesoup: { resetMarginTokens: 400_000 } } });
167
+ assert.equal(absurdMargin.source, "percent");
168
+ assert.ok(absurdMargin.reset > 0 && absurdMargin.warn > 0, "an absurd margin cannot zero the percent fallback either");
169
+ });
170
+ test("Claude limits read margins from the notesoup settings shape and ignore garbage", () => {
171
+ const base = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: true } };
172
+ assert.deepEqual(limitPoints({ ...base, settings: { notesoup: { resetMarginTokens: 10_000, warningRunwayTokens: 5_000 } } }), { source: "auto-compact", unit: "tokens", autoCompact: true, native: 167_000, reset: 157_000, warn: 152_000 });
173
+ for (const notesoup of [{ resetMarginTokens: 0 }, { resetMarginTokens: 8.5 }, { warningRunwayTokens: -1 }, { warningRunwayTokens: "big" }, "nonsense", null])
174
+ assert.deepEqual(limitPoints({ ...base, settings: { notesoup } }), { source: "auto-compact", unit: "tokens", autoCompact: true, ...CLAUDE_200K }, `notesoup ${JSON.stringify(notesoup)} degrades to the defaults`);
175
+ assert.equal(limitPoints({ ...base, settings: "nonsense", env: "nonsense", usage: "nonsense", breakdown: "nonsense" }).unit, "percent", "malformed facts degrade rather than throw");
176
+ // Malformed facts never throw: the resolver is the mod-helper boundary.
177
+ for (const facts of [undefined, null, "x", 7, [], { usage: { window: "nope" }, breakdown: { autoCompactThreshold: null } }])
178
+ assert.equal(resolveClaudeLimits(facts).unit, "percent");
179
+ });
180
+ test("Claude helper resolves limits across the boundary and never throws on nonsense", async () => {
181
+ const resolved = await dispatch({ op: "limits", facts: { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000 } } });
182
+ assert.equal(resolved.native, 167_000);
183
+ assert.equal(resolved.reset, 167_000 - DEFAULT_CLAUDE_RESET_MARGIN_TOKENS);
184
+ assert.equal(DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, 8_192);
185
+ assert.equal(WARNING_RUNWAY_TOKENS, 16_384);
186
+ const nonsense = JSON.parse(await handleLine(JSON.stringify({ op: "limits", facts: "nonsense" })));
187
+ assert.equal(nonsense.ok, true);
188
+ assert.equal(nonsense.result.unit, "percent");
189
+ assert.ok(nonsense.result.warn > 0 && nonsense.result.warn < 100);
190
+ });
191
+ test("Claude's wipe sentence replaces only that sentence in the shared protocol block", () => {
192
+ const piTools = { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "clear_memory" };
193
+ const pi = renderProtocolBlock(piTools);
194
+ assert.ok(pi.includes(PROTOCOL_WIPE_SENTENCE), "Pi keeps the default sentence, byte for byte");
195
+ const claude = renderProtocolBlock({ ...piTools, wipeSentence: CLAUDE_WIPE_SENTENCE });
196
+ assert.equal(claude, pi.replace(PROTOCOL_WIPE_SENTENCE, CLAUDE_WIPE_SENTENCE), "only that sentence changes");
197
+ assert.equal(claude.includes("erase yourself with dignity"), false);
198
+ assert.ok(claude.includes("end your turn and ask the human to run `/clear-memory`."));
199
+ });
112
200
  test("Claude Mod helper runs from a standalone copied plugin directory", () => {
113
201
  const fixture = mkdtempSync(join(tmpdir(), "claude-mod-install-"));
114
202
  try {
@@ -160,6 +248,8 @@ test("Claude Mod appends boot once and reuses persisted blocks after re-registra
160
248
  assert.equal(boot.name, "notesoup:boot");
161
249
  assert.ok(boot.text.length > 0, "the boot block carries real boot text");
162
250
  assert.match(boot.text, /mcp__notesoup__notes_\*/, "the boot text names the actual Claude note tool binding");
251
+ assert.ok(boot.text.includes(CLAUDE_WIPE_SENTENCE), "the boot speaks the Claude wipe path");
252
+ assert.equal(boot.text.includes("erase yourself with dignity"), false);
163
253
  assert.equal(first.sentinel, "kept", "unrelated result fields survive");
164
254
  assert.equal(bootRequests, 1, "the first prompt makes exactly one boot helper request");
165
255
  assert.equal(nextCalls, 1, "the upstream chain runs exactly once per prompt");
@@ -170,7 +260,7 @@ test("Claude Mod appends boot once and reuses persisted blocks after re-registra
170
260
  assert.deepEqual(notifications, [], "successful boot never notifies");
171
261
  });
172
262
  test("Claude Mod boot failure preserves fallback with available, absent, or failing notifications", async (t) => {
173
- for (const mode of ["available", "no ui", "no notify", "throws", "rejects"]) {
263
+ for (const mode of ["available", "no ui", "no toast", "throws", "rejects"]) {
174
264
  await t.test(mode, async (t) => {
175
265
  const hooks = await loadHookModule(t);
176
266
  const home = mkdtempSync(join(tmpdir(), "claude-hook-home-"));
@@ -178,10 +268,10 @@ test("Claude Mod boot failure preserves fallback with available, absent, or fail
178
268
  const { host, notifications } = fakeEngine(home);
179
269
  if (mode === "no ui")
180
270
  delete host.ui;
181
- else if (mode === "no notify")
271
+ else if (mode === "no toast")
182
272
  host.ui = {};
183
273
  else if (mode === "throws" || mode === "rejects") {
184
- host.ui = { notify: (text) => {
274
+ host.ui = { toast: (text) => {
185
275
  notifications.push(text);
186
276
  if (mode === "throws")
187
277
  throw new Error("notification unavailable");
@@ -207,9 +297,9 @@ test("Claude Mod boot failure preserves fallback with available, absent, or fail
207
297
  const failed = await promptContext(structuredClone(upstream));
208
298
  assert.deepEqual(failed, {
209
299
  ...upstream,
210
- blocks: [...upstream.blocks, { name: "notesoup:boot", text: "# notesoup\nhelper exited unsuccessfully" }],
300
+ blocks: [...upstream.blocks, { name: "notesoup:boot", text: "# notesoup\nYour notes didn't load this time (helper exited unsuccessfully). Try `mcp__notesoup__notes_list`; if it fails too, tell the human." }],
211
301
  }, "boot failure keeps the original fallback and upstream fields even if notify is absent or fails");
212
- const expectedNotifications = mode === "no ui" || mode === "no notify" ? [] : ["🥣 Notes didn't load"];
302
+ const expectedNotifications = mode === "no ui" || mode === "no toast" ? [] : ["🥣 Notes didn't load"];
213
303
  assert.deepEqual(notifications, expectedNotifications, "one user-facing notification reports the notes boot failure");
214
304
  assert.equal(bootRequests, 1);
215
305
  assert.equal(nextCalls, 1);
@@ -245,52 +335,60 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
245
335
  const foreign = await call("other_tool", {});
246
336
  assert.equal("result" in foreign, false, "an unregistered tool falls through to the engine's own handling");
247
337
  });
248
- test("Claude Mod resets at 85 after the turn, retains one fresh boot and deduplicates measure", async (t) => {
338
+ test("Claude Mod resets at Claude's resolved point after the turn, retains one fresh boot and deduplicates measure", async (t) => {
249
339
  const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
250
340
  t.after(() => rmSync(home, { recursive: true, force: true }));
251
341
  const { host, registered, notifications } = fakeEngine(home);
252
342
  const handlers = new Map();
253
343
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
254
344
  const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
255
- let percent = 84;
345
+ // A 200K window resolves to Claude's 167 000 point, so notesoup resets 8 192 below it.
346
+ let tokens = 140_000;
256
347
  let compactions = 0;
257
348
  let kept = [];
258
- host.session.usage = async () => ({ context: { percent } });
349
+ const measured = () => ({ context: { tokens, window: 200_000, percent: tokens === undefined ? undefined : (tokens / 200_000) * 100 } });
350
+ host.session.usage = async () => measured();
259
351
  host.session.compact = async ({ instructions }) => {
260
352
  compactions++;
261
353
  const result = await invoke("session.compact", { trigger: "plugin", instructions: `${instructions} (rewritten upstream)`, messages: [{ role: "user", text: "OLD_SECRET" }] });
262
354
  kept = result.messages;
263
- percent = undefined; // The real engine invalidates token usage after compact.
355
+ tokens = undefined; // The real engine invalidates token usage after compact.
264
356
  return result;
265
357
  };
266
358
  await invoke("session.start", { cwd: home, isInteractive: true });
267
359
  assert.equal(registered.length, 5);
268
360
  const initial = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
361
+ assert.equal(initial.blocks.length, 1, "below the warn point no warning joins the boot");
269
362
  assert.match(initial.blocks[0].text, /Current context window id: claude:hook-session:0/);
270
363
  await invoke("turn.start");
271
364
  await invoke("session.measure");
272
365
  await invoke("turn.complete");
273
- assert.equal(compactions, 0, "84 is below the fixed threshold");
366
+ assert.equal(compactions, 0, "140000 is below every resolved point");
274
367
  host.session.usage = async () => { throw new Error("usage unavailable"); };
275
368
  await invoke("session.measure");
276
369
  await invoke("turn.complete");
277
370
  assert.equal(notifications.filter((text) => text.includes("Context usage unavailable")).length, 1, "usage failure logs once per session");
278
- host.session.usage = async () => ({ context: { percent } });
371
+ host.session.usage = async () => measured();
279
372
  await dispatch({ op: "tool", tool: "notes_write", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, params: { address: "@human/MAP.md", content: "FRESH_NOTES_AT_RESET" } });
280
373
  await invoke("turn.start");
281
- percent = 85;
374
+ tokens = 158_807;
375
+ await invoke("turn.complete");
376
+ assert.equal(compactions, 0, "one token below the resolved reset point");
377
+ await invoke("turn.start");
378
+ tokens = 158_808;
282
379
  await invoke("session.measure");
283
380
  assert.equal(compactions, 0, "measure cannot compact under a running turn");
284
381
  assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" });
285
382
  assert.equal(compactions, 1);
286
- assert.equal(kept.length, 1);
383
+ assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
287
384
  assert.equal(kept[0].role, "user");
288
385
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
289
386
  assert.match(kept[0].text, /Previous context window id: claude:hook-session:0/);
290
387
  assert.match(kept[0].text, /FRESH_NOTES_AT_RESET/);
291
388
  assert.doesNotMatch(kept[0].text, /OLD_SECRET/);
389
+ assert.equal(kept[1].text, CONTINUATION, "the continuation is Pi's message, verbatim");
292
390
  await invoke("session.measure");
293
- assert.equal(compactions, 1, "invalidated percent cannot immediately reset twice");
391
+ assert.equal(compactions, 1, "invalidated tokens cannot immediately reset twice");
294
392
  const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
295
393
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => upstream), upstream, "the retained boot is not injected a second time");
296
394
  });
@@ -301,16 +399,16 @@ test("Claude Mod headless detection skips compaction and logs once", async (t) =
301
399
  const handlers = new Map();
302
400
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
303
401
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({ sentinel: name }));
304
- let percent;
402
+ let tokens;
305
403
  let attempts = 0;
306
- host.session.usage = async () => ({ context: { percent } });
404
+ host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
307
405
  host.session.compact = async () => { attempts++; throw new Error("not available in a headless (-p / SDK) session yet"); };
308
406
  await invoke("session.start", { cwd: home, isInteractive: false });
309
407
  await invoke("turn.start");
310
408
  await invoke("turn.complete");
311
409
  await invoke("session.measure");
312
- assert.equal(attempts, 0, "no counters means no automatic reset");
313
- percent = 85;
410
+ assert.equal(attempts, 0, "no measured tokens means no automatic reset");
411
+ tokens = 190_000;
314
412
  await invoke("turn.start");
315
413
  assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" }, "a rejection does not break the turn chain");
316
414
  await invoke("session.measure");
@@ -338,7 +436,7 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
338
436
  return { exitCode: 1, stdout: "" };
339
437
  return run(argv, init);
340
438
  };
341
- host.session.usage = async () => ({ context: { percent: 85 } });
439
+ host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
342
440
  let result = {};
343
441
  host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
344
442
  await invoke("turn.start");
@@ -349,7 +447,9 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
349
447
  await invoke("turn.start");
350
448
  await invoke("turn.complete");
351
449
  assert.equal(result.skip, undefined);
450
+ assert.equal(result.messages.length, 2);
352
451
  assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
452
+ assert.equal(result.messages[1].text, CONTINUATION);
353
453
  });
354
454
  test("Claude Mod manual reset uses one hidden close-out turn, then recovers its boot on reload", async (t) => {
355
455
  const home = mkdtempSync(join(tmpdir(), "claude-manual-home-"));
@@ -382,8 +482,11 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
382
482
  assert.equal(timers.length, 1);
383
483
  await timers.shift()();
384
484
  assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
485
+ assert.equal(prompts[0], CLAUDE_WARNING_PROMPT, "the close-out is the same warning text the automatic path shows");
385
486
  assert.equal(compactions, 1);
487
+ assert.equal(kept.length, 2);
386
488
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
489
+ assert.equal(kept[1].text, CONTINUATION);
387
490
  host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
388
491
  handlers = new Map();
389
492
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
@@ -395,10 +498,309 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
395
498
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
396
499
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
397
500
  });
398
- test("Claude dream skill projection stays byte-identical to canonical shared files", () => {
501
+ test("Claude Mod warns once per window once the measured context crosses the runway", async (t) => {
502
+ const home = mkdtempSync(join(tmpdir(), "claude-warn-home-"));
503
+ t.after(() => rmSync(home, { recursive: true, force: true }));
504
+ const { host } = fakeEngine(home);
505
+ const handlers = new Map();
506
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
507
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
508
+ let tokens = 142_423;
509
+ host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
510
+ host.session.compact = async ({ instructions }) => await invoke("session.compact", { trigger: "plugin", instructions });
511
+ await invoke("session.start", { cwd: home, isInteractive: true });
512
+ const promptContext = (result) => handlers.get("prompt.context")(host, {}, async () => result);
513
+ const upstream = { blocks: [{ name: "claude:user-context", text: "upstream" }] };
514
+ assert.deepEqual((await promptContext(structuredClone(upstream))).blocks.map((block) => block.name), ["claude:user-context", "notesoup:boot"], "one token below the warn point is silent");
515
+ tokens = 142_424;
516
+ const warned = await promptContext(structuredClone(upstream));
517
+ assert.deepEqual(warned.blocks.map((block) => block.name), ["claude:user-context", "notesoup:boot", "notesoup:warning"]);
518
+ assert.equal(warned.blocks[2].text, CLAUDE_WARNING_PROMPT);
519
+ assert.deepEqual(await promptContext(structuredClone(warned)), warned, "one warning per window");
520
+ // A reset opens a new window, and the flag resets with it.
521
+ await invoke("turn.start");
522
+ tokens = 158_808;
523
+ await invoke("turn.complete");
524
+ tokens = 142_424;
525
+ const again = await promptContext(structuredClone(upstream));
526
+ assert.deepEqual(again.blocks.map((block) => block.name), ["claude:user-context", "notesoup:warning"], "the new window warns again, and its retained boot is not duplicated");
527
+ assert.equal(again.blocks[1].text, CLAUDE_WARNING_PROMPT);
528
+ });
529
+ test("Claude Mod moves the reset point to the hard window when auto-compact is off", async (t) => {
530
+ const home = mkdtempSync(join(tmpdir(), "claude-off-home-"));
531
+ t.after(() => rmSync(home, { recursive: true, force: true }));
532
+ const { host, notifications } = fakeEngine(home);
533
+ host.settings = { read: async () => ({ autoCompactEnabled: false }) };
534
+ const handlers = new Map();
535
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
536
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
537
+ let tokens = 171_807;
538
+ let compactions = 0;
539
+ host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
540
+ host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
541
+ await invoke("session.start", { cwd: home, isInteractive: true });
542
+ await invoke("turn.start");
543
+ await invoke("turn.complete");
544
+ assert.equal(compactions, 0, "171807 is below the hard-window point");
545
+ await invoke("turn.start");
546
+ tokens = 171_808;
547
+ await invoke("turn.complete");
548
+ assert.equal(compactions, 1, "200000 - 20000 - 8192");
549
+ assert.deepEqual(notifications.filter((text) => text.includes("unavailable") || text.includes("Couldn't")), [], "a resolvable configuration logs no failure");
550
+ });
551
+ test("Claude Mod stops the automatic reset and the manual command under DISABLE_COMPACT", async (t) => {
552
+ const home = mkdtempSync(join(tmpdir(), "claude-disabled-home-"));
553
+ t.after(() => rmSync(home, { recursive: true, force: true }));
554
+ const { host, notifications } = fakeEngine(home);
555
+ host.env = { get: async (name) => name === "PI_NOTES_HOME" ? home : name === "DISABLE_COMPACT" ? "1" : undefined };
556
+ const timers = [];
557
+ host.clock.after = (_ms, callback) => { timers.push(callback); };
558
+ const handlers = new Map();
559
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
560
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
561
+ let compactions = 0;
562
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
563
+ host.session.compact = async () => { compactions++; return {}; };
564
+ await invoke("session.start", { cwd: home, isInteractive: true });
565
+ assert.equal(notifications.length, 1, "one startup line");
566
+ assert.match(notifications[0], /DISABLE_COMPACT/);
567
+ const manual = await invoke("command.run", { command: "clear-memory" });
568
+ assert.match(manual.text, /DISABLE_COMPACT/);
569
+ assert.equal(timers.length, 0, "no close-out turn is queued");
570
+ await invoke("turn.start");
571
+ await invoke("session.measure");
572
+ await invoke("turn.complete");
573
+ await invoke("session.measure");
574
+ assert.equal(compactions, 0, "the automatic reset is off and does not retry");
575
+ assert.equal(notifications.length, 1, "detection logs once, not per turn");
576
+ });
577
+ test("Claude Mod skips the automatic reset when thresholds cannot be resolved", async (t) => {
578
+ const home = mkdtempSync(join(tmpdir(), "claude-nolimits-home-"));
579
+ t.after(() => rmSync(home, { recursive: true, force: true }));
580
+ const { host, notifications } = fakeEngine(home);
581
+ host.process.run = async () => ({ exitCode: 1, stdout: "" });
582
+ const handlers = new Map();
583
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
584
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
585
+ let compactions = 0;
586
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
587
+ host.session.compact = async () => { compactions++; return {}; };
588
+ await invoke("session.start", { cwd: home, isInteractive: true });
589
+ await invoke("turn.start");
590
+ await invoke("session.measure");
591
+ await invoke("turn.complete");
592
+ await invoke("session.measure");
593
+ assert.equal(compactions, 0, "an unresolvable point never resets");
594
+ assert.equal(notifications.filter((text) => text.includes("Context thresholds unavailable")).length, 1, "one line, not one per turn");
595
+ });
596
+ test("Claude skill projections stay byte-identical to canonical shared files", () => {
597
+ assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/skills/memory/SKILL.md")), readFileSync(join(process.cwd(), "skills/memory/SKILL.md")));
399
598
  assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md")), readFileSync(join(process.cwd(), "skills/dream/SKILL.md")));
400
599
  assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/playbook.md")), readFileSync(join(process.cwd(), "playbook.md")));
401
600
  const skill = readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md"), "utf8");
402
601
  assert.match(skill, /\.\.\/\.\.\/playbook\.md/);
403
602
  assert.doesNotMatch(skill, /Claude.*runner|dream runner/i);
404
603
  });
604
+ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
605
+ const home = mkdtempSync(join(tmpdir(), "claude-subagent-home-"));
606
+ t.after(() => rmSync(home, { recursive: true, force: true }));
607
+ const { host } = fakeEngine(home);
608
+ const handlers = new Map();
609
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
610
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
611
+ let compactions = 0;
612
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
613
+ host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
614
+ await invoke("session.start", { cwd: home, isInteractive: true });
615
+ await invoke("turn.start");
616
+ await invoke("turn.start", { agentId: "sub-1" });
617
+ await invoke("turn.complete", { agentId: "sub-1" });
618
+ await invoke("session.measure");
619
+ assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
620
+ await invoke("turn.complete");
621
+ assert.equal(compactions, 1, "the main turn still resets at its own end");
622
+ });
623
+ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
624
+ const home = mkdtempSync(join(tmpdir(), "claude-flag-off-home-"));
625
+ t.after(() => rmSync(home, { recursive: true, force: true }));
626
+ const { host, notifications } = fakeEngine(home);
627
+ host.env = { get: async (name) => name === "PI_NOTES_HOME" ? home : name === "DISABLE_COMPACT" ? "off" : undefined };
628
+ const handlers = new Map();
629
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
630
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
631
+ let compactions = 0;
632
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
633
+ host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
634
+ await invoke("session.start", { cwd: home, isInteractive: true });
635
+ assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
636
+ await invoke("turn.start");
637
+ await invoke("turn.complete");
638
+ assert.equal(compactions, 1, "the automatic reset still runs");
639
+ });
640
+ test("Claude Mod retries an unresolvable threshold inside the same window", async (t) => {
641
+ const home = mkdtempSync(join(tmpdir(), "claude-retry-home-"));
642
+ t.after(() => rmSync(home, { recursive: true, force: true }));
643
+ const { host } = fakeEngine(home);
644
+ const helper = host.process.run;
645
+ let limitsCalls = 0;
646
+ host.process.run = async (argv, init) => {
647
+ const request = JSON.parse(String(init?.stdin ?? "{}"));
648
+ if (request.op === "limits" && ++limitsCalls === 1)
649
+ return { exitCode: 1, stdout: "" };
650
+ return await helper(argv, init);
651
+ };
652
+ const handlers = new Map();
653
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
654
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
655
+ let compactions = 0;
656
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
657
+ host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
658
+ await invoke("session.start", { cwd: home, isInteractive: true });
659
+ await invoke("turn.start");
660
+ await invoke("turn.complete");
661
+ assert.equal(limitsCalls, 1, "the first limits round trip failed");
662
+ assert.equal(compactions, 0, "one failed resolution does not disable the window");
663
+ await invoke("turn.start");
664
+ await invoke("turn.complete");
665
+ assert.equal(limitsCalls, 2, "the retry runs in the same window");
666
+ assert.equal(compactions, 1, "the retried resolution resets at the turn's end");
667
+ });
668
+ /** Start from a real retained boot, as after notesoup reset or a plugin reload. */
669
+ async function retainedFixture(t) {
670
+ const home = mkdtempSync(join(tmpdir(), "claude-lifecycle-"));
671
+ t.after(() => rmSync(home, { recursive: true, force: true }));
672
+ const { host } = fakeEngine(home);
673
+ const boot = await dispatch({ op: "boot", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, window: 2, tools: {
674
+ notes: "mcp__notesoup__notes_*", notesList: "mcp__notesoup__notes_list",
675
+ history: "unavailable", remaining: "unavailable", wipe: "/clear-memory",
676
+ } });
677
+ host.session.messages = async () => [{ role: "user", text: `# notesoup:boot\n${boot}` }];
678
+ const handlers = new Map();
679
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
680
+ const invoke = (name, e = {}, result = {}) => handlers.get(name)(host, e, async () => result);
681
+ const context = async () => await invoke("prompt.context", {}, { blocks: [] });
682
+ await invoke("session.start", { cwd: home, isInteractive: true });
683
+ assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
684
+ return { home, host, invoke, context, boot };
685
+ }
686
+ test("Claude session.end gives /clear, /resume and /branch a fresh boot and identity", async (t) => {
687
+ for (const action of ["clear", "resume", "branch"]) {
688
+ await t.test(action, async (t) => {
689
+ const { host, invoke, context } = await retainedFixture(t);
690
+ host.session.usage = async () => ({ context: { tokens: 142_424, window: 200_000 } });
691
+ assert.equal((await context()).blocks[0]?.name, "notesoup:warning", "the old window has already warned");
692
+ await invoke("turn.start");
693
+ await invoke("command.run", { command: "clear-memory" });
694
+ const ended = { sentinel: action };
695
+ assert.equal(await invoke("session.end", { reason: action === "clear" ? "clear" : "resume", sessionId: "hook-session" }, ended), ended);
696
+ host.session.id = async () => `after-${action}`;
697
+ host.session.messages = async () => [];
698
+ // Clear the old running-turn and queued-reset state, not just the retained boot.
699
+ let compactions = 0;
700
+ host.session.compact = async () => { compactions++; return {}; };
701
+ await invoke("turn.complete");
702
+ assert.equal(compactions, 0, "the old queued reset cannot spill into the new session");
703
+ const fresh = await context();
704
+ assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot", "notesoup:warning"]);
705
+ assert.match(fresh.blocks[0].text, new RegExp(`Current context window id: claude:after-${action}:0`));
706
+ assert.doesNotMatch(fresh.blocks[0].text, /claude:hook-session:/);
707
+ const requests = [];
708
+ const run = host.process.run;
709
+ host.process.run = async (argv, init) => { requests.push(JSON.parse(init.stdin)); return run(argv, init); };
710
+ const written = await invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "new-session", address: "session.md", content: action });
711
+ assert.equal(written.result, "created session.md");
712
+ assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session home");
713
+ });
714
+ }
715
+ });
716
+ test("Claude lazy identity detects a switched session without session.start or session.end", async (t) => {
717
+ const { host, context } = await retainedFixture(t);
718
+ host.session.id = async () => "lazy-session";
719
+ host.session.messages = async () => [];
720
+ const fresh = await context();
721
+ assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
722
+ assert.match(fresh.blocks[0].text, /Current context window id: claude:lazy-session:0/);
723
+ });
724
+ test("Claude native compaction invalidates only a removed main-conversation retained boot", async (t) => {
725
+ for (const mode of ["manual", "auto", "foreign plugin", "veto", "precompute", "subagent", "kept boot"]) {
726
+ await t.test(mode, async (t) => {
727
+ const { host, invoke, context } = await retainedFixture(t);
728
+ const before = { role: "user", text: "OLD" };
729
+ const trigger = mode === "foreign plugin" ? "plugin" : mode === "precompute" ? "precompute" : mode === "auto" ? "auto" : "manual";
730
+ const event = { trigger, messages: [before], ...(mode === "subagent" ? { agentId: "child" } : {}) };
731
+ const upstream = mode === "veto" ? { skip: "user veto" } : {
732
+ messages: mode === "kept boot" ? await host.session.messages() : [{ role: "user", text: "SUMMARY" }], sentinel: mode,
733
+ };
734
+ assert.equal(await invoke("session.compact", event, upstream), upstream, "native compaction is passed through unchanged");
735
+ const after = await context();
736
+ if (["manual", "auto", "foreign plugin"].includes(mode)) {
737
+ assert.deepEqual(after.blocks.map((block) => block.name), ["notesoup:boot"]);
738
+ assert.match(after.blocks[0].text, /Current context window id: claude:hook-session:2/);
739
+ }
740
+ else {
741
+ assert.deepEqual(after.blocks, [], "veto, precompute and subagent leave the main boot alone");
742
+ }
743
+ });
744
+ }
745
+ });
746
+ test("Claude serves every registered notes tool to subagents without leaking event fields into params", async (t) => {
747
+ const { invoke } = await retainedFixture(t);
748
+ const call = (tool, params) => invoke("tool.call", {
749
+ tool: `mcp__notesoup__${tool}`, tool_use_id: "child-call", agentId: "child", ...params,
750
+ });
751
+ assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md");
752
+ assert.match((await call("notes_read", { address: "child.md" })).result, /child body/);
753
+ assert.equal((await call("notes_update", { address: "child.md", edits: [{ oldText: "child body", newText: "updated body" }] })).isError, undefined);
754
+ assert.match((await call("notes_list", {})).result, /child\.md/);
755
+ assert.match((await call("notes_search", { query: "updated body" })).result, /child\.md/);
756
+ assert.equal((await call("notes_read", { address: "absent.md" })).isError, true, "refusals retain the error discriminator in subagents");
757
+ });
758
+ test("Claude identity uses the documented current model and cwd, with a safe model fallback", async (t) => {
759
+ const { host, home, invoke } = await retainedFixture(t);
760
+ let model = "Claude Opus 4.6";
761
+ let cwd = home;
762
+ host.session.model = async () => model;
763
+ host.session.cwd = async () => cwd;
764
+ const seen = [];
765
+ const run = host.process.run;
766
+ host.process.run = async (argv, init) => { seen.push(JSON.parse(init.stdin)); return run(argv, init); };
767
+ const write = (address, content) => invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "model-call", address, content });
768
+ assert.equal((await write("@model/model.md", "opus")).result, "created @model/model.md");
769
+ assert.equal(seen.at(-1).identity.model, "claude-opus-4-6");
770
+ assert.ok(readFileSync(join(home, "models/claude-opus-4-6/model.md"), "utf8").includes("opus"));
771
+ model = "Claude Sonnet 4.6";
772
+ cwd = mkdtempSync(join(tmpdir(), "claude-cwd-"));
773
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
774
+ await write("@model/model.md", "sonnet");
775
+ assert.equal(seen.at(-1).identity.model, "claude-sonnet-4-6");
776
+ assert.equal(seen.at(-1).identity.cwd, cwd, "a /cd or worktree move is not frozen at session.start");
777
+ assert.ok(readFileSync(join(home, "models/claude-sonnet-4-6/model.md"), "utf8").includes("sonnet"));
778
+ host.session.model = async () => { throw new Error("model unavailable"); };
779
+ await write("@model/model.md", "fallback");
780
+ assert.equal(seen.at(-1).identity.model, "claude");
781
+ });
782
+ test("Claude session.end cannot be undone by an in-flight old reset", async (t) => {
783
+ const { host, invoke, context } = await retainedFixture(t);
784
+ let prepared;
785
+ const ready = new Promise((resolve) => { prepared = resolve; });
786
+ let release;
787
+ const hold = new Promise((resolve) => { release = resolve; });
788
+ host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
789
+ host.session.compact = async ({ instructions }) => {
790
+ const result = await invoke("session.compact", { trigger: "plugin", instructions });
791
+ prepared();
792
+ await hold;
793
+ return result;
794
+ };
795
+ const finishing = invoke("turn.complete");
796
+ await ready;
797
+ await invoke("session.end", { reason: "clear", sessionId: "hook-session" });
798
+ host.session.id = async () => "after-flight";
799
+ host.session.messages = async () => [];
800
+ host.session.usage = async () => ({ context: {} });
801
+ release();
802
+ await finishing;
803
+ const fresh = await context();
804
+ assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
805
+ assert.match(fresh.blocks[0].text, /Current context window id: claude:after-flight:0/);
806
+ });
@@ -0,0 +1 @@
1
+ export {};