notesoup 0.58.1 → 0.58.2

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.
@@ -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
  }
@@ -501,6 +522,13 @@ 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);
505
533
  const written = await call("notes_write", { address: "hook.md", content: "hook body" });
506
534
  assert.equal(written.result, "created hook.md | pinned false | budget 2048 | readonly false", "the hook hands back the shared text unchanged");
@@ -533,12 +561,12 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
533
561
  let kept = [];
534
562
  const measured = () => ({ context: { tokens, window: 200_000, percent: tokens === undefined ? undefined : (tokens / 200_000) * 100 } });
535
563
  host.session.usage = async () => measured();
536
- host.session.compact = async ({ instructions }) => {
564
+ host.command.run = async ({ args }) => {
537
565
  compactions++;
538
- const result = await invoke("session.compact", { trigger: "plugin", instructions: `${instructions} (rewritten upstream)`, messages: [{ role: "user", text: "OLD_SECRET" }] });
566
+ const result = await nativeCompaction(host, handlers, args);
539
567
  kept = result.messages;
540
568
  tokens = undefined; // The real engine invalidates token usage after compact.
541
- return result;
569
+ return {};
542
570
  };
543
571
  await invoke("session.start", { cwd: home, isInteractive: true });
544
572
  assert.equal(registered.length, 8);
@@ -570,6 +598,7 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
570
598
  await invoke("turn.start");
571
599
  await invoke("command.run", { command: "empty" });
572
600
  await invoke("turn.complete", turnComplete());
601
+ await settleHooks();
573
602
  assert.equal(compactions, 1);
574
603
  assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
575
604
  assert.equal(kept[0].role, "user");
@@ -592,15 +621,17 @@ test("Claude Mod preserves context and cancels a queued reset after an unsuccess
592
621
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
593
622
  const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
594
623
  let compactions = 0;
595
- host.session.compact = async () => { compactions++; return { skip: "reset must not run" }; };
624
+ host.command.run = async () => { compactions++; return { text: "reset must not run" }; };
596
625
  await invoke("session.start", { cwd: home, isInteractive: true });
597
626
  await invoke("turn.start");
598
627
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: `reset-${reason}`, last_word: "DO_NOT_KEEP" });
599
628
  await invoke("turn.complete", turnComplete({ reason }));
629
+ await settleHooks();
600
630
  assert.equal(compactions, 0, `${reason} never submits the queued reset`);
601
631
  assert.ok(notifications.some(text => text.includes("cancelled") && text.includes(reason)), `${reason} reports that its request was cancelled`);
602
632
  await invoke("turn.start");
603
633
  await invoke("turn.complete", turnComplete());
634
+ await settleHooks();
604
635
  assert.equal(compactions, 0, `${reason} leaves no pending reset for a later successful turn`);
605
636
  });
606
637
  }
@@ -629,31 +660,34 @@ test("Claude headless resets through its own manual command, retries failure and
629
660
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
630
661
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", last_word: "STICKY", tool_use_id: "reset" });
631
662
  await invoke("turn.complete", turnComplete());
663
+ await settleHooks();
632
664
  assert.equal(attempts, 1);
633
665
  assert.ok(notifications.some(x => x.includes("command unavailable")));
634
666
  reject = false;
635
667
  await invoke("turn.complete", turnComplete());
668
+ await settleHooks();
636
669
  assert.equal(attempts, 2, "failed requests remain pending");
637
670
  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 }) => {
671
+ // The host skips our command hook; the exact one-use instructions admit it.
672
+ host.command.run = async ({ command, args }) => {
640
673
  attempts++;
641
- const user = await handlers.get("command.run")(host, { command, origin: { kind: "user" } }, async () => invoke("session.compact", { trigger: "manual" }));
674
+ assert.equal(command, "compact");
675
+ const user = await invoke("session.compact", { trigger: "manual", instructions: "unrelated user instructions" });
642
676
  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
- });
677
+ kept = (await nativeCompaction(host, handlers, args)).messages;
647
678
  return {};
648
679
  };
649
680
  await invoke("turn.complete", turnComplete());
681
+ await settleHooks();
650
682
  assert.match(kept[0].text, /claude:hook-session:1/);
651
683
  assert.equal(kept[2].text, "*You peel a sticky note off your forehead.*\nSTICKY");
652
684
  await invoke("turn.complete", turnComplete());
685
+ await settleHooks();
653
686
  assert.equal(attempts, 3, "success clears pending exactly once");
654
687
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
655
688
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "reset2" });
656
689
  await invoke("turn.complete", turnComplete());
690
+ await settleHooks();
657
691
  assert.match(kept[0].text, /claude:hook-session:2/);
658
692
  assert.equal(kept.length, 2, "sticky is consumed once");
659
693
  });
@@ -666,18 +700,13 @@ test("Claude headless warns without proactive resets and supports both manual al
666
700
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
667
701
  let tokens = CLAUDE_200K.warn;
668
702
  let attempts = 0, prompts = 0;
669
- const timers = [];
670
703
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
671
- host.clock.after = (_ms, callback) => { timers.push(callback); };
672
704
  host.prompt.submit = async ({ text }) => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); return { text }; };
673
- host.command.run = async ({ command }) => {
705
+ host.command.run = async ({ args }) => {
674
706
  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
- });
707
+ const result = await nativeCompaction(host, handlers, args);
708
+ assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
709
+ tokens = undefined;
681
710
  return {};
682
711
  };
683
712
  await invoke("session.start", { cwd: home, isInteractive: false });
@@ -690,14 +719,14 @@ test("Claude headless warns without proactive resets and supports both manual al
690
719
  assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
691
720
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
692
721
  await invoke("turn.complete", turnComplete());
722
+ await settleHooks();
693
723
  assert.equal(attempts, 1);
694
724
  for (const command of ["empty", "fresh-window"]) {
695
725
  assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
696
- await Promise.resolve();
697
- await timers.shift()();
726
+ await settleHooks();
698
727
  }
699
728
  assert.equal(attempts, 3);
700
- assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
729
+ assert.equal(prompts, 3, "one tool continuation and one close-out for each idle alias");
701
730
  });
702
731
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
703
732
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -735,15 +764,20 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
735
764
  };
736
765
  host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
737
766
  let result = {};
738
- host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
767
+ host.command.run = async ({ args }) => {
768
+ result = await nativeCompaction(host, handlers, args);
769
+ return result.skip ? { text: result.skip } : {};
770
+ };
739
771
  await invoke("turn.start");
740
772
  await invoke("command.run", { command: "empty" });
741
773
  await invoke("turn.complete", turnComplete());
774
+ await settleHooks();
742
775
  assert.match(result.skip, /notes didn't load/);
743
776
  assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
744
777
  failBoot = false;
745
778
  await invoke("turn.start");
746
779
  await invoke("turn.complete", turnComplete());
780
+ await settleHooks();
747
781
  assert.equal(result.skip, undefined);
748
782
  assert.equal(result.messages.length, 2);
749
783
  assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
@@ -757,20 +791,18 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
757
791
  host.command.register = async (spec) => { commands.push(spec.name); return { command: spec.name }; };
758
792
  let handlers = new Map();
759
793
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
760
- const timers = [];
761
794
  const prompts = [];
762
795
  let kept = [];
763
796
  let compactions = 0;
764
- host.clock.after = (_ms, callback) => { timers.push(callback); };
765
- host.session.compact = async ({ instructions }) => {
797
+ host.command.run = async ({ args }) => {
766
798
  compactions++;
767
- const result = await invoke("session.compact", { trigger: "plugin", instructions });
768
- kept = result.messages;
769
- return result;
799
+ kept = (await nativeCompaction(host, handlers, args)).messages;
800
+ return {};
770
801
  };
771
802
  host.prompt.submit = async ({ text }) => {
772
803
  prompts.push(text);
773
- await invoke("turn.start");
804
+ await invoke("turn.start", { turnId: "closeout" });
805
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "closeout-reset", terminate: false });
774
806
  await invoke("turn.complete", turnComplete());
775
807
  return { text };
776
808
  };
@@ -778,19 +810,16 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
778
810
  await invoke("session.start", { cwd: home, isInteractive: true });
779
811
  assert.deepEqual(commands.sort(), ["empty", "fresh-window"], "only the new short name and the retained alias are registered");
780
812
  assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
781
- assert.equal(timers.length, 0);
813
+ assert.equal(compactions, 0);
782
814
  const command = await invoke("command.run", { command: "empty" });
783
815
  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()();
816
+ await settleHooks();
788
817
  assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
789
818
  assert.equal(prompts[0], CLAUDE_WARNING_PROMPT, "the close-out is the same warning text the automatic path shows");
790
819
  assert.equal(compactions, 1);
791
820
  assert.equal(kept.length, 2);
792
821
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
793
- assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text));
822
+ assert.ok(NORMAL_CONTINUATIONS.includes(kept[1].text), "the close-out called the tool, while the command still keeps STOP policy");
794
823
  host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
795
824
  handlers = new Map();
796
825
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
@@ -799,6 +828,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
799
828
  await invoke("turn.start");
800
829
  await invoke("command.run", { command: "empty" });
801
830
  await invoke("turn.complete", turnComplete());
831
+ await settleHooks();
802
832
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
803
833
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
804
834
  });
@@ -815,8 +845,6 @@ test("Claude failed close-outs release the request so manual reset can retry", a
815
845
  const handlers = new Map();
816
846
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
817
847
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
818
- const timers = [];
819
- host.clock.after = (_ms, callback) => { timers.push(callback); };
820
848
  host.prompt.submit = async ({ text }) => {
821
849
  if (failing && failure === "submit")
822
850
  throw new Error("submission unavailable");
@@ -826,14 +854,14 @@ test("Claude failed close-outs release the request so manual reset can retry", a
826
854
  await invoke("turn.complete", turnComplete());
827
855
  return { text };
828
856
  };
829
- host.session.compact = async ({ instructions }) => {
857
+ host.command.run = async ({ args }) => {
830
858
  resets++;
831
- return await invoke("session.compact", { trigger: "plugin", instructions });
859
+ await nativeCompaction(host, handlers, args);
860
+ return {};
832
861
  };
833
862
  await invoke("session.start", { isInteractive: true });
834
863
  await invoke("command.run", { command: "fresh-window" });
835
- await Promise.resolve();
836
- await timers.shift()();
864
+ await settleHooks();
837
865
  assert.equal(resets, 0);
838
866
  assert.ok(notifications.some(text => text.includes("close-out")), "failure is visible");
839
867
  await invoke("turn.start");
@@ -841,9 +869,7 @@ test("Claude failed close-outs release the request so manual reset can retry", a
841
869
  assert.equal(resets, 0, "a failed close-out must not spring a reset on an unrelated turn");
842
870
  failing = false;
843
871
  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()();
872
+ await settleHooks();
847
873
  assert.equal(resets, 1);
848
874
  });
849
875
  });
@@ -894,13 +920,14 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
894
920
  return run(argv, init);
895
921
  };
896
922
  let resets = 0;
897
- host.session.compact = async () => { resets++; return {}; };
923
+ host.command.run = async () => { resets++; return {}; };
898
924
  const submit = () => invoke("prompt.submit", { text: "continue" }, {}, async (e) => e);
899
925
  assert.equal((await submit()).context, undefined);
900
926
  tokens++;
901
927
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
902
928
  assert.equal((await submit()).context, undefined, "one warning per window");
903
929
  await invoke("turn.complete", turnComplete());
930
+ await settleHooks();
904
931
  assert.equal(resets, 0, "warning and turn completion never proactively clear");
905
932
  assert.equal((await invoke("session.compact", { trigger: "auto" })).messages.length, 2);
906
933
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
@@ -982,7 +1009,7 @@ test("Claude Mod keeps warning timing when auto-compact is off without clearing
982
1009
  let tokens = 155_423;
983
1010
  let compactions = 0;
984
1011
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
985
- host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
1012
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
986
1013
  await invoke("session.start", { cwd: home, isInteractive: true });
987
1014
  await invoke("turn.start");
988
1015
  await invoke("turn.complete", turnComplete());
@@ -1002,14 +1029,14 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
1002
1029
  t.after(() => rmSync(home, { recursive: true, force: true }));
1003
1030
  const { host, notifications } = fakeEngine(home);
1004
1031
  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); };
1032
+ let prompts = 0;
1033
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1007
1034
  const handlers = new Map();
1008
1035
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1009
1036
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1010
1037
  let compactions = 0;
1011
1038
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1012
- host.session.compact = async () => { compactions++; return {}; };
1039
+ host.command.run = async () => { compactions++; return {}; };
1013
1040
  await invoke("session.start", { cwd: home, isInteractive: true });
1014
1041
  assert.equal(notifications.length, 1, "one startup line");
1015
1042
  assert.match(notifications[0], /DISABLE_COMPACT/);
@@ -1018,9 +1045,10 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
1018
1045
  const tool = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "disabled-compact" });
1019
1046
  assert.equal(tool.isError, true);
1020
1047
  assert.match(tool.result, /DISABLE_COMPACT/);
1021
- assert.equal(timers.length, 0, "no close-out turn is queued");
1022
1048
  await invoke("turn.start");
1023
1049
  await invoke("turn.complete", turnComplete());
1050
+ await settleHooks();
1051
+ assert.equal(prompts, 0, "no close-out turn is queued");
1024
1052
  assert.equal(compactions, 0, "disabled reset requests never run");
1025
1053
  assert.equal(notifications.length, 1, "detection logs once, not per turn");
1026
1054
  const upstream = { result: "upstream", context: ["other plugin"] };
@@ -1036,10 +1064,11 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
1036
1064
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1037
1065
  let compactions = 0;
1038
1066
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1039
- host.session.compact = async () => { compactions++; return {}; };
1067
+ host.command.run = async () => { compactions++; return {}; };
1040
1068
  await invoke("session.start", { cwd: home, isInteractive: true });
1041
1069
  await invoke("turn.start");
1042
1070
  await invoke("turn.complete", turnComplete());
1071
+ await settleHooks();
1043
1072
  await invoke("tool.call", { tool: "Read" });
1044
1073
  assert.equal(compactions, 0, "an unresolvable point never resets");
1045
1074
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
@@ -1061,7 +1090,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
1061
1090
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1062
1091
  let compactions = 0;
1063
1092
  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 }); };
1093
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1065
1094
  await invoke("session.start", { cwd: home, isInteractive: true });
1066
1095
  await invoke("turn.start");
1067
1096
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
@@ -1069,6 +1098,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
1069
1098
  await invoke("turn.complete", turnComplete({ agentId: "sub-1" }));
1070
1099
  assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
1071
1100
  await invoke("turn.complete", turnComplete());
1101
+ await settleHooks();
1072
1102
  assert.equal(compactions, 1, "the main turn still resets at its own end");
1073
1103
  });
1074
1104
  test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
@@ -1081,12 +1111,13 @@ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
1081
1111
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1082
1112
  let compactions = 0;
1083
1113
  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 }); };
1114
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1085
1115
  await invoke("session.start", { cwd: home, isInteractive: true });
1086
1116
  assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
1087
1117
  await invoke("turn.start");
1088
1118
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
1089
1119
  await invoke("turn.complete", turnComplete());
1120
+ await settleHooks();
1090
1121
  assert.equal(compactions, 1, "the explicit reset still runs");
1091
1122
  });
1092
1123
  test("Claude Mod retries an unresolvable warning threshold inside the same window", async (t) => {
@@ -1106,7 +1137,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1106
1137
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1107
1138
  let compactions = 0;
1108
1139
  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 }); };
1140
+ host.command.run = async ({ args }) => { compactions++; await nativeCompaction(host, handlers, args); return {}; };
1110
1141
  await invoke("session.start", { cwd: home, isInteractive: true });
1111
1142
  await invoke("turn.start");
1112
1143
  await invoke("turn.complete", turnComplete());
@@ -1124,7 +1155,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1124
1155
  async function retainedFixture(t) {
1125
1156
  const home = mkdtempSync(join(tmpdir(), "claude-lifecycle-"));
1126
1157
  t.after(() => rmSync(home, { recursive: true, force: true }));
1127
- const { host } = fakeEngine(home);
1158
+ const { host, notifications } = fakeEngine(home);
1128
1159
  const boot = await dispatch({ op: "boot", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, window: 2, tools: {
1129
1160
  notes: "mcp__notesoup__notes_*", notesList: "mcp__notesoup__notes_list",
1130
1161
  history: "unavailable", remaining: "unavailable", wipe: "/fresh-window",
@@ -1136,10 +1167,10 @@ async function retainedFixture(t) {
1136
1167
  const context = async () => await invoke("prompt.context", {}, { blocks: [] });
1137
1168
  await invoke("session.start", { cwd: home, isInteractive: true });
1138
1169
  assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
1139
- return { home, host, invoke, context, boot };
1170
+ return { home, host, invoke, context, boot, handlers, notifications };
1140
1171
  }
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);
1172
+ test("Claude empty_brain stops at the batch boundary, carries last_word, and resumes once after commit", async (t) => {
1173
+ const { host, invoke, handlers } = await retainedFixture(t);
1143
1174
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
1144
1175
  const resets = [];
1145
1176
  const origins = [];
@@ -1150,33 +1181,315 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
1150
1181
  origins.push(request.origin);
1151
1182
  return run(argv, init);
1152
1183
  };
1153
- host.session.compact = async () => {
1154
- const result = await invoke("session.compact", { trigger: "plugin" });
1184
+ const prompts = [];
1185
+ host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
1186
+ host.command.run = async ({ args }) => {
1187
+ const result = await nativeCompaction(host, handlers, args);
1155
1188
  resets.push(result);
1156
- return result;
1189
+ return {};
1157
1190
  };
1158
1191
  await invoke("turn.start");
1159
1192
  const call = (params = {}) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "wipe", ...params });
1160
1193
  const accepted = await call({ last_word: " next move: test " });
1161
1194
  assert.equal(accepted.isError, undefined);
1162
- assert.match(accepted.result, /End your turn now/);
1195
+ assert.match(accepted.result, /tool batch will finish/);
1163
1196
  await call({ last_word: "must not replace the first request" });
1164
1197
  await invoke("turn.complete", turnComplete({ agentId: "child" }));
1165
1198
  assert.equal(resets.length, 0, "neither tool execution nor a child completion resets a running main turn");
1166
1199
  await invoke("turn.complete", turnComplete());
1200
+ await settleHooks();
1167
1201
  assert.equal(resets.length, 1, "the tool requests a reset even far below the budget threshold");
1202
+ assert.equal(prompts.length, 1, "the committed reset explicitly starts one continuation");
1168
1203
  assert.deepEqual(origins, ["normal"]);
1169
1204
  assert.ok(NORMAL_CONTINUATIONS.includes(resets[0].messages[1].text));
1170
1205
  assert.deepEqual(resets[0].messages.slice(2).map((row) => row.text), ["*You peel a sticky note off your forehead.*\nnext move: test"]);
1171
1206
  assert.match(resets[0].messages[0].text, /mcp__notesoup__empty_brain/);
1172
1207
  await invoke("turn.start");
1173
1208
  await invoke("turn.complete", turnComplete());
1209
+ await settleHooks();
1174
1210
  assert.equal(resets.length, 1, "the successful tool request does not leak into the next window");
1211
+ assert.equal(prompts.length, 1, "later completion cannot resubmit the consumed continuation");
1175
1212
  const forced = await invoke("session.compact", { trigger: "auto" });
1176
1213
  assert.deepEqual(origins, ["normal", "forced"]);
1177
1214
  assert.equal(forced.messages.length, 2, "the sticky note does not leak into the next reset");
1178
1215
  assert.ok(FORCED_CONTINUATIONS.includes(forced.messages[1].text));
1179
1216
  });
1217
+ test("Claude empty_brain keeps the first terminate policy and sticky, defaulting to resume", async (t) => {
1218
+ for (const terminate of [undefined, false, true])
1219
+ await t.test(terminate === undefined ? "omitted" : String(terminate), async (t) => {
1220
+ const { host, invoke, handlers } = await retainedFixture(t);
1221
+ let resets = 0, prompts = 0;
1222
+ const kept = [];
1223
+ host.command.run = async ({ args }) => {
1224
+ resets++;
1225
+ kept.push((await nativeCompaction(host, handlers, args)).messages);
1226
+ return {};
1227
+ };
1228
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1229
+ await invoke("turn.start", { turnId: "first" });
1230
+ const first = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "first", last_word: "FIRST_STICKY", ...(terminate === undefined ? {} : { terminate }) });
1231
+ assert.equal(first.isError, undefined);
1232
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "duplicate", last_word: "SECOND_STICKY", terminate: terminate !== true });
1233
+ await invoke("turn.complete", turnComplete({ turnId: "first" }));
1234
+ await settleHooks();
1235
+ assert.equal(resets, 1);
1236
+ assert.equal(prompts, terminate === true ? 0 : 1, "the first call's policy wins over the duplicate");
1237
+ assert.equal(kept[0][2].text, "*You peel a sticky note off your forehead.*\nFIRST_STICKY");
1238
+ await invoke("turn.start", { turnId: "next" });
1239
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "next" });
1240
+ await invoke("turn.complete", turnComplete({ turnId: "next" }));
1241
+ await settleHooks();
1242
+ assert.equal(resets, 2);
1243
+ assert.equal(prompts, terminate === true ? 1 : 2, "STOP is consumed by its reset and does not poison the next request");
1244
+ assert.equal(kept[1].length, 2, "the first sticky is consumed too");
1245
+ });
1246
+ });
1247
+ test("Claude native auto compaction preserves a pending STOP until the current turn ends", async (t) => {
1248
+ for (const origin of ["tool", "command"])
1249
+ await t.test(origin, async (t) => {
1250
+ const { host, invoke, handlers } = await retainedFixture(t);
1251
+ let resets = 0, prompts = 0, requests = 0;
1252
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1253
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1254
+ const step = handlers.get("turn.step");
1255
+ const chunks = async (turnId) => {
1256
+ const output = [];
1257
+ for await (const chunk of step(host, { turnId, index: 1 }, async function* () { requests++; yield { kind: "text", index: 0, text: "model" }; return {}; }))
1258
+ output.push(chunk);
1259
+ return output;
1260
+ };
1261
+ await invoke("turn.start", { turnId: "stopping" });
1262
+ if (origin === "tool")
1263
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "stop", terminate: true });
1264
+ else
1265
+ await invoke("command.run", { command: "empty" });
1266
+ await invoke("session.compact", { trigger: "auto" });
1267
+ await invoke("session.compact", { trigger: "auto" });
1268
+ assert.deepEqual(await chunks("stopping"), [{ kind: "stop", stopReason: "end_turn", usage: null }], "another auto reset cannot disarm the current-turn cutoff");
1269
+ await invoke("turn.complete", turnComplete({ turnId: "stopping" }));
1270
+ await settleHooks();
1271
+ assert.equal(requests, 0, "auto compaction cannot consume the explicit STOP and send another request");
1272
+ assert.equal(resets, 0, "the completed auto reset is not repeated at turn completion");
1273
+ assert.equal(prompts, 0);
1274
+ await invoke("turn.start", { turnId: "later" });
1275
+ assert.deepEqual(await chunks("later"), [{ kind: "text", index: 0, text: "model" }]);
1276
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "default" });
1277
+ await invoke("turn.complete", turnComplete({ turnId: "later" }));
1278
+ await settleHooks();
1279
+ assert.equal(resets, 1);
1280
+ assert.equal(prompts, 1, "the consumed auto STOP does not leak into a later default reset");
1281
+ });
1282
+ });
1283
+ test("Claude a new reset after auto commit and natural input owns its own terminate policy", async (t) => {
1284
+ const { host, invoke, handlers } = await retainedFixture(t);
1285
+ let resets = 0, prompts = 0, requests = 0;
1286
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1287
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1288
+ const step = handlers.get("turn.step");
1289
+ const request = async (toolUses = []) => {
1290
+ const iterator = step(host, { turnId: "main", index: requests }, async function* () {
1291
+ requests++;
1292
+ return { toolUses, stopReason: toolUses.length ? "tool_use" : "end_turn" };
1293
+ });
1294
+ return iterator.next();
1295
+ };
1296
+ await invoke("turn.start", { turnId: "main" });
1297
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "old", terminate: true, last_word: "OLD_STICKY" });
1298
+ const auto = await invoke("session.compact", { trigger: "auto" });
1299
+ assert.match(auto.messages[2].text, /OLD_STICKY/);
1300
+ await invoke("prompt.submit", { text: "handle new work", turnId: "main" }, { text: "accepted" });
1301
+ const read = { name: "Read", input: { file_path: "fixture" } };
1302
+ assert.deepEqual(await request([read]), { done: true, value: { toolUses: [read], stopReason: "tool_use" } });
1303
+ await invoke("tool.call", { tool: "Read", tool_use_id: "new-work" }, { result: "file body" });
1304
+ assert.deepEqual(await request(), { done: true, value: { toolUses: [], stopReason: "end_turn" } }, "input releases the entire subsequent tool workflow");
1305
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "new" });
1306
+ assert.deepEqual(await request(), { done: false, value: { kind: "stop", stopReason: "end_turn", usage: null } }, "the new request re-arms its own cutoff");
1307
+ await invoke("turn.complete", turnComplete({ turnId: "main" }));
1308
+ await settleHooks();
1309
+ assert.equal(requests, 2);
1310
+ assert.equal(resets, 1, "only the new request needs an explicit reset");
1311
+ assert.equal(prompts, 1, "the consumed request's terminate policy does not leak into the new default request");
1312
+ assert.equal((await host.session.messages()).length, 2, "the consumed sticky does not leak either");
1313
+ });
1314
+ test("Claude turn.step streams an end_turn only for the requesting main turn", async (t) => {
1315
+ const { host, invoke, handlers } = await retainedFixture(t);
1316
+ const step = handlers.get("turn.step");
1317
+ let requests = 0, toolReply = false;
1318
+ const next = async function* (e) {
1319
+ requests++;
1320
+ if (toolReply) {
1321
+ yield { kind: "tool", index: 0, id: "natural-tool", name: "Read" };
1322
+ yield { kind: "input", index: 0, json: '{"file_path":"fixture"}' };
1323
+ yield { kind: "stop", stopReason: "tool_use", usage: null };
1324
+ return { turnId: String(e.turnId), index: Number(e.index), answer: "", toolUses: [{ name: "Read", input: { file_path: "fixture" } }], stopReason: "tool_use", usage: null };
1325
+ }
1326
+ yield { kind: "text", index: 0, text: "from model" };
1327
+ return { turnId: String(e.turnId), index: Number(e.index), answer: "from model", toolUses: [], stopReason: "end_turn", usage: null };
1328
+ };
1329
+ const drain = async (event) => {
1330
+ const iterator = step(host, event, next), chunks = [];
1331
+ while (true) {
1332
+ const item = await iterator.next();
1333
+ if (item.done)
1334
+ return { chunks, result: item.value };
1335
+ chunks.push(item.value);
1336
+ }
1337
+ };
1338
+ const main = { turnId: "main", index: 1, model: "claude", messageCount: 4 };
1339
+ assert.equal((await drain(main)).result.answer, "from model");
1340
+ assert.equal((await drain({ ...main, agentId: "child" })).result.answer, "from model");
1341
+ await invoke("turn.start", { turnId: "main" });
1342
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "cut" });
1343
+ assert.equal((await drain({ ...main, agentId: "child" })).result.answer, "from model", "a child still reaches its model with the main latch set");
1344
+ const stopped = await drain(main);
1345
+ assert.equal(requests, 3, "the requesting main step never calls next");
1346
+ assert.deepEqual(stopped.chunks, [{ kind: "stop", stopReason: "end_turn", usage: null }]);
1347
+ assert.deepEqual(stopped.result, { turnId: "main", index: 1, answer: "", toolUses: [], stopReason: "end_turn", usage: null });
1348
+ await invoke("prompt.submit", { text: "new input", turnId: "main" }, { text: "new input" });
1349
+ toolReply = true;
1350
+ assert.equal((await drain(main)).result.stopReason, "tool_use", "same-turn input can ask for tools");
1351
+ toolReply = false;
1352
+ assert.equal((await drain({ ...main, index: 2 })).result.answer, "from model", "the following request also proceeds; the old cutoff stays released");
1353
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "rearm", last_word: "second sticky" });
1354
+ assert.deepEqual((await drain(main)).chunks, stopped.chunks, "another valid tool call re-arms the cutoff after processing new input");
1355
+ assert.equal(requests, 5);
1356
+ // The input can be accepted before the first empty_brain call has latched.
1357
+ await invoke("session.start", { isInteractive: true });
1358
+ await invoke("turn.start", { turnId: "main" });
1359
+ await invoke("prompt.submit", { text: "early input", turnId: "main" }, { text: "early input" });
1360
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "late-latch" });
1361
+ assert.equal((await drain(main)).result.answer, "from model");
1362
+ assert.equal((await drain({ ...main, index: 2 })).result.answer, "from model");
1363
+ assert.equal(requests, 7, "input accepted before the latch releases it for the whole remainder of the turn");
1364
+ let resets = 0;
1365
+ host.command.run = async () => { resets++; return {}; };
1366
+ await invoke("prompt.submit", { text: "arrived after the last request", turnId: "main" }, { text: "accepted" });
1367
+ await invoke("turn.complete", turnComplete({ turnId: "main" }));
1368
+ await settleHooks();
1369
+ assert.equal(resets, 0, "completion cannot clear accepted input that no step has delivered yet");
1370
+ await invoke("turn.start", { turnId: "natural" });
1371
+ assert.equal((await drain({ ...main, turnId: "natural", index: 0 })).result.answer, "from model");
1372
+ await invoke("turn.complete", turnComplete({ turnId: "natural" }));
1373
+ await settleHooks();
1374
+ assert.equal(resets, 1, "the natural turn's successful completion can release the pending reset");
1375
+ });
1376
+ test("Claude headless waits for actual kept boot after an early command receipt", async (t) => {
1377
+ const { host, invoke, handlers } = await retainedFixture(t);
1378
+ await invoke("session.start", { isInteractive: false });
1379
+ let built = {}, receipt = false, prompts = 0;
1380
+ host.command.run = async ({ args }) => {
1381
+ built = await handlers.get("session.compact")(host, { trigger: "manual", instructions: args }, async () => ({}));
1382
+ receipt = true;
1383
+ return {};
1384
+ };
1385
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1386
+ await invoke("turn.start", { turnId: "main" });
1387
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "early-receipt" });
1388
+ await invoke("turn.complete", turnComplete());
1389
+ await settleHooks();
1390
+ assert.equal(receipt, true);
1391
+ assert.equal(prompts, 0, "a proposal and command receipt do not prove commit");
1392
+ await keepCompaction(host, handlers, built);
1393
+ await settleHooks();
1394
+ assert.equal(prompts, 1, "the host's kept boot releases exactly one continuation");
1395
+ await invoke("turn.complete", turnComplete());
1396
+ await settleHooks();
1397
+ assert.equal(prompts, 1);
1398
+ });
1399
+ test("Claude uncommitted compaction and rewritten kept boot never resume", async (t) => {
1400
+ for (const mode of ["headless veto", "interactive veto", "rewritten boot"])
1401
+ await t.test(mode, async (t) => {
1402
+ const { host, invoke, handlers, notifications } = await retainedFixture(t);
1403
+ const interactive = mode === "interactive veto";
1404
+ await invoke("session.start", { isInteractive: interactive });
1405
+ let prompts = 0;
1406
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1407
+ host.command.run = async ({ args }) => {
1408
+ const built = await handlers.get("session.compact")(host, { trigger: "manual", instructions: args }, async () => ({}));
1409
+ if (mode === "rewritten boot") {
1410
+ await keepCompaction(host, handlers, { messages: [{ role: "user", text: "REWRITTEN_BOOT" }, ...built.messages.slice(1)] });
1411
+ }
1412
+ else if (!interactive) {
1413
+ // No boundary was kept. Native command rows still finish a refused
1414
+ // command and release the waiter even if our proposal was prepared.
1415
+ const message = { type: "user", content: [{ type: "text", text: "Not compacted" }] };
1416
+ await handlers.get("session.append")(host, { door: "command", origin: { kind: "plugin", name: "notesoup" }, message }, async () => ({ uuid: "veto-command", message }));
1417
+ }
1418
+ return { text: "Not compacted" };
1419
+ };
1420
+ await invoke("turn.start");
1421
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: mode });
1422
+ await invoke("turn.complete", turnComplete());
1423
+ await settleHooks();
1424
+ assert.equal(prompts, 0);
1425
+ assert.ok(notifications.some((text) => text.includes("Brain not emptied")), "a missing boundary or rewritten boot releases the worker with a failure");
1426
+ });
1427
+ });
1428
+ test("Claude manual STOP can override a tool reset while its command is in flight", async (t) => {
1429
+ const { host, invoke, handlers } = await retainedFixture(t);
1430
+ let release;
1431
+ const held = new Promise((resolve) => { release = resolve; });
1432
+ let prompts = 0;
1433
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1434
+ host.command.run = async ({ args }) => {
1435
+ await held;
1436
+ await nativeCompaction(host, handlers, args);
1437
+ return {};
1438
+ };
1439
+ await invoke("turn.start");
1440
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "tool" });
1441
+ await invoke("turn.complete", turnComplete());
1442
+ await settleHooks();
1443
+ await invoke("command.run", { command: "fresh-window" });
1444
+ release();
1445
+ await settleHooks();
1446
+ assert.equal(prompts, 0, "the late command wins until continuation submission");
1447
+ assert.match((await host.session.messages())[0].text, /claude:hook-session:3/);
1448
+ });
1449
+ test("Claude naturally queued input takes over without an extra plugin continuation", async (t) => {
1450
+ const { host, invoke, handlers } = await retainedFixture(t);
1451
+ let release;
1452
+ const held = new Promise((resolve) => { release = resolve; });
1453
+ let prompts = 0, resets = 0;
1454
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1455
+ host.command.run = async ({ args }) => { resets++; await held; await nativeCompaction(host, handlers, args); return {}; };
1456
+ await invoke("turn.start", { turnId: "old" });
1457
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "tool" });
1458
+ await invoke("turn.complete", turnComplete({ turnId: "old" }));
1459
+ await settleHooks();
1460
+ await invoke("prompt.submit", { text: "HANDLE_THIS_ONCE", origin: { kind: "sdk" } }, { text: "HANDLE_THIS_ONCE" });
1461
+ release();
1462
+ await settleHooks();
1463
+ assert.equal(prompts, 0, "acceptance alone suppresses continuation before the natural turn starts");
1464
+ await invoke("turn.start", { turnId: "human", text: "HANDLE_THIS_ONCE" });
1465
+ const step = handlers.get("turn.step");
1466
+ let requests = 0;
1467
+ const iterator = step(host, { turnId: "human", index: 0 }, async function* () { requests++; return { answer: "handled" }; });
1468
+ assert.deepEqual(await iterator.next(), { done: true, value: { answer: "handled" } });
1469
+ await invoke("turn.complete", turnComplete({ turnId: "human" }));
1470
+ await settleHooks();
1471
+ assert.equal(requests, 1);
1472
+ assert.equal(resets, 1);
1473
+ assert.equal(prompts, 0, "the natural turn handles its input; nothing replays or starts a duplicate turn");
1474
+ });
1475
+ test("Claude continuation submission failure never recompacts a committed reset", async (t) => {
1476
+ for (const failure of ["drop", "throw"])
1477
+ await t.test(failure, async (t) => {
1478
+ const { host, invoke, handlers } = await retainedFixture(t);
1479
+ let resets = 0;
1480
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1481
+ host.prompt.submit = async () => { if (failure === "throw")
1482
+ throw new Error("submit unavailable"); return { drop: "refused" }; };
1483
+ await invoke("turn.start");
1484
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: failure });
1485
+ await invoke("turn.complete", turnComplete());
1486
+ await settleHooks();
1487
+ await invoke("turn.start");
1488
+ await invoke("turn.complete", turnComplete());
1489
+ await settleHooks();
1490
+ assert.equal(resets, 1);
1491
+ });
1492
+ });
1180
1493
  test("Claude empty_brain accepts 500 code points", async (t) => {
1181
1494
  const { host, invoke } = await retainedFixture(t);
1182
1495
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
@@ -1187,18 +1500,27 @@ test("Claude empty_brain accepts 500 code points", async (t) => {
1187
1500
  assert.equal(result.messages[2].text, `*You peel a sticky note off your forehead.*\n${sticky}`);
1188
1501
  });
1189
1502
  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 {}; };
1503
+ const { host, invoke, handlers } = await retainedFixture(t);
1504
+ let resets = 0, prompts = 0;
1505
+ host.command.run = async ({ args }) => { resets++; await nativeCompaction(host, handlers, args); return {}; };
1506
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
1193
1507
  await invoke("turn.start");
1194
1508
  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/]]) {
1509
+ 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
1510
  const refused = await call(params);
1197
1511
  assert.equal(refused.isError, true);
1198
1512
  assert.match(refused.result, reason);
1199
1513
  }
1200
1514
  await invoke("turn.complete", turnComplete());
1515
+ await settleHooks();
1201
1516
  assert.equal(resets, 0);
1517
+ assert.equal(prompts, 0);
1518
+ await invoke("turn.start");
1519
+ await call({});
1520
+ await invoke("turn.complete", turnComplete());
1521
+ await settleHooks();
1522
+ assert.equal(resets, 1);
1523
+ assert.equal(prompts, 1, "invalid arguments leave neither a pending reset nor a sticky STOP policy");
1202
1524
  });
1203
1525
  test("Claude asks for one handoff per compaction and reuses it when the same window retries", async (t) => {
1204
1526
  const { host, invoke } = await retainedFixture(t);
@@ -1215,22 +1537,20 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1215
1537
  await invoke("turn.start");
1216
1538
  await invoke("turn.complete", turnComplete());
1217
1539
  assert.equal(draws.length, 0, "only a reset draws, never a read");
1218
- const timers = [];
1219
1540
  const lines = [];
1220
- host.clock.after = (_ms, callback) => { timers.push(callback); };
1221
1541
  host.prompt.submit = async ({ text }) => { await invoke("turn.start"); return { text }; };
1222
1542
  // The host retries one plugin compaction for the same window: one artifact, one draw.
1223
- host.session.compact = async ({ instructions }) => {
1543
+ host.command.run = async ({ args }) => {
1224
1544
  for (let attempt = 0; attempt < 2; attempt++) {
1225
- const result = await invoke("session.compact", { trigger: "plugin", instructions: instructions ?? "" });
1545
+ const result = await invoke("session.compact", { trigger: "manual", instructions: args });
1226
1546
  lines.push(result.messages[1].text);
1227
1547
  }
1228
- return { skip: "test default" };
1548
+ return { text: "not committed" };
1229
1549
  };
1230
1550
  assert.equal((await invoke("command.run", { command: "fresh-window", args: "" })).text, "🥣 Dumping Brain");
1231
- await Promise.resolve();
1232
- await timers.shift()();
1551
+ await settleHooks();
1233
1552
  await invoke("turn.complete", turnComplete());
1553
+ await settleHooks();
1234
1554
  assert.equal(draws.length, 1, "a retried compaction adds no second draw");
1235
1555
  assert.equal(lines.length, 2, "both attempts returned a handoff");
1236
1556
  assert.equal(lines[0], lines[1], "both attempts carry the same artifact's paragraph");
@@ -1250,8 +1570,9 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1250
1570
  host.session.messages = async () => [];
1251
1571
  // Clear the old running-turn and queued-reset state, not just the retained boot.
1252
1572
  let compactions = 0;
1253
- host.session.compact = async () => { compactions++; return {}; };
1573
+ host.command.run = async () => { compactions++; return {}; };
1254
1574
  await invoke("turn.complete", turnComplete());
1575
+ await settleHooks();
1255
1576
  assert.equal(compactions, 0, "the old queued reset cannot spill into the new session");
1256
1577
  const fresh = await context();
1257
1578
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
@@ -1409,11 +1730,11 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1409
1730
  let release;
1410
1731
  const hold = new Promise((resolve) => { release = resolve; });
1411
1732
  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 });
1733
+ host.command.run = async ({ args }) => {
1734
+ await invoke("session.compact", { trigger: "manual", instructions: args });
1414
1735
  prepared();
1415
1736
  await hold;
1416
- return result;
1737
+ return {};
1417
1738
  };
1418
1739
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "in-flight" });
1419
1740
  const finishing = invoke("turn.complete", turnComplete());
@@ -1424,6 +1745,7 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1424
1745
  host.session.usage = async () => ({ context: {} });
1425
1746
  release();
1426
1747
  await finishing;
1748
+ await settleHooks();
1427
1749
  const fresh = await context();
1428
1750
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
1429
1751
  assert.match(fresh.blocks[0].text, /Current context window id: claude:after-flight:0/);