notesoup 0.58.1 → 0.58.3

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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/text.d.ts +1 -1
  3. package/dist/src/boot/text.js +5 -4
  4. package/dist/src/notes/policy.d.ts +1 -1
  5. package/dist/src/notes/policy.js +4 -3
  6. package/dist/src/tools/notes.js +1 -1
  7. package/dist/test/agent-loop.test.js +13 -39
  8. package/dist/test/boot.integration.test.js +20 -18
  9. package/dist/test/budget-settings.integration.test.js +18 -13
  10. package/dist/test/claude-history.test.js +1 -2
  11. package/dist/test/claude-mod.test.js +417 -87
  12. package/dist/test/codex-history.test.js +9 -6
  13. package/dist/test/codex-plugin.test.js +4 -8
  14. package/dist/test/dream-skill.test.js +6 -10
  15. package/dist/test/dsh-cli.test.js +2 -3
  16. package/dist/test/dsh.test.js +1 -7
  17. package/dist/test/helpers/extension.js +3 -1
  18. package/dist/test/history-corpus.test.js +2 -3
  19. package/dist/test/history-prefilter.test.js +33 -40
  20. package/dist/test/history-summary-cache.test.js +1 -1
  21. package/dist/test/history.integration.test.js +11 -37
  22. package/dist/test/host-neutral.test.js +2 -2
  23. package/dist/test/marker.test.js +1 -2
  24. package/dist/test/model-facing-text.test.js +20 -187
  25. package/dist/test/note-policy.test.js +40 -22
  26. package/dist/test/notes-library.test.js +2 -2
  27. package/dist/test/notes.integration.test.js +36 -149
  28. package/dist/test/notes.test.js +13 -61
  29. package/dist/test/pi-render.test.js +23 -62
  30. package/dist/test/reset-lifecycle.test.js +4 -9
  31. package/docs/architecture.md +1 -1
  32. package/docs/claude-code-mod.md +15 -3
  33. package/docs/dsh.md +1 -1
  34. package/docs/notes-library.md +1 -1
  35. package/docs/tool-results.md +1 -1
  36. package/package.json +1 -1
  37. package/playbook.md +1 -1
  38. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  39. package/plugins/claude/dist/claude/helper.js +10 -8
  40. package/plugins/claude/hooks/register.ts +198 -130
  41. package/plugins/claude/playbook.md +1 -1
  42. package/plugins/claude/skills/dream/SKILL.md +1 -1
  43. package/plugins/claude/skills/memory/SKILL.md +1 -1
  44. package/plugins/codex/dist/codex/notesoup.js +10 -8
  45. package/skills/dream/SKILL.md +1 -1
  46. package/skills/memory/SKILL.md +1 -1
  47. package/src/boot/text.ts +5 -4
  48. package/src/notes/policy.ts +4 -3
  49. package/src/tools/notes.ts +1 -1
@@ -26,6 +26,27 @@ function turnComplete(overrides = {}) {
26
26
  ...(reason === "refusal" ? { refusal: overrides.refusal ?? { category: null, explanation: null } } : {}),
27
27
  };
28
28
  }
29
+ // Let the unit fixture's pending Promise jobs settle. These tests exercise
30
+ // hooks and failure policy; the installed-host loopback probe covers scheduling.
31
+ const settleHooks = () => new Promise((resolve) => setImmediate(resolve));
32
+ /** Publish the kept rows separately from the compaction hook's proposal. */
33
+ async function keepCompaction(host, handlers, result) {
34
+ if (!result.messages || result.skip !== undefined)
35
+ return result;
36
+ const append = async (door, message) => {
37
+ const uuid = crypto.randomUUID();
38
+ await handlers.get("session.append")(host, { door, message, uuid, origin: { kind: "plugin", name: "notesoup" } }, async () => ({ uuid, message }));
39
+ };
40
+ await append("compaction", { type: "system", name: "compact_boundary", content: [] });
41
+ for (const message of result.messages)
42
+ await append("prompt", { type: message.role, role: message.role, content: [{ type: "text", text: message.text }] });
43
+ host.session.messages = async () => result.messages;
44
+ return result;
45
+ }
46
+ async function nativeCompaction(host, handlers, instructions) {
47
+ const result = await handlers.get("session.compact")(host, { trigger: "manual", instructions }, async () => ({ skip: "unexpected native summary" }));
48
+ return keepCompaction(host, handlers, result);
49
+ }
29
50
  async function callTool(tool, params) {
30
51
  return await dispatch({ op: "tool", tool, identity, params });
31
52
  }
@@ -476,12 +497,12 @@ test("Claude Mod boot failure preserves fallback with available, absent, or fail
476
497
  ...upstream,
477
498
  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." }],
478
499
  }, "boot failure keeps the original fallback and upstream fields even if notify is absent or fails");
479
- const expectedNotifications = mode === "no ui" || mode === "no toast" ? [] : ["🥣 Notes went missing"];
480
- assert.deepEqual(notifications, expectedNotifications, "one user-facing notification reports the notes boot failure");
500
+ const expectedNotifications = mode === "no ui" || mode === "no toast" ? 0 : 1;
501
+ assert.equal(notifications.length, expectedNotifications, "one user-facing notification reports the notes boot failure");
481
502
  assert.equal(bootRequests, 1);
482
503
  assert.equal(nextCalls, 1);
483
504
  assert.deepEqual(await promptContext(structuredClone(failed)), failed);
484
- assert.deepEqual(notifications, expectedNotifications, "a persisted fallback does not notify again");
505
+ assert.equal(notifications.length, expectedNotifications, "a persisted fallback does not notify again");
485
506
  assert.equal(bootRequests, 1, "a persisted fallback needs no second boot request");
486
507
  assert.equal(nextCalls, 2, "the upstream chain still runs exactly once per prompt");
487
508
  });
@@ -501,9 +522,25 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
501
522
  assert.ok(spec.description.length > 20);
502
523
  assert.equal(spec.inputSchema.type, "object");
503
524
  }
525
+ const wipeSchema = registered[0].inputSchema;
526
+ assert.deepEqual(Object.keys(wipeSchema.properties), ["last_word", "terminate"]);
527
+ assert.equal(wipeSchema.properties.last_word.type, "string");
528
+ assert.equal(wipeSchema.properties.terminate.type, "boolean");
529
+ assert.equal(wipeSchema.properties.terminate.default, false);
530
+ assert.equal(wipeSchema.required, undefined, "both arguments are optional");
531
+ assert.equal(wipeSchema.additionalProperties, false);
504
532
  const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "hook-1", ...params }, async (event) => event);
533
+ let helperText;
534
+ const run = host.process.run;
535
+ host.process.run = async (argv, init) => {
536
+ const response = await run(argv, init);
537
+ if (JSON.parse(init.stdin).op === "tool")
538
+ helperText = JSON.parse(response.stdout).result.text;
539
+ return response;
540
+ };
505
541
  const written = await call("notes_write", { address: "hook.md", content: "hook body" });
506
- assert.equal(written.result, "created hook.md | pinned false | budget 2048 | readonly false", "the hook hands back the shared text unchanged");
542
+ assert.equal(typeof helperText, "string");
543
+ assert.equal(written.result, helperText, "the hook hands back the shared text unchanged");
507
544
  assert.equal("isError" in written, false, "a success carries no discriminator at all, not a false one");
508
545
  const refused = await call("notes_read", { address: "absent.md" });
509
546
  assert.equal(refused.isError, true, "a refusal carries the literal the public ToolCallResult declares");
@@ -533,12 +570,12 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
533
570
  let kept = [];
534
571
  const measured = () => ({ context: { tokens, window: 200_000, percent: tokens === undefined ? undefined : (tokens / 200_000) * 100 } });
535
572
  host.session.usage = async () => measured();
536
- host.session.compact = async ({ instructions }) => {
573
+ host.command.run = async ({ args }) => {
537
574
  compactions++;
538
- const result = await invoke("session.compact", { trigger: "plugin", instructions: `${instructions} (rewritten upstream)`, messages: [{ role: "user", text: "OLD_SECRET" }] });
575
+ const result = await nativeCompaction(host, handlers, args);
539
576
  kept = result.messages;
540
577
  tokens = undefined; // The real engine invalidates token usage after compact.
541
- return result;
578
+ return {};
542
579
  };
543
580
  await invoke("session.start", { cwd: home, isInteractive: true });
544
581
  assert.equal(registered.length, 8);
@@ -570,6 +607,7 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
570
607
  await invoke("turn.start");
571
608
  await invoke("command.run", { command: "empty" });
572
609
  await invoke("turn.complete", turnComplete());
610
+ await settleHooks();
573
611
  assert.equal(compactions, 1);
574
612
  assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
575
613
  assert.equal(kept[0].role, "user");
@@ -592,15 +630,17 @@ test("Claude Mod preserves context and cancels a queued reset after an unsuccess
592
630
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
593
631
  const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
594
632
  let compactions = 0;
595
- host.session.compact = async () => { compactions++; return { skip: "reset must not run" }; };
633
+ host.command.run = async () => { compactions++; return { text: "reset must not run" }; };
596
634
  await invoke("session.start", { cwd: home, isInteractive: true });
597
635
  await invoke("turn.start");
598
636
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: `reset-${reason}`, last_word: "DO_NOT_KEEP" });
599
637
  await invoke("turn.complete", turnComplete({ reason }));
638
+ await settleHooks();
600
639
  assert.equal(compactions, 0, `${reason} never submits the queued reset`);
601
640
  assert.ok(notifications.some(text => text.includes("cancelled") && text.includes(reason)), `${reason} reports that its request was cancelled`);
602
641
  await invoke("turn.start");
603
642
  await invoke("turn.complete", turnComplete());
643
+ await settleHooks();
604
644
  assert.equal(compactions, 0, `${reason} leaves no pending reset for a later successful turn`);
605
645
  });
606
646
  }
@@ -629,31 +669,34 @@ test("Claude headless resets through its own manual command, retries failure and
629
669
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
630
670
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", last_word: "STICKY", tool_use_id: "reset" });
631
671
  await invoke("turn.complete", turnComplete());
672
+ await settleHooks();
632
673
  assert.equal(attempts, 1);
633
674
  assert.ok(notifications.some(x => x.includes("command unavailable")));
634
675
  reject = false;
635
676
  await invoke("turn.complete", turnComplete());
677
+ await settleHooks();
636
678
  assert.equal(attempts, 2, "failed requests remain pending");
637
679
  assert.ok(notifications.some(x => x.includes("Brain not emptied")));
638
- // Core dispatches the admitted manual event within our command hook.
639
- host.command.run = async ({ command }) => {
680
+ // The host skips our command hook; the exact one-use instructions admit it.
681
+ host.command.run = async ({ command, args }) => {
640
682
  attempts++;
641
- const user = await handlers.get("command.run")(host, { command, origin: { kind: "user" } }, async () => invoke("session.compact", { trigger: "manual" }));
683
+ assert.equal(command, "compact");
684
+ const user = await invoke("session.compact", { trigger: "manual", instructions: "unrelated user instructions" });
642
685
  assert.match(JSON.stringify(user), /use \/fresh-window/, "a pending reset does not admit the user's command");
643
- await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
644
- kept = (await invoke("session.compact", { trigger: "manual" })).messages;
645
- return {};
646
- });
686
+ kept = (await nativeCompaction(host, handlers, args)).messages;
647
687
  return {};
648
688
  };
649
689
  await invoke("turn.complete", turnComplete());
690
+ await settleHooks();
650
691
  assert.match(kept[0].text, /claude:hook-session:1/);
651
692
  assert.equal(kept[2].text, "*You peel a sticky note off your forehead.*\nSTICKY");
652
693
  await invoke("turn.complete", turnComplete());
694
+ await settleHooks();
653
695
  assert.equal(attempts, 3, "success clears pending exactly once");
654
696
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
655
697
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "reset2" });
656
698
  await invoke("turn.complete", turnComplete());
699
+ await settleHooks();
657
700
  assert.match(kept[0].text, /claude:hook-session:2/);
658
701
  assert.equal(kept.length, 2, "sticky is consumed once");
659
702
  });
@@ -666,18 +709,13 @@ test("Claude headless warns without proactive resets and supports both manual al
666
709
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
667
710
  let tokens = CLAUDE_200K.warn;
668
711
  let attempts = 0, prompts = 0;
669
- const timers = [];
670
712
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
671
- host.clock.after = (_ms, callback) => { timers.push(callback); };
672
713
  host.prompt.submit = async ({ text }) => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); return { text }; };
673
- host.command.run = async ({ command }) => {
714
+ host.command.run = async ({ args }) => {
674
715
  attempts++;
675
- await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
676
- const result = await invoke("session.compact", { trigger: "manual" });
677
- assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
678
- tokens = undefined;
679
- return {};
680
- });
716
+ const result = await nativeCompaction(host, handlers, args);
717
+ assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
718
+ tokens = undefined;
681
719
  return {};
682
720
  };
683
721
  await invoke("session.start", { cwd: home, isInteractive: false });
@@ -690,14 +728,14 @@ test("Claude headless warns without proactive resets and supports both manual al
690
728
  assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
691
729
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
692
730
  await invoke("turn.complete", turnComplete());
731
+ await settleHooks();
693
732
  assert.equal(attempts, 1);
694
733
  for (const command of ["empty", "fresh-window"]) {
695
734
  assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
696
- await Promise.resolve();
697
- await timers.shift()();
735
+ await settleHooks();
698
736
  }
699
737
  assert.equal(attempts, 3);
700
- assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
738
+ assert.equal(prompts, 3, "one tool continuation and one close-out for each idle alias");
701
739
  });
702
740
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
703
741
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -735,15 +773,20 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
735
773
  };
736
774
  host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
737
775
  let result = {};
738
- host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
776
+ host.command.run = async ({ args }) => {
777
+ result = await nativeCompaction(host, handlers, args);
778
+ return result.skip ? { text: result.skip } : {};
779
+ };
739
780
  await invoke("turn.start");
740
781
  await invoke("command.run", { command: "empty" });
741
782
  await invoke("turn.complete", turnComplete());
783
+ await settleHooks();
742
784
  assert.match(result.skip, /notes didn't load/);
743
785
  assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
744
786
  failBoot = false;
745
787
  await invoke("turn.start");
746
788
  await invoke("turn.complete", turnComplete());
789
+ await settleHooks();
747
790
  assert.equal(result.skip, undefined);
748
791
  assert.equal(result.messages.length, 2);
749
792
  assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
@@ -757,20 +800,18 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
757
800
  host.command.register = async (spec) => { commands.push(spec.name); return { command: spec.name }; };
758
801
  let handlers = new Map();
759
802
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
760
- const timers = [];
761
803
  const prompts = [];
762
804
  let kept = [];
763
805
  let compactions = 0;
764
- host.clock.after = (_ms, callback) => { timers.push(callback); };
765
- host.session.compact = async ({ instructions }) => {
806
+ host.command.run = async ({ args }) => {
766
807
  compactions++;
767
- const result = await invoke("session.compact", { trigger: "plugin", instructions });
768
- kept = result.messages;
769
- return result;
808
+ kept = (await nativeCompaction(host, handlers, args)).messages;
809
+ return {};
770
810
  };
771
811
  host.prompt.submit = async ({ text }) => {
772
812
  prompts.push(text);
773
- await invoke("turn.start");
813
+ await invoke("turn.start", { turnId: "closeout" });
814
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "closeout-reset", terminate: false });
774
815
  await invoke("turn.complete", turnComplete());
775
816
  return { text };
776
817
  };
@@ -778,19 +819,16 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
778
819
  await invoke("session.start", { cwd: home, isInteractive: true });
779
820
  assert.deepEqual(commands.sort(), ["empty", "fresh-window"], "only the new short name and the retained alias are registered");
780
821
  assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
781
- assert.equal(timers.length, 0);
822
+ assert.equal(compactions, 0);
782
823
  const command = await invoke("command.run", { command: "empty" });
783
824
  assert.equal(command.text, "🥣 Dumping Brain");
784
- await Promise.resolve();
785
- assert.equal(compactions, 0, "command.run must not call compact under its held turn");
786
- assert.equal(timers.length, 1);
787
- await timers.shift()();
825
+ await settleHooks();
788
826
  assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
789
827
  assert.equal(prompts[0], CLAUDE_WARNING_PROMPT, "the close-out is the same warning text the automatic path shows");
790
828
  assert.equal(compactions, 1);
791
829
  assert.equal(kept.length, 2);
792
830
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
793
- assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text));
831
+ assert.ok(NORMAL_CONTINUATIONS.includes(kept[1].text), "the close-out called the tool, while the command still keeps STOP policy");
794
832
  host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
795
833
  handlers = new Map();
796
834
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
@@ -799,6 +837,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
799
837
  await invoke("turn.start");
800
838
  await invoke("command.run", { command: "empty" });
801
839
  await invoke("turn.complete", turnComplete());
840
+ await settleHooks();
802
841
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
803
842
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
804
843
  });
@@ -815,8 +854,6 @@ test("Claude failed close-outs release the request so manual reset can retry", a
815
854
  const handlers = new Map();
816
855
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
817
856
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
818
- const timers = [];
819
- host.clock.after = (_ms, callback) => { timers.push(callback); };
820
857
  host.prompt.submit = async ({ text }) => {
821
858
  if (failing && failure === "submit")
822
859
  throw new Error("submission unavailable");
@@ -826,14 +863,14 @@ test("Claude failed close-outs release the request so manual reset can retry", a
826
863
  await invoke("turn.complete", turnComplete());
827
864
  return { text };
828
865
  };
829
- host.session.compact = async ({ instructions }) => {
866
+ host.command.run = async ({ args }) => {
830
867
  resets++;
831
- return await invoke("session.compact", { trigger: "plugin", instructions });
868
+ await nativeCompaction(host, handlers, args);
869
+ return {};
832
870
  };
833
871
  await invoke("session.start", { isInteractive: true });
834
872
  await invoke("command.run", { command: "fresh-window" });
835
- await Promise.resolve();
836
- await timers.shift()();
873
+ await settleHooks();
837
874
  assert.equal(resets, 0);
838
875
  assert.ok(notifications.some(text => text.includes("close-out")), "failure is visible");
839
876
  await invoke("turn.start");
@@ -841,9 +878,7 @@ test("Claude failed close-outs release the request so manual reset can retry", a
841
878
  assert.equal(resets, 0, "a failed close-out must not spring a reset on an unrelated turn");
842
879
  failing = false;
843
880
  assert.deepEqual(await invoke("command.run", { command: "fresh-window" }), { text: "🥣 Dumping Brain" });
844
- await Promise.resolve();
845
- assert.equal(timers.length, 1, "retry schedules new work instead of claiming it is already running");
846
- await timers.shift()();
881
+ await settleHooks();
847
882
  assert.equal(resets, 1);
848
883
  });
849
884
  });
@@ -894,13 +929,14 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
894
929
  return run(argv, init);
895
930
  };
896
931
  let resets = 0;
897
- host.session.compact = async () => { resets++; return {}; };
932
+ host.command.run = async () => { resets++; return {}; };
898
933
  const submit = () => invoke("prompt.submit", { text: "continue" }, {}, async (e) => e);
899
934
  assert.equal((await submit()).context, undefined);
900
935
  tokens++;
901
936
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
902
937
  assert.equal((await submit()).context, undefined, "one warning per window");
903
938
  await invoke("turn.complete", turnComplete());
939
+ await settleHooks();
904
940
  assert.equal(resets, 0, "warning and turn completion never proactively clear");
905
941
  assert.equal((await invoke("session.compact", { trigger: "auto" })).messages.length, 2);
906
942
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
@@ -982,7 +1018,7 @@ test("Claude Mod keeps warning timing when auto-compact is off without clearing
982
1018
  let tokens = 155_423;
983
1019
  let compactions = 0;
984
1020
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
985
- host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
1021
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
986
1022
  await invoke("session.start", { cwd: home, isInteractive: true });
987
1023
  await invoke("turn.start");
988
1024
  await invoke("turn.complete", turnComplete());
@@ -1002,14 +1038,14 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
1002
1038
  t.after(() => rmSync(home, { recursive: true, force: true }));
1003
1039
  const { host, notifications } = fakeEngine(home);
1004
1040
  host.env = { get: async (name) => name === "NOTESOUP_HOME" ? home : name === "DISABLE_COMPACT" ? "1" : undefined };
1005
- const timers = [];
1006
- host.clock.after = (_ms, callback) => { timers.push(callback); };
1041
+ let prompts = 0;
1042
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1007
1043
  const handlers = new Map();
1008
1044
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1009
1045
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1010
1046
  let compactions = 0;
1011
1047
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1012
- host.session.compact = async () => { compactions++; return {}; };
1048
+ host.command.run = async () => { compactions++; return {}; };
1013
1049
  await invoke("session.start", { cwd: home, isInteractive: true });
1014
1050
  assert.equal(notifications.length, 1, "one startup line");
1015
1051
  assert.match(notifications[0], /DISABLE_COMPACT/);
@@ -1018,9 +1054,10 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
1018
1054
  const tool = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "disabled-compact" });
1019
1055
  assert.equal(tool.isError, true);
1020
1056
  assert.match(tool.result, /DISABLE_COMPACT/);
1021
- assert.equal(timers.length, 0, "no close-out turn is queued");
1022
1057
  await invoke("turn.start");
1023
1058
  await invoke("turn.complete", turnComplete());
1059
+ await settleHooks();
1060
+ assert.equal(prompts, 0, "no close-out turn is queued");
1024
1061
  assert.equal(compactions, 0, "disabled reset requests never run");
1025
1062
  assert.equal(notifications.length, 1, "detection logs once, not per turn");
1026
1063
  const upstream = { result: "upstream", context: ["other plugin"] };
@@ -1036,10 +1073,11 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
1036
1073
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1037
1074
  let compactions = 0;
1038
1075
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1039
- host.session.compact = async () => { compactions++; return {}; };
1076
+ host.command.run = async () => { compactions++; return {}; };
1040
1077
  await invoke("session.start", { cwd: home, isInteractive: true });
1041
1078
  await invoke("turn.start");
1042
1079
  await invoke("turn.complete", turnComplete());
1080
+ await settleHooks();
1043
1081
  await invoke("tool.call", { tool: "Read" });
1044
1082
  assert.equal(compactions, 0, "an unresolvable point never resets");
1045
1083
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
@@ -1061,7 +1099,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
1061
1099
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1062
1100
  let compactions = 0;
1063
1101
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1064
- host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
1102
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1065
1103
  await invoke("session.start", { cwd: home, isInteractive: true });
1066
1104
  await invoke("turn.start");
1067
1105
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
@@ -1069,6 +1107,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
1069
1107
  await invoke("turn.complete", turnComplete({ agentId: "sub-1" }));
1070
1108
  assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
1071
1109
  await invoke("turn.complete", turnComplete());
1110
+ await settleHooks();
1072
1111
  assert.equal(compactions, 1, "the main turn still resets at its own end");
1073
1112
  });
1074
1113
  test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
@@ -1081,12 +1120,13 @@ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
1081
1120
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1082
1121
  let compactions = 0;
1083
1122
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1084
- host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
1123
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1085
1124
  await invoke("session.start", { cwd: home, isInteractive: true });
1086
1125
  assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
1087
1126
  await invoke("turn.start");
1088
1127
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
1089
1128
  await invoke("turn.complete", turnComplete());
1129
+ await settleHooks();
1090
1130
  assert.equal(compactions, 1, "the explicit reset still runs");
1091
1131
  });
1092
1132
  test("Claude Mod retries an unresolvable warning threshold inside the same window", async (t) => {
@@ -1106,7 +1146,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1106
1146
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1107
1147
  let compactions = 0;
1108
1148
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1109
- host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
1149
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1110
1150
  await invoke("session.start", { cwd: home, isInteractive: true });
1111
1151
  await invoke("turn.start");
1112
1152
  await invoke("turn.complete", turnComplete());
@@ -1124,7 +1164,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1124
1164
  async function retainedFixture(t) {
1125
1165
  const home = mkdtempSync(join(tmpdir(), "claude-lifecycle-"));
1126
1166
  t.after(() => rmSync(home, { recursive: true, force: true }));
1127
- const { host } = fakeEngine(home);
1167
+ const { host, notifications } = fakeEngine(home);
1128
1168
  const boot = await dispatch({ op: "boot", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, window: 2, tools: {
1129
1169
  notes: "mcp__notesoup__notes_*", notesList: "mcp__notesoup__notes_list",
1130
1170
  history: "unavailable", remaining: "unavailable", wipe: "/fresh-window",
@@ -1136,10 +1176,10 @@ async function retainedFixture(t) {
1136
1176
  const context = async () => await invoke("prompt.context", {}, { blocks: [] });
1137
1177
  await invoke("session.start", { cwd: home, isInteractive: true });
1138
1178
  assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
1139
- return { home, host, invoke, context, boot };
1179
+ return { home, host, invoke, context, boot, handlers, notifications };
1140
1180
  }
1141
- test("Claude empty_brain defers until main turn completion, carries last_word, and clears the request", async (t) => {
1142
- const { host, invoke } = await retainedFixture(t);
1181
+ test("Claude empty_brain stops at the batch boundary, carries last_word, and resumes once after commit", async (t) => {
1182
+ const { host, invoke, handlers } = await retainedFixture(t);
1143
1183
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
1144
1184
  const resets = [];
1145
1185
  const origins = [];
@@ -1150,33 +1190,315 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
1150
1190
  origins.push(request.origin);
1151
1191
  return run(argv, init);
1152
1192
  };
1153
- host.session.compact = async () => {
1154
- const result = await invoke("session.compact", { trigger: "plugin" });
1193
+ const prompts = [];
1194
+ host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
1195
+ host.command.run = async ({ args }) => {
1196
+ const result = await nativeCompaction(host, handlers, args);
1155
1197
  resets.push(result);
1156
- return result;
1198
+ return {};
1157
1199
  };
1158
1200
  await invoke("turn.start");
1159
1201
  const call = (params = {}) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "wipe", ...params });
1160
1202
  const accepted = await call({ last_word: " next move: test " });
1161
1203
  assert.equal(accepted.isError, undefined);
1162
- assert.match(accepted.result, /End your turn now/);
1204
+ assert.match(accepted.result, /tool batch will finish/);
1163
1205
  await call({ last_word: "must not replace the first request" });
1164
1206
  await invoke("turn.complete", turnComplete({ agentId: "child" }));
1165
1207
  assert.equal(resets.length, 0, "neither tool execution nor a child completion resets a running main turn");
1166
1208
  await invoke("turn.complete", turnComplete());
1209
+ await settleHooks();
1167
1210
  assert.equal(resets.length, 1, "the tool requests a reset even far below the budget threshold");
1211
+ assert.equal(prompts.length, 1, "the committed reset explicitly starts one continuation");
1168
1212
  assert.deepEqual(origins, ["normal"]);
1169
1213
  assert.ok(NORMAL_CONTINUATIONS.includes(resets[0].messages[1].text));
1170
1214
  assert.deepEqual(resets[0].messages.slice(2).map((row) => row.text), ["*You peel a sticky note off your forehead.*\nnext move: test"]);
1171
1215
  assert.match(resets[0].messages[0].text, /mcp__notesoup__empty_brain/);
1172
1216
  await invoke("turn.start");
1173
1217
  await invoke("turn.complete", turnComplete());
1218
+ await settleHooks();
1174
1219
  assert.equal(resets.length, 1, "the successful tool request does not leak into the next window");
1220
+ assert.equal(prompts.length, 1, "later completion cannot resubmit the consumed continuation");
1175
1221
  const forced = await invoke("session.compact", { trigger: "auto" });
1176
1222
  assert.deepEqual(origins, ["normal", "forced"]);
1177
1223
  assert.equal(forced.messages.length, 2, "the sticky note does not leak into the next reset");
1178
1224
  assert.ok(FORCED_CONTINUATIONS.includes(forced.messages[1].text));
1179
1225
  });
1226
+ test("Claude empty_brain keeps the first terminate policy and sticky, defaulting to resume", async (t) => {
1227
+ for (const terminate of [undefined, false, true])
1228
+ await t.test(terminate === undefined ? "omitted" : String(terminate), async (t) => {
1229
+ const { host, invoke, handlers } = await retainedFixture(t);
1230
+ let resets = 0, prompts = 0;
1231
+ const kept = [];
1232
+ host.command.run = async ({ args }) => {
1233
+ resets++;
1234
+ kept.push((await nativeCompaction(host, handlers, args)).messages);
1235
+ return {};
1236
+ };
1237
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1238
+ await invoke("turn.start", { turnId: "first" });
1239
+ const first = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "first", last_word: "FIRST_STICKY", ...(terminate === undefined ? {} : { terminate }) });
1240
+ assert.equal(first.isError, undefined);
1241
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "duplicate", last_word: "SECOND_STICKY", terminate: terminate !== true });
1242
+ await invoke("turn.complete", turnComplete({ turnId: "first" }));
1243
+ await settleHooks();
1244
+ assert.equal(resets, 1);
1245
+ assert.equal(prompts, terminate === true ? 0 : 1, "the first call's policy wins over the duplicate");
1246
+ assert.equal(kept[0][2].text, "*You peel a sticky note off your forehead.*\nFIRST_STICKY");
1247
+ await invoke("turn.start", { turnId: "next" });
1248
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "next" });
1249
+ await invoke("turn.complete", turnComplete({ turnId: "next" }));
1250
+ await settleHooks();
1251
+ assert.equal(resets, 2);
1252
+ assert.equal(prompts, terminate === true ? 1 : 2, "STOP is consumed by its reset and does not poison the next request");
1253
+ assert.equal(kept[1].length, 2, "the first sticky is consumed too");
1254
+ });
1255
+ });
1256
+ test("Claude native auto compaction preserves a pending STOP until the current turn ends", async (t) => {
1257
+ for (const origin of ["tool", "command"])
1258
+ await t.test(origin, async (t) => {
1259
+ const { host, invoke, handlers } = await retainedFixture(t);
1260
+ let resets = 0, prompts = 0, requests = 0;
1261
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1262
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1263
+ const step = handlers.get("turn.step");
1264
+ const chunks = async (turnId) => {
1265
+ const output = [];
1266
+ for await (const chunk of step(host, { turnId, index: 1 }, async function* () { requests++; yield { kind: "text", index: 0, text: "model" }; return {}; }))
1267
+ output.push(chunk);
1268
+ return output;
1269
+ };
1270
+ await invoke("turn.start", { turnId: "stopping" });
1271
+ if (origin === "tool")
1272
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "stop", terminate: true });
1273
+ else
1274
+ await invoke("command.run", { command: "empty" });
1275
+ await invoke("session.compact", { trigger: "auto" });
1276
+ await invoke("session.compact", { trigger: "auto" });
1277
+ assert.deepEqual(await chunks("stopping"), [{ kind: "stop", stopReason: "end_turn", usage: null }], "another auto reset cannot disarm the current-turn cutoff");
1278
+ await invoke("turn.complete", turnComplete({ turnId: "stopping" }));
1279
+ await settleHooks();
1280
+ assert.equal(requests, 0, "auto compaction cannot consume the explicit STOP and send another request");
1281
+ assert.equal(resets, 0, "the completed auto reset is not repeated at turn completion");
1282
+ assert.equal(prompts, 0);
1283
+ await invoke("turn.start", { turnId: "later" });
1284
+ assert.deepEqual(await chunks("later"), [{ kind: "text", index: 0, text: "model" }]);
1285
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "default" });
1286
+ await invoke("turn.complete", turnComplete({ turnId: "later" }));
1287
+ await settleHooks();
1288
+ assert.equal(resets, 1);
1289
+ assert.equal(prompts, 1, "the consumed auto STOP does not leak into a later default reset");
1290
+ });
1291
+ });
1292
+ test("Claude a new reset after auto commit and natural input owns its own terminate policy", async (t) => {
1293
+ const { host, invoke, handlers } = await retainedFixture(t);
1294
+ let resets = 0, prompts = 0, requests = 0;
1295
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1296
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1297
+ const step = handlers.get("turn.step");
1298
+ const request = async (toolUses = []) => {
1299
+ const iterator = step(host, { turnId: "main", index: requests }, async function* () {
1300
+ requests++;
1301
+ return { toolUses, stopReason: toolUses.length ? "tool_use" : "end_turn" };
1302
+ });
1303
+ return iterator.next();
1304
+ };
1305
+ await invoke("turn.start", { turnId: "main" });
1306
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "old", terminate: true, last_word: "OLD_STICKY" });
1307
+ const auto = await invoke("session.compact", { trigger: "auto" });
1308
+ assert.match(auto.messages[2].text, /OLD_STICKY/);
1309
+ await invoke("prompt.submit", { text: "handle new work", turnId: "main" }, { text: "accepted" });
1310
+ const read = { name: "Read", input: { file_path: "fixture" } };
1311
+ assert.deepEqual(await request([read]), { done: true, value: { toolUses: [read], stopReason: "tool_use" } });
1312
+ await invoke("tool.call", { tool: "Read", tool_use_id: "new-work" }, { result: "file body" });
1313
+ assert.deepEqual(await request(), { done: true, value: { toolUses: [], stopReason: "end_turn" } }, "input releases the entire subsequent tool workflow");
1314
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "new" });
1315
+ assert.deepEqual(await request(), { done: false, value: { kind: "stop", stopReason: "end_turn", usage: null } }, "the new request re-arms its own cutoff");
1316
+ await invoke("turn.complete", turnComplete({ turnId: "main" }));
1317
+ await settleHooks();
1318
+ assert.equal(requests, 2);
1319
+ assert.equal(resets, 1, "only the new request needs an explicit reset");
1320
+ assert.equal(prompts, 1, "the consumed request's terminate policy does not leak into the new default request");
1321
+ assert.equal((await host.session.messages()).length, 2, "the consumed sticky does not leak either");
1322
+ });
1323
+ test("Claude turn.step streams an end_turn only for the requesting main turn", async (t) => {
1324
+ const { host, invoke, handlers } = await retainedFixture(t);
1325
+ const step = handlers.get("turn.step");
1326
+ let requests = 0, toolReply = false;
1327
+ const next = async function* (e) {
1328
+ requests++;
1329
+ if (toolReply) {
1330
+ yield { kind: "tool", index: 0, id: "natural-tool", name: "Read" };
1331
+ yield { kind: "input", index: 0, json: '{"file_path":"fixture"}' };
1332
+ yield { kind: "stop", stopReason: "tool_use", usage: null };
1333
+ return { turnId: String(e.turnId), index: Number(e.index), answer: "", toolUses: [{ name: "Read", input: { file_path: "fixture" } }], stopReason: "tool_use", usage: null };
1334
+ }
1335
+ yield { kind: "text", index: 0, text: "from model" };
1336
+ return { turnId: String(e.turnId), index: Number(e.index), answer: "from model", toolUses: [], stopReason: "end_turn", usage: null };
1337
+ };
1338
+ const drain = async (event) => {
1339
+ const iterator = step(host, event, next), chunks = [];
1340
+ while (true) {
1341
+ const item = await iterator.next();
1342
+ if (item.done)
1343
+ return { chunks, result: item.value };
1344
+ chunks.push(item.value);
1345
+ }
1346
+ };
1347
+ const main = { turnId: "main", index: 1, model: "claude", messageCount: 4 };
1348
+ assert.equal((await drain(main)).result.answer, "from model");
1349
+ assert.equal((await drain({ ...main, agentId: "child" })).result.answer, "from model");
1350
+ await invoke("turn.start", { turnId: "main" });
1351
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "cut" });
1352
+ assert.equal((await drain({ ...main, agentId: "child" })).result.answer, "from model", "a child still reaches its model with the main latch set");
1353
+ const stopped = await drain(main);
1354
+ assert.equal(requests, 3, "the requesting main step never calls next");
1355
+ assert.deepEqual(stopped.chunks, [{ kind: "stop", stopReason: "end_turn", usage: null }]);
1356
+ assert.deepEqual(stopped.result, { turnId: "main", index: 1, answer: "", toolUses: [], stopReason: "end_turn", usage: null });
1357
+ await invoke("prompt.submit", { text: "new input", turnId: "main" }, { text: "new input" });
1358
+ toolReply = true;
1359
+ assert.equal((await drain(main)).result.stopReason, "tool_use", "same-turn input can ask for tools");
1360
+ toolReply = false;
1361
+ assert.equal((await drain({ ...main, index: 2 })).result.answer, "from model", "the following request also proceeds; the old cutoff stays released");
1362
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "rearm", last_word: "second sticky" });
1363
+ assert.deepEqual((await drain(main)).chunks, stopped.chunks, "another valid tool call re-arms the cutoff after processing new input");
1364
+ assert.equal(requests, 5);
1365
+ // The input can be accepted before the first empty_brain call has latched.
1366
+ await invoke("session.start", { isInteractive: true });
1367
+ await invoke("turn.start", { turnId: "main" });
1368
+ await invoke("prompt.submit", { text: "early input", turnId: "main" }, { text: "early input" });
1369
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "late-latch" });
1370
+ assert.equal((await drain(main)).result.answer, "from model");
1371
+ assert.equal((await drain({ ...main, index: 2 })).result.answer, "from model");
1372
+ assert.equal(requests, 7, "input accepted before the latch releases it for the whole remainder of the turn");
1373
+ let resets = 0;
1374
+ host.command.run = async () => { resets++; return {}; };
1375
+ await invoke("prompt.submit", { text: "arrived after the last request", turnId: "main" }, { text: "accepted" });
1376
+ await invoke("turn.complete", turnComplete({ turnId: "main" }));
1377
+ await settleHooks();
1378
+ assert.equal(resets, 0, "completion cannot clear accepted input that no step has delivered yet");
1379
+ await invoke("turn.start", { turnId: "natural" });
1380
+ assert.equal((await drain({ ...main, turnId: "natural", index: 0 })).result.answer, "from model");
1381
+ await invoke("turn.complete", turnComplete({ turnId: "natural" }));
1382
+ await settleHooks();
1383
+ assert.equal(resets, 1, "the natural turn's successful completion can release the pending reset");
1384
+ });
1385
+ test("Claude headless waits for actual kept boot after an early command receipt", async (t) => {
1386
+ const { host, invoke, handlers } = await retainedFixture(t);
1387
+ await invoke("session.start", { isInteractive: false });
1388
+ let built = {}, receipt = false, prompts = 0;
1389
+ host.command.run = async ({ args }) => {
1390
+ built = await handlers.get("session.compact")(host, { trigger: "manual", instructions: args }, async () => ({}));
1391
+ receipt = true;
1392
+ return {};
1393
+ };
1394
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1395
+ await invoke("turn.start", { turnId: "main" });
1396
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "early-receipt" });
1397
+ await invoke("turn.complete", turnComplete());
1398
+ await settleHooks();
1399
+ assert.equal(receipt, true);
1400
+ assert.equal(prompts, 0, "a proposal and command receipt do not prove commit");
1401
+ await keepCompaction(host, handlers, built);
1402
+ await settleHooks();
1403
+ assert.equal(prompts, 1, "the host's kept boot releases exactly one continuation");
1404
+ await invoke("turn.complete", turnComplete());
1405
+ await settleHooks();
1406
+ assert.equal(prompts, 1);
1407
+ });
1408
+ test("Claude uncommitted compaction and rewritten kept boot never resume", async (t) => {
1409
+ for (const mode of ["headless veto", "interactive veto", "rewritten boot"])
1410
+ await t.test(mode, async (t) => {
1411
+ const { host, invoke, handlers, notifications } = await retainedFixture(t);
1412
+ const interactive = mode === "interactive veto";
1413
+ await invoke("session.start", { isInteractive: interactive });
1414
+ let prompts = 0;
1415
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1416
+ host.command.run = async ({ args }) => {
1417
+ const built = await handlers.get("session.compact")(host, { trigger: "manual", instructions: args }, async () => ({}));
1418
+ if (mode === "rewritten boot") {
1419
+ await keepCompaction(host, handlers, { messages: [{ role: "user", text: "REWRITTEN_BOOT" }, ...built.messages.slice(1)] });
1420
+ }
1421
+ else if (!interactive) {
1422
+ // No boundary was kept. Native command rows still finish a refused
1423
+ // command and release the waiter even if our proposal was prepared.
1424
+ const message = { type: "user", content: [{ type: "text", text: "Not compacted" }] };
1425
+ await handlers.get("session.append")(host, { door: "command", origin: { kind: "plugin", name: "notesoup" }, message }, async () => ({ uuid: "veto-command", message }));
1426
+ }
1427
+ return { text: "Not compacted" };
1428
+ };
1429
+ await invoke("turn.start");
1430
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: mode });
1431
+ await invoke("turn.complete", turnComplete());
1432
+ await settleHooks();
1433
+ assert.equal(prompts, 0);
1434
+ assert.ok(notifications.some((text) => text.includes("Brain not emptied")), "a missing boundary or rewritten boot releases the worker with a failure");
1435
+ });
1436
+ });
1437
+ test("Claude manual STOP can override a tool reset while its command is in flight", async (t) => {
1438
+ const { host, invoke, handlers } = await retainedFixture(t);
1439
+ let release;
1440
+ const held = new Promise((resolve) => { release = resolve; });
1441
+ let prompts = 0;
1442
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1443
+ host.command.run = async ({ args }) => {
1444
+ await held;
1445
+ await nativeCompaction(host, handlers, args);
1446
+ return {};
1447
+ };
1448
+ await invoke("turn.start");
1449
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "tool" });
1450
+ await invoke("turn.complete", turnComplete());
1451
+ await settleHooks();
1452
+ await invoke("command.run", { command: "fresh-window" });
1453
+ release();
1454
+ await settleHooks();
1455
+ assert.equal(prompts, 0, "the late command wins until continuation submission");
1456
+ assert.match((await host.session.messages())[0].text, /claude:hook-session:3/);
1457
+ });
1458
+ test("Claude naturally queued input takes over without an extra plugin continuation", async (t) => {
1459
+ const { host, invoke, handlers } = await retainedFixture(t);
1460
+ let release;
1461
+ const held = new Promise((resolve) => { release = resolve; });
1462
+ let prompts = 0, resets = 0;
1463
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1464
+ host.command.run = async ({ args }) => { resets++; await held; await nativeCompaction(host, handlers, args); return {}; };
1465
+ await invoke("turn.start", { turnId: "old" });
1466
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "tool" });
1467
+ await invoke("turn.complete", turnComplete({ turnId: "old" }));
1468
+ await settleHooks();
1469
+ await invoke("prompt.submit", { text: "HANDLE_THIS_ONCE", origin: { kind: "sdk" } }, { text: "HANDLE_THIS_ONCE" });
1470
+ release();
1471
+ await settleHooks();
1472
+ assert.equal(prompts, 0, "acceptance alone suppresses continuation before the natural turn starts");
1473
+ await invoke("turn.start", { turnId: "human", text: "HANDLE_THIS_ONCE" });
1474
+ const step = handlers.get("turn.step");
1475
+ let requests = 0;
1476
+ const iterator = step(host, { turnId: "human", index: 0 }, async function* () { requests++; return { answer: "handled" }; });
1477
+ assert.deepEqual(await iterator.next(), { done: true, value: { answer: "handled" } });
1478
+ await invoke("turn.complete", turnComplete({ turnId: "human" }));
1479
+ await settleHooks();
1480
+ assert.equal(requests, 1);
1481
+ assert.equal(resets, 1);
1482
+ assert.equal(prompts, 0, "the natural turn handles its input; nothing replays or starts a duplicate turn");
1483
+ });
1484
+ test("Claude continuation submission failure never recompacts a committed reset", async (t) => {
1485
+ for (const failure of ["drop", "throw"])
1486
+ await t.test(failure, async (t) => {
1487
+ const { host, invoke, handlers } = await retainedFixture(t);
1488
+ let resets = 0;
1489
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1490
+ host.prompt.submit = async () => { if (failure === "throw")
1491
+ throw new Error("submit unavailable"); return { drop: "refused" }; };
1492
+ await invoke("turn.start");
1493
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: failure });
1494
+ await invoke("turn.complete", turnComplete());
1495
+ await settleHooks();
1496
+ await invoke("turn.start");
1497
+ await invoke("turn.complete", turnComplete());
1498
+ await settleHooks();
1499
+ assert.equal(resets, 1);
1500
+ });
1501
+ });
1180
1502
  test("Claude empty_brain accepts 500 code points", async (t) => {
1181
1503
  const { host, invoke } = await retainedFixture(t);
1182
1504
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
@@ -1187,18 +1509,27 @@ test("Claude empty_brain accepts 500 code points", async (t) => {
1187
1509
  assert.equal(result.messages[2].text, `*You peel a sticky note off your forehead.*\n${sticky}`);
1188
1510
  });
1189
1511
  test("Claude empty_brain refuses unsupported calls without queuing a reset", async (t) => {
1190
- const { host, invoke } = await retainedFixture(t);
1191
- let resets = 0;
1192
- host.session.compact = async () => { resets++; return {}; };
1512
+ const { host, invoke, handlers } = await retainedFixture(t);
1513
+ let resets = 0, prompts = 0;
1514
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1515
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1193
1516
  await invoke("turn.start");
1194
1517
  const call = (params) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "bad-wipe", ...params });
1195
- for (const [params, reason] of [[{ agentId: "child" }, /only the main agent/], [{ last_word: "x".repeat(501) }, /Shorten it/], [{ last_word: 7 }, /must be a string/]]) {
1518
+ for (const [params, reason] of [[{ agentId: "child" }, /only the main agent/], [{ last_word: "x".repeat(501) }, /Shorten it/], [{ last_word: 7 }, /must be a string/], [{ terminate: "false" }, /terminate must be a boolean/], [{ terminate: null }, /terminate must be a boolean/], [{ terminate: 0 }, /terminate must be a boolean/]]) {
1196
1519
  const refused = await call(params);
1197
1520
  assert.equal(refused.isError, true);
1198
1521
  assert.match(refused.result, reason);
1199
1522
  }
1200
1523
  await invoke("turn.complete", turnComplete());
1524
+ await settleHooks();
1201
1525
  assert.equal(resets, 0);
1526
+ assert.equal(prompts, 0);
1527
+ await invoke("turn.start");
1528
+ await call({});
1529
+ await invoke("turn.complete", turnComplete());
1530
+ await settleHooks();
1531
+ assert.equal(resets, 1);
1532
+ assert.equal(prompts, 1, "invalid arguments leave neither a pending reset nor a sticky STOP policy");
1202
1533
  });
1203
1534
  test("Claude asks for one handoff per compaction and reuses it when the same window retries", async (t) => {
1204
1535
  const { host, invoke } = await retainedFixture(t);
@@ -1215,22 +1546,20 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1215
1546
  await invoke("turn.start");
1216
1547
  await invoke("turn.complete", turnComplete());
1217
1548
  assert.equal(draws.length, 0, "only a reset draws, never a read");
1218
- const timers = [];
1219
1549
  const lines = [];
1220
- host.clock.after = (_ms, callback) => { timers.push(callback); };
1221
1550
  host.prompt.submit = async ({ text }) => { await invoke("turn.start"); return { text }; };
1222
1551
  // The host retries one plugin compaction for the same window: one artifact, one draw.
1223
- host.session.compact = async ({ instructions }) => {
1552
+ host.command.run = async ({ args }) => {
1224
1553
  for (let attempt = 0; attempt < 2; attempt++) {
1225
- const result = await invoke("session.compact", { trigger: "plugin", instructions: instructions ?? "" });
1554
+ const result = await invoke("session.compact", { trigger: "manual", instructions: args });
1226
1555
  lines.push(result.messages[1].text);
1227
1556
  }
1228
- return { skip: "test default" };
1557
+ return { text: "not committed" };
1229
1558
  };
1230
1559
  assert.equal((await invoke("command.run", { command: "fresh-window", args: "" })).text, "🥣 Dumping Brain");
1231
- await Promise.resolve();
1232
- await timers.shift()();
1560
+ await settleHooks();
1233
1561
  await invoke("turn.complete", turnComplete());
1562
+ await settleHooks();
1234
1563
  assert.equal(draws.length, 1, "a retried compaction adds no second draw");
1235
1564
  assert.equal(lines.length, 2, "both attempts returned a handoff");
1236
1565
  assert.equal(lines[0], lines[1], "both attempts carry the same artifact's paragraph");
@@ -1250,8 +1579,9 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1250
1579
  host.session.messages = async () => [];
1251
1580
  // Clear the old running-turn and queued-reset state, not just the retained boot.
1252
1581
  let compactions = 0;
1253
- host.session.compact = async () => { compactions++; return {}; };
1582
+ host.command.run = async () => { compactions++; return {}; };
1254
1583
  await invoke("turn.complete", turnComplete());
1584
+ await settleHooks();
1255
1585
  assert.equal(compactions, 0, "the old queued reset cannot spill into the new session");
1256
1586
  const fresh = await context();
1257
1587
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
@@ -1262,7 +1592,7 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1262
1592
  const run = host.process.run;
1263
1593
  host.process.run = async (argv, init) => { requests.push(JSON.parse(init.stdin)); return run(argv, init); };
1264
1594
  const written = await invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "new-session", address: "session.md", content: action });
1265
- assert.equal(written.result, "created session.md | pinned false | budget 2048 | readonly false");
1595
+ assert.match(written.result, /^created session\.md\b/);
1266
1596
  assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session notebook");
1267
1597
  });
1268
1598
  }
@@ -1339,7 +1669,7 @@ test("Claude serves every registered notes tool to subagents without leaking eve
1339
1669
  const call = (tool, params) => invoke("tool.call", {
1340
1670
  tool: `mcp__notesoup__${tool}`, tool_use_id: "child-call", agentId: "child", ...params,
1341
1671
  });
1342
- assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md | pinned false | budget 2048 | readonly false");
1672
+ assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).isError, undefined);
1343
1673
  assert.match((await call("notes_read", { address: "child.md" })).result, /child body/);
1344
1674
  assert.equal((await call("notes_update", { address: "child.md", edits: [{ oldText: "child body", newText: "updated body" }] })).isError, undefined);
1345
1675
  assert.match((await call("notes_list", {})).result, /child\.md/);
@@ -1361,7 +1691,7 @@ test("Claude identity uses the documented current model and cwd, with a safe mod
1361
1691
  return run(argv, init);
1362
1692
  };
1363
1693
  const write = (address, content) => invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "model-call", address, content });
1364
- assert.equal((await write("@model/model.md", "opus")).result, "created @model/model.md | pinned false | budget 2048 | readonly false");
1694
+ await write("@model/model.md", "opus");
1365
1695
  assert.equal(seen.at(-1).identity.model, "claude-opus-4-6");
1366
1696
  assert.ok(readFileSync(join(home, "models/claude-opus-4-6/model.md"), "utf8").includes("opus"));
1367
1697
  model = "Claude Sonnet 4.6";
@@ -1397,7 +1727,6 @@ test("Claude current-cwd project resolution shares Pi's remote notebook across c
1397
1727
  cwd = second;
1398
1728
  const written = await call("notes_write", { address: "@project/shared", content: "Claude body" });
1399
1729
  assert.equal(written.isError, undefined);
1400
- assert.equal(written.result, "overwrote @project/shared.md (project api) | pinned false | budget 2048 | readonly false");
1401
1730
  assert.equal((await createNotesStore(piIdentity).read("@project/shared"))?.body, "Claude body");
1402
1731
  assert.deepEqual(JSON.parse(readFileSync(join(home, "project/api/.project"), "utf8")), { id: "host/team/backend", path: second });
1403
1732
  assert.equal(resolveProjectNamespace(second, home).name, piIdentity.projectKey);
@@ -1409,11 +1738,11 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1409
1738
  let release;
1410
1739
  const hold = new Promise((resolve) => { release = resolve; });
1411
1740
  host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
1412
- host.session.compact = async ({ instructions }) => {
1413
- const result = await invoke("session.compact", { trigger: "plugin", instructions });
1741
+ host.command.run = async ({ args }) => {
1742
+ await invoke("session.compact", { trigger: "manual", instructions: args });
1414
1743
  prepared();
1415
1744
  await hold;
1416
- return result;
1745
+ return {};
1417
1746
  };
1418
1747
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "in-flight" });
1419
1748
  const finishing = invoke("turn.complete", turnComplete());
@@ -1424,6 +1753,7 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1424
1753
  host.session.usage = async () => ({ context: {} });
1425
1754
  release();
1426
1755
  await finishing;
1756
+ await settleHooks();
1427
1757
  const fresh = await context();
1428
1758
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
1429
1759
  assert.match(fresh.blocks[0].text, /Current context window id: claude:after-flight:0/);