notesoup 0.42.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 (120) 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.js +1 -1
  4. package/dist/src/budget/parse.d.ts +14 -0
  5. package/dist/src/budget/parse.js +36 -0
  6. package/dist/src/budget/policy.js +2 -7
  7. package/dist/src/budget/text.d.ts +2 -0
  8. package/dist/src/budget/text.js +2 -0
  9. package/dist/src/claude/helper.js +1 -2
  10. package/dist/src/claude/thresholds.js +45 -66
  11. package/dist/src/dream/lock.js +6 -13
  12. package/dist/src/dream/report.js +5 -15
  13. package/dist/src/history/history.js +4 -2
  14. package/dist/src/history/query.js +10 -22
  15. package/dist/src/notes/address.d.ts +0 -1
  16. package/dist/src/notes/address.js +5 -17
  17. package/dist/src/notes/errors.d.ts +2 -0
  18. package/dist/src/notes/errors.js +5 -0
  19. package/dist/src/notes/frontmatter.js +16 -2
  20. package/dist/src/notes/identity.js +0 -3
  21. package/dist/src/notes/paths.d.ts +11 -1
  22. package/dist/src/notes/paths.js +28 -7
  23. package/dist/src/notes/store.d.ts +1 -0
  24. package/dist/src/notes/store.js +38 -37
  25. package/dist/src/pi/boot.js +1 -5
  26. package/dist/src/pi/budget.d.ts +3 -3
  27. package/dist/src/pi/budget.js +11 -11
  28. package/dist/src/pi/dream/cli.js +43 -11
  29. package/dist/src/pi/estimate.d.ts +1 -5
  30. package/dist/src/pi/estimate.js +4 -4
  31. package/dist/src/pi/history.js +1 -4
  32. package/dist/src/pi/notes/adapter.d.ts +1 -1
  33. package/dist/src/pi/notes/adapter.js +2 -2
  34. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  35. package/dist/src/pi/reset/artifacts.js +4 -4
  36. package/dist/src/pi/reset/committed.js +2 -2
  37. package/dist/src/pi/runtime.js +8 -5
  38. package/dist/src/pi/thresholds.js +5 -9
  39. package/dist/src/pi/tool-result.d.ts +1 -4
  40. package/dist/src/pi/tool-result.js +1 -1
  41. package/dist/src/pi/window.d.ts +5 -0
  42. package/dist/src/pi/window.js +7 -0
  43. package/dist/src/settings.d.ts +2 -0
  44. package/dist/src/settings.js +4 -3
  45. package/dist/src/tools/history.js +4 -7
  46. package/dist/src/tools/notes.d.ts +0 -4
  47. package/dist/src/tools/notes.js +6 -16
  48. package/dist/src/tools/output.d.ts +0 -3
  49. package/dist/src/tools/output.js +1 -9
  50. package/dist/src/tools/result.d.ts +1 -0
  51. package/dist/src/tools/result.js +14 -20
  52. package/dist/src/tools/schema.d.ts +0 -1
  53. package/dist/src/tools/schema.js +0 -1
  54. package/dist/test/agent-loop.test.js +1 -2
  55. package/dist/test/boot.integration.test.js +1 -1
  56. package/dist/test/claude-mod.test.js +221 -9
  57. package/dist/test/claude-validation.test.d.ts +1 -0
  58. package/dist/test/claude-validation.test.js +73 -0
  59. package/dist/test/dream-skill.test.js +2 -4
  60. package/dist/test/dream.test.js +14 -0
  61. package/dist/test/helpers/extension.js +1 -1
  62. package/dist/test/history.integration.test.js +2 -1
  63. package/dist/test/host-neutral.test.js +15 -0
  64. package/dist/test/notes-library.test.js +30 -1
  65. package/dist/test/notes.integration.test.js +7 -7
  66. package/dist/test/notes.test.js +24 -5
  67. package/dist/test/reset-lifecycle.test.js +1 -1
  68. package/docs/claude-code-mod.md +5 -3
  69. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  70. package/mods/notesoup/dist/claude/helper.js +147 -173
  71. package/mods/notesoup/hooks/register.ts +158 -67
  72. package/mods/notesoup/playbook.md +1 -1
  73. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  74. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  75. package/package.json +5 -3
  76. package/playbook.md +1 -1
  77. package/skills/dream/SKILL.md +1 -1
  78. package/skills/memory/SKILL.md +1 -1
  79. package/src/boot/render.ts +11 -21
  80. package/src/boot/snapshot.ts +2 -7
  81. package/src/boot/text.ts +1 -1
  82. package/src/budget/parse.ts +39 -0
  83. package/src/budget/policy.ts +2 -6
  84. package/src/budget/text.ts +3 -0
  85. package/src/claude/helper.ts +2 -2
  86. package/src/claude/thresholds.ts +45 -62
  87. package/src/dream/lock.ts +3 -9
  88. package/src/dream/report.ts +5 -10
  89. package/src/history/history.ts +4 -2
  90. package/src/history/query.ts +10 -23
  91. package/src/notes/address.ts +4 -16
  92. package/src/notes/errors.ts +6 -0
  93. package/src/notes/frontmatter.ts +12 -2
  94. package/src/notes/identity.ts +0 -2
  95. package/src/notes/paths.ts +23 -5
  96. package/src/notes/store.ts +33 -36
  97. package/src/pi/boot.ts +1 -13
  98. package/src/pi/budget.ts +10 -11
  99. package/src/pi/dream/cli.ts +35 -10
  100. package/src/pi/estimate.ts +4 -4
  101. package/src/pi/history.ts +1 -5
  102. package/src/pi/notes/adapter.ts +2 -2
  103. package/src/pi/reset/artifacts.ts +4 -4
  104. package/src/pi/reset/committed.ts +2 -2
  105. package/src/pi/runtime.ts +7 -6
  106. package/src/pi/thresholds.ts +5 -11
  107. package/src/pi/tool-result.ts +1 -1
  108. package/src/pi/window.ts +8 -0
  109. package/src/settings.ts +4 -3
  110. package/src/tools/history.ts +4 -8
  111. package/src/tools/notes.ts +7 -20
  112. package/src/tools/output.ts +1 -12
  113. package/src/tools/result.ts +14 -19
  114. package/src/tools/schema.ts +0 -1
  115. package/dist/src/dream/playbook.d.ts +0 -1
  116. package/dist/src/dream/playbook.js +0 -2
  117. package/dist/src/pi/reset/text.d.ts +0 -4
  118. package/dist/src/pi/reset/text.js +0 -7
  119. package/src/dream/playbook.ts +0 -3
  120. package/src/pi/reset/text.ts +0 -9
@@ -10,7 +10,7 @@ import { dispatch, handleLine } from "../src/claude/helper.js";
10
10
  import { DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, resolveClaudeLimits } from "../src/claude/thresholds.js";
11
11
  import { WARNING_RUNWAY_TOKENS } from "../src/budget/constants.js";
12
12
  import { PROTOCOL_WIPE_SENTENCE, CLAUDE_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js";
13
- import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../src/pi/reset/text.js";
13
+ import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../src/budget/text.js";
14
14
  const identity = { home: mkdtempSync(join(tmpdir(), "claude-mod-")), sessionId: "session", cwd: process.cwd(), agent: "claude", model: "claude" };
15
15
  async function callTool(tool, params) {
16
16
  return await dispatch({ op: "tool", tool, identity, params });
@@ -42,12 +42,13 @@ function fakeEngine(home) {
42
42
  notifications,
43
43
  host: {
44
44
  env: { get: async (name) => name === "PI_NOTES_HOME" ? home : undefined },
45
- 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 () => ({}) },
46
47
  command: { register: async (spec) => ({ command: spec.name }) },
47
48
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
48
49
  prompt: { submit: async () => undefined },
49
50
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
50
- 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); } },
51
52
  process: { run: async (argv, init) => ({
52
53
  exitCode: 0,
53
54
  stdout: execFileSync(argv[0], argv.slice(1), { cwd: init?.cwd, input: init?.stdin, encoding: "utf8" }),
@@ -157,7 +158,14 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
157
158
  assert.equal(percent.unit, "percent");
158
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");
159
160
  assert.equal(limitPoints({ env: { pctOverride: "50" } }).native, 50);
160
- assert.equal(limitPoints({ usage: { window: 8_000 } }).unit, "percent", "a window too small for the reserve degrades to percent");
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");
161
169
  });
162
170
  test("Claude limits read margins from the notesoup settings shape and ignore garbage", () => {
163
171
  const base = { usage: { window: 200_000 }, breakdown: { autoCompactThreshold: 167_000, isAutoCompactEnabled: true } };
@@ -252,7 +260,7 @@ test("Claude Mod appends boot once and reuses persisted blocks after re-registra
252
260
  assert.deepEqual(notifications, [], "successful boot never notifies");
253
261
  });
254
262
  test("Claude Mod boot failure preserves fallback with available, absent, or failing notifications", async (t) => {
255
- for (const mode of ["available", "no ui", "no notify", "throws", "rejects"]) {
263
+ for (const mode of ["available", "no ui", "no toast", "throws", "rejects"]) {
256
264
  await t.test(mode, async (t) => {
257
265
  const hooks = await loadHookModule(t);
258
266
  const home = mkdtempSync(join(tmpdir(), "claude-hook-home-"));
@@ -260,10 +268,10 @@ test("Claude Mod boot failure preserves fallback with available, absent, or fail
260
268
  const { host, notifications } = fakeEngine(home);
261
269
  if (mode === "no ui")
262
270
  delete host.ui;
263
- else if (mode === "no notify")
271
+ else if (mode === "no toast")
264
272
  host.ui = {};
265
273
  else if (mode === "throws" || mode === "rejects") {
266
- host.ui = { notify: (text) => {
274
+ host.ui = { toast: (text) => {
267
275
  notifications.push(text);
268
276
  if (mode === "throws")
269
277
  throw new Error("notification unavailable");
@@ -291,7 +299,7 @@ test("Claude Mod boot failure preserves fallback with available, absent, or fail
291
299
  ...upstream,
292
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." }],
293
301
  }, "boot failure keeps the original fallback and upstream fields even if notify is absent or fails");
294
- 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"];
295
303
  assert.deepEqual(notifications, expectedNotifications, "one user-facing notification reports the notes boot failure");
296
304
  assert.equal(bootRequests, 1);
297
305
  assert.equal(nextCalls, 1);
@@ -585,10 +593,214 @@ test("Claude Mod skips the automatic reset when thresholds cannot be resolved",
585
593
  assert.equal(compactions, 0, "an unresolvable point never resets");
586
594
  assert.equal(notifications.filter((text) => text.includes("Context thresholds unavailable")).length, 1, "one line, not one per turn");
587
595
  });
588
- test("Claude dream skill projection stays byte-identical to canonical shared files", () => {
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")));
589
598
  assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md")), readFileSync(join(process.cwd(), "skills/dream/SKILL.md")));
590
599
  assert.deepEqual(readFileSync(join(process.cwd(), "mods/notesoup/playbook.md")), readFileSync(join(process.cwd(), "playbook.md")));
591
600
  const skill = readFileSync(join(process.cwd(), "mods/notesoup/skills/dream/SKILL.md"), "utf8");
592
601
  assert.match(skill, /\.\.\/\.\.\/playbook\.md/);
593
602
  assert.doesNotMatch(skill, /Claude.*runner|dream runner/i);
594
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 {};
@@ -0,0 +1,73 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import test from "node:test";
7
+ const plugin = join(process.cwd(), "mods/notesoup");
8
+ /** Only an absent executable may skip the real loader gate; other failures fail the suite. */
9
+ function validate(t, dir) {
10
+ const result = spawnSync("claude", ["plugin", "validate", dir, "--strict", "--json"], {
11
+ encoding: "utf8", timeout: 30_000,
12
+ });
13
+ if (result.error?.code === "ENOENT") {
14
+ t.skip("Claude mod validation skipped: claude is not installed (not found on PATH)");
15
+ return undefined;
16
+ }
17
+ assert.ifError(result.error);
18
+ assert.equal(result.signal, null, result.stderr);
19
+ const report = JSON.parse(result.stdout);
20
+ return { ...result, report };
21
+ }
22
+ test("Claude mod passes the installed engine's strict loader validation", (t) => {
23
+ const result = validate(t, plugin);
24
+ if (!result)
25
+ return;
26
+ assert.equal(result.status, 0, result.stdout + result.stderr);
27
+ assert.equal(result.report.success, true, result.stdout);
28
+ t.diagnostic("claude plugin validate mods/notesoup --strict: passed");
29
+ });
30
+ test("Claude mod typechecks against the vendored engine contract without Node globals", () => {
31
+ const result = spawnSync(process.execPath, ["node_modules/typescript/bin/tsc", "-p", "mods/notesoup/tsconfig.json"], {
32
+ encoding: "utf8", timeout: 30_000,
33
+ });
34
+ assert.ifError(result.error);
35
+ assert.equal(result.status, 0, result.stdout + result.stderr);
36
+ });
37
+ // Test each original ScanRefusal independently against the real scanner. A regression must
38
+ // fail the gate rather than silently transpile in our fake engine's lifecycle tests.
39
+ for (const mutation of [
40
+ {
41
+ name: "variable environment names",
42
+ from: 'return await $.env.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE")',
43
+ to: 'const name = "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE"; return await $.env.get(name)',
44
+ },
45
+ {
46
+ name: "bound session usage ops",
47
+ from: "const context = (await $.session.usage()).context",
48
+ to: "const read = $.session.usage; const context = (await read()).context",
49
+ },
50
+ {
51
+ name: "bound settings nouns",
52
+ from: "return await $.settings.read()",
53
+ to: "const settings = $.settings; return await settings.read()",
54
+ },
55
+ ]) {
56
+ test(`Claude loader gate rejects ${mutation.name}`, (t) => {
57
+ const fixture = mkdtempSync(join(tmpdir(), "claude-scanner-gate-"));
58
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
59
+ const dir = join(fixture, "notesoup");
60
+ cpSync(plugin, dir, { recursive: true });
61
+ const source = join(dir, "hooks/register.ts");
62
+ const text = readFileSync(source, "utf8");
63
+ assert.equal(text.split(mutation.from).length, 2, "one scanner-safe call site is mutated");
64
+ writeFileSync(source, text.replace(mutation.from, mutation.to));
65
+ const result = validate(t, dir);
66
+ if (!result)
67
+ return;
68
+ assert.notEqual(result.status, 0, "the strict gate must fail a loader refusal");
69
+ assert.equal(result.report.success, false);
70
+ // This build emits a null error code for ScanRefusal, so use the module error path.
71
+ assert.ok(result.report.contents.some((entry) => entry.errors.some((error) => error.path === "modules../register.ts")), result.stdout);
72
+ });
73
+ }
@@ -6,7 +6,6 @@ import { tmpdir } from "node:os";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { loadSkillsFromDir } from "@earendil-works/pi-coding-agent";
9
- import { loadPlaybook } from "../src/dream/playbook.js";
10
9
  function packageRoot() {
11
10
  let dir = dirname(fileURLToPath(import.meta.url));
12
11
  while (!existsSync(join(dir, "package.json"))) {
@@ -38,7 +37,7 @@ test("dream skill is publicly discoverable and resolves the CLI's shared playboo
38
37
  const packagePlaybook = resolve(root, "playbook.md");
39
38
  assert.equal(skillPlaybook, packagePlaybook);
40
39
  const playbook = readFileSync(packagePlaybook, "utf8");
41
- assert.equal(loadPlaybook(skillPlaybook), playbook);
40
+ assert.equal(readFileSync(skillPlaybook, "utf8"), playbook);
42
41
  });
43
42
  test("npm tarball keeps the skill's relative playbook path portable after extraction", () => {
44
43
  const root = packageRoot();
@@ -63,8 +62,7 @@ test("npm tarball keeps the skill's relative playbook path portable after extrac
63
62
  const installedSkill = discoverSkill(join(installedRoot, "skills"), "dream");
64
63
  const referencedPlaybook = resolve(installedSkill.baseDir, "../../playbook.md");
65
64
  assert.equal(referencedPlaybook, resolve(installedRoot, "playbook.md"));
66
- assert.equal(loadPlaybook(referencedPlaybook), readFileSync(referencedPlaybook, "utf8"));
67
- assert.equal(loadPlaybook(referencedPlaybook), readFileSync(join(root, "playbook.md"), "utf8"));
65
+ assert.equal(readFileSync(referencedPlaybook, "utf8"), readFileSync(join(root, "playbook.md"), "utf8"));
68
66
  }
69
67
  finally {
70
68
  rmSync(fixture, { recursive: true, force: true });
@@ -134,3 +134,17 @@ test("CLI commits partial writes when report writing fails", async () => {
134
134
  assert.match(execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim(), /\(failed\)/);
135
135
  assert.equal(execFileSync("git", ["show", "HEAD:global/partial.md"], { cwd: home, encoding: "utf8" }), "half");
136
136
  });
137
+ test("CLI refuses a malformed flag value before creating anything", async () => {
138
+ const numberHome = join(fixture(), "notes");
139
+ const badNumber = await captureErrors(() => main(["--notes-home", numberHome, "--min-hours", "abc"], { dreamerSettings: () => ({ warnings: [] }) }));
140
+ assert.equal(badNumber.code, 1);
141
+ assert.ok(badNumber.errors.some((line) => /--min-hours needs a positive whole number/.test(line)), badNumber.errors.join("\n"));
142
+ assert.equal(existsSync(numberHome), false, "a bad number is refused before the home is created");
143
+ for (const value of ["", "--force"]) {
144
+ const home = join(fixture(), "notes");
145
+ const badHome = await captureErrors(() => main(["--notes-home", value], { dreamerSettings: () => ({ warnings: [] }) }));
146
+ assert.equal(badHome.code, 1, `--notes-home ${JSON.stringify(value)} is refused`);
147
+ assert.ok(badHome.errors.some((line) => /--notes-home needs a directory path/.test(line)), badHome.errors.join("\n"));
148
+ assert.equal(existsSync(home), false, "a flag-looking path never becomes the home");
149
+ }
150
+ });
@@ -136,7 +136,7 @@ export function makeExtension(sessionManager, settingsManager) {
136
136
  export async function explicitBoot(ctx, currentWindowId, previousWindowId) {
137
137
  return renderBootBlock({
138
138
  tools: PI_TOOL_NAMES,
139
- agentName: agentSlug(ctx),
139
+ agentName: agentSlug(),
140
140
  modelName: modelSlug(ctx),
141
141
  firstWindowId: rootWindowId(ctx.sessionManager.getSessionId()),
142
142
  currentWindowId,
@@ -1,7 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { Check } from "typebox/value";
4
- import { earliestMatchOffsetChars, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
4
+ import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
5
+ import { earliestMatchOffsetChars } from "../src/text-match.js";
5
6
  import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
6
7
  import { historyDocument, projectHistory } from "../src/history/history.js";
7
8
  import { selectPage } from "../src/history/query.js";
@@ -272,3 +272,18 @@ test("one role schema declares the four public roles for the page item, the read
272
272
  assert.equal(Check(HistoryRoleSchema, "developer"), false, "a role outside the four is refused");
273
273
  assert.equal(Check(historyRead.outputSchema, read("developer")), false, "history_read refuses a role outside the four");
274
274
  });
275
+ test("history paging bounds are the schema's, and a zero limit still pages one event", async () => {
276
+ const items = Array.from({ length: 3 }, (_, index) => ({ seq: index + 1, windowId: "root", role: "user", text: `message-${index}` }));
277
+ const projection = projectHistory([{ windowId: "root", items }], 3, new Set([1, 2, 3]));
278
+ assert.equal(Check(historyList.parameters, { limit: 0 }), false, "the schema refuses a zero limit");
279
+ assert.equal(Check(historyList.parameters, { limit: 501 }), false, "the schema refuses a limit past its maximum");
280
+ assert.equal(Check(historyList.parameters, { max_chars_per_item: 0 }), false, "the schema refuses a zero preview budget");
281
+ const zero = data(await historyList.execute({ limit: 0, from: "oldest", roles: ["user"] }, projection));
282
+ assert.equal(zero.items.length, 1, "an unvalidated zero limit still returns one row instead of none");
283
+ const negative = data(await historyList.execute({ max_chars_per_item: -5, roles: ["user"] }, projection));
284
+ const row = negative.items[0];
285
+ if ("folded" in row)
286
+ assert.fail("a role filter returns event rows only");
287
+ assert.equal(row.content, "", "a negative budget delivers nothing instead of cutting the tail");
288
+ assert.equal(row.truncated, true, "the empty preview says it was truncated");
289
+ });
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import test from "node:test";
@@ -212,3 +212,32 @@ test("a massively ambiguous edit still reports every match line to a library cal
212
212
  });
213
213
  assert.equal((await notes.read("many"))?.body.startsWith("beta\nbeta"), true, "the refused edit left the body alone");
214
214
  });
215
+ test("one unreadable note is named without hiding its readable siblings", async (t) => {
216
+ if (process.getuid?.() === 0 || process.platform === "win32")
217
+ return t.skip("chmod 000 is not a read refusal for this user");
218
+ const { home, notes } = fixture(t);
219
+ await notes.write("@project/bad.md", "bad body");
220
+ await notes.write("@project/good.md", "good body");
221
+ chmodSync(join(home, "project", "project-12345678", "bad.md"), 0o000);
222
+ const result = await notes.listWithStatus({ scope: "project" });
223
+ assert.deepEqual(result.rows.map((row) => row.address), ["@project/good.md"], "the readable sibling still lists");
224
+ assert.deepEqual(result.status.homesUnavailable, ["@project/bad.md"], "the unreadable note is named on its own");
225
+ await assert.rejects(() => notes.list({ scope: "project" }), (error) => error.code === "EACCES", "a caller that asked for no status still sees the failure");
226
+ });
227
+ test("a hand-written quoted numeric extra survives a rewrite as a string", async (t) => {
228
+ const { home, notes } = fixture(t);
229
+ await notes.write("typed", "body");
230
+ const path = join(home, "pi/session/session-a/typed.md");
231
+ writeFileSync(path, readFileSync(path, "utf8").replace("\n---\n\n", "\ncount: \"1\"\n---\n\n"));
232
+ assert.equal((await notes.read("typed"))?.meta.count, "1", "a quoted scalar is read as text");
233
+ const raw = readFileSync(path, "utf8");
234
+ assert.match(raw, /^count: "1"$/m, "a bare 1 would read back as a number");
235
+ assert.match(raw, /^origin: self$/m, "an ordinary string still stays bare");
236
+ });
237
+ test("writing keeps an existing note's origin unless the caller names one", async (t) => {
238
+ const { notes } = fixture(t);
239
+ await notes.write("owned", "first", { origin: "user" });
240
+ assert.equal((await notes.write("owned", "second")).meta.origin, "user", "a rewrite does not re-attribute the note");
241
+ assert.equal((await notes.write("owned", "third", { origin: "external" })).meta.origin, "external", "an explicit origin still wins");
242
+ assert.equal((await notes.write("fresh", "new")).meta.origin, "self", "a new note still defaults to self");
243
+ });
@@ -272,18 +272,18 @@ test("the boot block gives awake agents the notes-home file layout", async () =>
272
272
  assert.equal(rendered.includes(process.env.PI_NOTES_HOME ?? ""), false, "the absolute notes home is never exposed");
273
273
  assert.match(rendered, /`<path>`, no @[\s\S]*`@project\/<path>`[\s\S]*`@human\/<path>`/);
274
274
  });
275
- test("the boot protocol carries the approved copy and cuts an over-cap MAP with the approved notice", async () => {
275
+ test("the boot binds its tools and bounds an over-cap MAP with a lookup pointer", async () => {
276
276
  const session = manager();
277
277
  const captured = makeExtension(session);
278
278
  const ctx = context(session);
279
279
  await call(captured, "notes_write", { address: "MAP.md", content: "M".repeat(MAP_BOOT_MAX_CHARS + 10) }, ctx);
280
280
  const rendered = await explicitBoot(ctx, "pcw:test:root", undefined);
281
- assert.ok(rendered.includes("History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice."), "the History paragraph is the approved copy");
282
- assert.ok(rendered.includes("- `@project/<path>` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say."), "the @project bullet is the approved copy");
283
- assert.ok(rendered.includes("- `<path>`, no @") && rendered.includes("- `@human/<path>`") && rendered.includes("- `@self/<path>`") && rendered.includes("- `@model/<path>`"), "every address bullet is backticked");
284
- assert.ok(rendered.includes("Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like `read`, `write`, `edit`, or `bash`."), "the fake-address paragraph is the approved copy");
285
- assert.ok(rendered.includes(`[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`MAP.md\`]`), "an over-cap MAP is cut with the approved notice");
286
- assert.equal(rendered.includes("MAP cut at"), false, "the retired cut notice is gone");
281
+ for (const tool of ["notes_*", "history_*", "get_context_remaining", "clear_memory"]) {
282
+ assert.ok(rendered.includes(`\`${tool}\``), `${tool} is bound in the protocol`);
283
+ }
284
+ assert.ok(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS)), "the existing MAP cap keeps a bounded prefix");
285
+ assert.equal(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS + 1)), false, "the over-cap suffix is not inlined");
286
+ assert.ok(rendered.includes("`MAP.md`"), "the full MAP remains available by address");
287
287
  for (const retired of ["history_windows", "history_list", "history_read"]) {
288
288
  assert.equal(rendered.includes(retired), false, `${retired} no longer appears in the boot block`);
289
289
  }
@@ -8,12 +8,14 @@
8
8
  */
9
9
  import assert from "node:assert/strict";
10
10
  import { execFileSync } from "node:child_process";
11
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
12
- import { join } from "node:path";
11
+ import { createHash } from "node:crypto";
12
+ import { existsSync, mkdirSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
13
+ import { basename, join } from "node:path";
13
14
  import test from "node:test";
14
15
  import { Check } from "typebox/value";
15
16
  import { parseNote } from "../src/notes/frontmatter.js";
16
17
  import { projectKey } from "../src/notes/paths.js";
18
+ import { globToRegExp } from "../src/notes/address.js";
17
19
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
18
20
  import { call, context, explicitBoot, makeExtension, manager, resultData, resultError, resultRead } from "./helpers/extension.js";
19
21
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
@@ -164,9 +166,8 @@ test("session-note project ownership is per note, persistent across sessions, an
164
166
  });
165
167
  test("linked git worktrees share the main checkout's project key", () => {
166
168
  freshRoot();
167
- // realpath keeps the fixture's gitdir pointer and the asserted paths on one spelling
168
- // (macOS temp roots live under the /var -> /private/var symlink).
169
- const root = realpathSync(testEnvironment.cwd);
169
+ // The fixture root is used as spelled: a symlinked temp root must still hash to one key.
170
+ const root = testEnvironment.cwd;
170
171
  const main = join(root, "repo");
171
172
  mkdirSync(main, { recursive: true });
172
173
  const git = (args) => {
@@ -528,3 +529,21 @@ async function withAgent(name, run) {
528
529
  process.env.PI_NOTES_AGENT = previous;
529
530
  }
530
531
  }
532
+ test("a symlinked checkout hashes the canonical root, so one checkout has one project home", () => {
533
+ const root = realpathSync(testEnvironment.cwd);
534
+ const real = join(root, "real-repo");
535
+ mkdirSync(join(real, ".git"), { recursive: true });
536
+ const linked = join(root, "linked-repo");
537
+ symlinkSync(real, linked);
538
+ // The formula the key is documented to be: basename plus sha1 of the canonical root.
539
+ const canonicalKey = `${basename(real)}-${createHash("sha1").update(real).digest("hex").slice(0, 8)}`;
540
+ assert.equal(projectKey(linked), canonicalKey, "the symlinked spelling hashes the canonical root");
541
+ assert.equal(projectKey(real), canonicalKey, "the canonical spelling hashes the same root");
542
+ assert.notEqual(`${basename(linked)}-${createHash("sha1").update(linked).digest("hex").slice(0, 8)}`, canonicalKey, "a path-spelled key would differ");
543
+ });
544
+ test("a glob ? matches exactly one non-slash character", () => {
545
+ const pattern = globToRegExp("a?.md");
546
+ assert.equal(pattern.test("ab.md"), true, "? matches one ordinary character");
547
+ assert.equal(pattern.test("a.md"), false, "? is not optional");
548
+ assert.equal(pattern.test("a/b.md"), false, "? never matches a path separator");
549
+ });
@@ -8,7 +8,7 @@ import notesoup from "../src/pi/extension.js";
8
8
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
9
9
  import { MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
10
10
  import { toolContext } from "./helpers/extension.js";
11
- import { WARNING_CONTENT } from "../src/pi/reset/text.js";
11
+ import { WARNING_CONTENT } from "../src/budget/text.js";
12
12
  import { initialResetControl, reduceResetControl, registerResetLifecycle, } from "../src/pi/reset/lifecycle.js";
13
13
  const previousNotesHome = process.env.PI_NOTES_HOME;
14
14
  const testNotesHome = mkdtempSync(join(tmpdir(), "notesoup-lifecycle-notes-"));
@@ -4,14 +4,16 @@ The package also ships `mods/notesoup`, an early-access Claude Code Mod that reg
4
4
 
5
5
  In interactive sessions it resets automatically when the measured context reaches notesoup's reset point, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. That point is derived from Claude's own auto-compact threshold instead of a fixed percent, in `src/claude/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
6
6
 
7
- 1. `$.session.usage({breakdown:true}).context.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
7
+ 1. `$.session.usage({breakdown:"summary"}).context.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
8
8
  2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer;
9
9
  3. otherwise the percent fallback, which expresses the same reserves on the classic 200K window.
10
10
 
11
11
  Notesoup resets one `resetMarginTokens` (default 8192) below that point, and warns one `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below the reset. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the automatic reset. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, disables the automatic reset, and makes `/clear-memory` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored.
12
12
 
13
- Once per window, when the measured context crosses the warning point, `prompt.context` adds a `notesoup:warning` block carrying the shared warning text with Claude's closing instruction ("end your turn; the reset runs after it"). The warned flag resets with the window ordinal. Its own `session.compact` hook replaces the conversation with the freshly built notes boot followed by the shared continuation message — the same order and the same words as Pi — not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block tells the model to end its turn and ask the human to run `/clear-memory`, replacing that one sentence through `BootToolNames.wipeSentence`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk.
13
+ Once per window, when the measured context crosses the warning point, `prompt.context` adds a `notesoup:warning` block carrying the shared warning text with Claude's closing instruction ("end your turn; the reset runs after it"). The warned flag resets with the window ordinal. Its own `session.compact` hook replaces the conversation with the freshly built notes boot followed by the shared continuation message — the same order and the same words as Pi — not a generated summary. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block tells the model to end its turn and ask the human to run `/clear-memory`, replacing that one sentence through `BootToolNames.wipeSentence`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. Successful native main-session compaction invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
14
14
 
15
15
  `/clear-memory` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. Claude history tools and a Claude dream backend are not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the reset points and the one warning per window now follow Claude's own configuration.
16
16
 
17
- The plugin also exposes the shared `skills/dream/SKILL.md` and its referenced `playbook.md`; the build synchronizes both projections from the canonical repository files. Validate it from a built checkout with `claude plugin validate mods/notesoup --strict`; the package build and `npm pack --dry-run` include the manifests, hooks module, helper, skill, and playbook.
17
+ The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared memory and dream skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
18
+
19
+ `npm run typecheck` includes the mod against the vendored Claude Code 2.1.295 contract. `npm test` also typechecks it and runs `claude plugin validate mods/notesoup --strict`, skipping validation with a clear message only if `claude` is not installed. Scanner regression tests deliberately reintroduce each of the three forbidden call shapes and require the gate to fail. From a built checkout, check the real load with `claude --plugin-dir mods/notesoup -p "ok"`; a model/API failure after load is separate from a hooks-module refusal. The package build and `npm pack --dry-run` include the manifests, hooks module, helper, skills, and playbook.