notesoup 0.58.0 → 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
  }
@@ -66,7 +87,7 @@ function fakeEngine(home) {
66
87
  settings: { read: async () => ({}) },
67
88
  command: { run: async () => ({}), register: async (spec) => ({ command: spec.name }) },
68
89
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
69
- prompt: { submit: async () => undefined },
90
+ prompt: { submit: async ({ text }) => ({ text }) },
70
91
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
71
92
  ui: { toast: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
72
93
  process: { run: async (argv, init) => ({
@@ -237,7 +258,17 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
237
258
  assert.equal(percent.source, "percent");
238
259
  assert.equal(percent.unit, "percent");
239
260
  assert.ok(Math.abs(percent.native - 83.5) < 1e-9 && Math.abs(percent.reset - 79.404) < 1e-9 && Math.abs(percent.warn - 71.212) < 1e-9, "83.5 / 79.4 / 71.2 on 200K");
240
- assert.equal(limitPoints({ env: { pctOverride: "50" } }).native, 50);
261
+ for (const facts of [
262
+ { env: { pctOverride: "50" } },
263
+ { settings: { autoCompactEnabled: false }, env: { pctOverride: "10" } },
264
+ { settings: { autoCompactWindow: 100_000 } },
265
+ ]) {
266
+ const fallback = resolveClaudeLimits(facts);
267
+ const tokens = resolveClaudeLimits({ ...facts, usage: { window: 200_000 } });
268
+ for (const point of ["native", "reset", "warn"])
269
+ assert.ok(Math.abs(fallback[point] - tokens[point] / 200_000 * 100) < 1e-9, `${point}: percent fallback uses the same token derivation`);
270
+ assert.equal(fallback.autoCompact, tokens.autoCompact);
271
+ }
241
272
  // A real window is never re-expressed on the assumed 200K window, and no point is zero:
242
273
  // the mod treats `measured >= reset` as due, so a zero point would clear memory every turn.
243
274
  const tiny = limitPoints({ usage: { window: 8_000 } });
@@ -491,6 +522,13 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
491
522
  assert.ok(spec.description.length > 20);
492
523
  assert.equal(spec.inputSchema.type, "object");
493
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);
494
532
  const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "hook-1", ...params }, async (event) => event);
495
533
  const written = await call("notes_write", { address: "hook.md", content: "hook body" });
496
534
  assert.equal(written.result, "created hook.md | pinned false | budget 2048 | readonly false", "the hook hands back the shared text unchanged");
@@ -523,12 +561,12 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
523
561
  let kept = [];
524
562
  const measured = () => ({ context: { tokens, window: 200_000, percent: tokens === undefined ? undefined : (tokens / 200_000) * 100 } });
525
563
  host.session.usage = async () => measured();
526
- host.session.compact = async ({ instructions }) => {
564
+ host.command.run = async ({ args }) => {
527
565
  compactions++;
528
- 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);
529
567
  kept = result.messages;
530
568
  tokens = undefined; // The real engine invalidates token usage after compact.
531
- return result;
569
+ return {};
532
570
  };
533
571
  await invoke("session.start", { cwd: home, isInteractive: true });
534
572
  assert.equal(registered.length, 8);
@@ -560,6 +598,7 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
560
598
  await invoke("turn.start");
561
599
  await invoke("command.run", { command: "empty" });
562
600
  await invoke("turn.complete", turnComplete());
601
+ await settleHooks();
563
602
  assert.equal(compactions, 1);
564
603
  assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
565
604
  assert.equal(kept[0].role, "user");
@@ -582,15 +621,17 @@ test("Claude Mod preserves context and cancels a queued reset after an unsuccess
582
621
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
583
622
  const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
584
623
  let compactions = 0;
585
- host.session.compact = async () => { compactions++; return { skip: "reset must not run" }; };
624
+ host.command.run = async () => { compactions++; return { text: "reset must not run" }; };
586
625
  await invoke("session.start", { cwd: home, isInteractive: true });
587
626
  await invoke("turn.start");
588
627
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: `reset-${reason}`, last_word: "DO_NOT_KEEP" });
589
628
  await invoke("turn.complete", turnComplete({ reason }));
629
+ await settleHooks();
590
630
  assert.equal(compactions, 0, `${reason} never submits the queued reset`);
591
631
  assert.ok(notifications.some(text => text.includes("cancelled") && text.includes(reason)), `${reason} reports that its request was cancelled`);
592
632
  await invoke("turn.start");
593
633
  await invoke("turn.complete", turnComplete());
634
+ await settleHooks();
594
635
  assert.equal(compactions, 0, `${reason} leaves no pending reset for a later successful turn`);
595
636
  });
596
637
  }
@@ -619,31 +660,34 @@ test("Claude headless resets through its own manual command, retries failure and
619
660
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
620
661
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", last_word: "STICKY", tool_use_id: "reset" });
621
662
  await invoke("turn.complete", turnComplete());
663
+ await settleHooks();
622
664
  assert.equal(attempts, 1);
623
665
  assert.ok(notifications.some(x => x.includes("command unavailable")));
624
666
  reject = false;
625
667
  await invoke("turn.complete", turnComplete());
668
+ await settleHooks();
626
669
  assert.equal(attempts, 2, "failed requests remain pending");
627
670
  assert.ok(notifications.some(x => x.includes("Brain not emptied")));
628
- // Core dispatches the admitted manual event within our command hook.
629
- 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 }) => {
630
673
  attempts++;
631
- 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" });
632
676
  assert.match(JSON.stringify(user), /use \/fresh-window/, "a pending reset does not admit the user's command");
633
- await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
634
- kept = (await invoke("session.compact", { trigger: "manual" })).messages;
635
- return {};
636
- });
677
+ kept = (await nativeCompaction(host, handlers, args)).messages;
637
678
  return {};
638
679
  };
639
680
  await invoke("turn.complete", turnComplete());
681
+ await settleHooks();
640
682
  assert.match(kept[0].text, /claude:hook-session:1/);
641
683
  assert.equal(kept[2].text, "*You peel a sticky note off your forehead.*\nSTICKY");
642
684
  await invoke("turn.complete", turnComplete());
685
+ await settleHooks();
643
686
  assert.equal(attempts, 3, "success clears pending exactly once");
644
687
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
645
688
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "reset2" });
646
689
  await invoke("turn.complete", turnComplete());
690
+ await settleHooks();
647
691
  assert.match(kept[0].text, /claude:hook-session:2/);
648
692
  assert.equal(kept.length, 2, "sticky is consumed once");
649
693
  });
@@ -656,18 +700,13 @@ test("Claude headless warns without proactive resets and supports both manual al
656
700
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
657
701
  let tokens = CLAUDE_200K.warn;
658
702
  let attempts = 0, prompts = 0;
659
- const timers = [];
660
703
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
661
- host.clock.after = (_ms, callback) => { timers.push(callback); };
662
- host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); };
663
- host.command.run = async ({ command }) => {
704
+ host.prompt.submit = async ({ text }) => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); return { text }; };
705
+ host.command.run = async ({ args }) => {
664
706
  attempts++;
665
- await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
666
- const result = await invoke("session.compact", { trigger: "manual" });
667
- assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
668
- tokens = undefined;
669
- return {};
670
- });
707
+ const result = await nativeCompaction(host, handlers, args);
708
+ assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
709
+ tokens = undefined;
671
710
  return {};
672
711
  };
673
712
  await invoke("session.start", { cwd: home, isInteractive: false });
@@ -680,20 +719,14 @@ test("Claude headless warns without proactive resets and supports both manual al
680
719
  assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
681
720
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
682
721
  await invoke("turn.complete", turnComplete());
722
+ await settleHooks();
683
723
  assert.equal(attempts, 1);
684
724
  for (const command of ["empty", "fresh-window"]) {
685
725
  assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
686
- await Promise.resolve();
687
- await timers.shift()();
726
+ await settleHooks();
688
727
  }
689
728
  assert.equal(attempts, 3);
690
- assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
691
- host.prompt.submit = async () => { throw new Error("close-out unavailable"); };
692
- await invoke("command.run", { command: "empty" });
693
- await Promise.resolve();
694
- await timers.shift()();
695
- await invoke("turn.complete", turnComplete());
696
- assert.equal(attempts, 4, "a failed close-out also leaves the reset pending");
729
+ assert.equal(prompts, 3, "one tool continuation and one close-out for each idle alias");
697
730
  });
698
731
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
699
732
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -731,15 +764,20 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
731
764
  };
732
765
  host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
733
766
  let result = {};
734
- 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
+ };
735
771
  await invoke("turn.start");
736
772
  await invoke("command.run", { command: "empty" });
737
773
  await invoke("turn.complete", turnComplete());
774
+ await settleHooks();
738
775
  assert.match(result.skip, /notes didn't load/);
739
776
  assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
740
777
  failBoot = false;
741
778
  await invoke("turn.start");
742
779
  await invoke("turn.complete", turnComplete());
780
+ await settleHooks();
743
781
  assert.equal(result.skip, undefined);
744
782
  assert.equal(result.messages.length, 2);
745
783
  assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
@@ -753,39 +791,35 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
753
791
  host.command.register = async (spec) => { commands.push(spec.name); return { command: spec.name }; };
754
792
  let handlers = new Map();
755
793
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
756
- const timers = [];
757
794
  const prompts = [];
758
795
  let kept = [];
759
796
  let compactions = 0;
760
- host.clock.after = (_ms, callback) => { timers.push(callback); };
761
- host.session.compact = async ({ instructions }) => {
797
+ host.command.run = async ({ args }) => {
762
798
  compactions++;
763
- const result = await invoke("session.compact", { trigger: "plugin", instructions });
764
- kept = result.messages;
765
- return result;
799
+ kept = (await nativeCompaction(host, handlers, args)).messages;
800
+ return {};
766
801
  };
767
802
  host.prompt.submit = async ({ text }) => {
768
803
  prompts.push(text);
769
- 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 });
770
806
  await invoke("turn.complete", turnComplete());
807
+ return { text };
771
808
  };
772
809
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
773
810
  await invoke("session.start", { cwd: home, isInteractive: true });
774
811
  assert.deepEqual(commands.sort(), ["empty", "fresh-window"], "only the new short name and the retained alias are registered");
775
812
  assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
776
- assert.equal(timers.length, 0);
813
+ assert.equal(compactions, 0);
777
814
  const command = await invoke("command.run", { command: "empty" });
778
815
  assert.equal(command.text, "🥣 Dumping Brain");
779
- await Promise.resolve();
780
- assert.equal(compactions, 0, "command.run must not call compact under its held turn");
781
- assert.equal(timers.length, 1);
782
- await timers.shift()();
816
+ await settleHooks();
783
817
  assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
784
818
  assert.equal(prompts[0], CLAUDE_WARNING_PROMPT, "the close-out is the same warning text the automatic path shows");
785
819
  assert.equal(compactions, 1);
786
820
  assert.equal(kept.length, 2);
787
821
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
788
- 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");
789
823
  host.session.messages = async () => [{ role: "user", text: "OLD_SECRET" }, ...kept];
790
824
  handlers = new Map();
791
825
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
@@ -794,9 +828,51 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
794
828
  await invoke("turn.start");
795
829
  await invoke("command.run", { command: "empty" });
796
830
  await invoke("turn.complete", turnComplete());
831
+ await settleHooks();
797
832
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
798
833
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
799
834
  });
835
+ test("Claude failed close-outs release the request so manual reset can retry", async (t) => {
836
+ for (const failure of ["texts", "submit", "drop"])
837
+ await t.test(failure, async (t) => {
838
+ const home = mkdtempSync(join(tmpdir(), "claude-closeout-retry-"));
839
+ t.after(() => rmSync(home, { recursive: true, force: true }));
840
+ const { host, notifications } = fakeEngine(home);
841
+ const helper = host.process.run;
842
+ let failing = true, resets = 0;
843
+ host.process.run = async (argv, init) => failing && failure === "texts" && JSON.parse(init.stdin).op === "texts"
844
+ ? { exitCode: 1, stdout: "" } : helper(argv, init);
845
+ const handlers = new Map();
846
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
847
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
848
+ host.prompt.submit = async ({ text }) => {
849
+ if (failing && failure === "submit")
850
+ throw new Error("submission unavailable");
851
+ if (failing && failure === "drop")
852
+ return { drop: "another plugin refused" };
853
+ await invoke("turn.start");
854
+ await invoke("turn.complete", turnComplete());
855
+ return { text };
856
+ };
857
+ host.command.run = async ({ args }) => {
858
+ resets++;
859
+ await nativeCompaction(host, handlers, args);
860
+ return {};
861
+ };
862
+ await invoke("session.start", { isInteractive: true });
863
+ await invoke("command.run", { command: "fresh-window" });
864
+ await settleHooks();
865
+ assert.equal(resets, 0);
866
+ assert.ok(notifications.some(text => text.includes("close-out")), "failure is visible");
867
+ await invoke("turn.start");
868
+ await invoke("turn.complete", turnComplete());
869
+ assert.equal(resets, 0, "a failed close-out must not spring a reset on an unrelated turn");
870
+ failing = false;
871
+ assert.deepEqual(await invoke("command.run", { command: "fresh-window" }), { text: "🥣 Dumping Brain" });
872
+ await settleHooks();
873
+ assert.equal(resets, 1);
874
+ });
875
+ });
800
876
  test("Claude Mod delivers one warning per window through main tools or prompt submission, never boot", async (t) => {
801
877
  const { host, invoke, context } = await retainedFixture(t);
802
878
  const texts = await dispatch({ op: "texts" });
@@ -844,18 +920,53 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
844
920
  return run(argv, init);
845
921
  };
846
922
  let resets = 0;
847
- host.session.compact = async () => { resets++; return {}; };
923
+ host.command.run = async () => { resets++; return {}; };
848
924
  const submit = () => invoke("prompt.submit", { text: "continue" }, {}, async (e) => e);
849
925
  assert.equal((await submit()).context, undefined);
850
926
  tokens++;
851
927
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
852
928
  assert.equal((await submit()).context, undefined, "one warning per window");
853
929
  await invoke("turn.complete", turnComplete());
930
+ await settleHooks();
854
931
  assert.equal(resets, 0, "warning and turn completion never proactively clear");
855
932
  assert.equal((await invoke("session.compact", { trigger: "auto" })).messages.length, 2);
856
933
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
857
934
  }
858
935
  });
936
+ test("Claude warning limits follow live model, threshold and settings changes without re-resolving for fill", async (t) => {
937
+ const home = mkdtempSync(join(tmpdir(), "claude-live-limits-"));
938
+ t.after(() => rmSync(home, { recursive: true, force: true }));
939
+ const { host } = fakeEngine(home);
940
+ let model = "claude-a", threshold = 167_000, tokens = 10_000;
941
+ const settings = { notesoup: { warningRunwayTokens: WARNING_RUNWAY_TOKENS } };
942
+ host.session.model = async () => model;
943
+ host.session.usage = async () => ({ context: { tokens, window: 200_000, breakdown: { model, autoCompactThreshold: threshold } } });
944
+ host.settings.read = async () => settings;
945
+ const helper = host.process.run;
946
+ let resolutions = 0;
947
+ host.process.run = async (argv, init) => {
948
+ if (JSON.parse(init.stdin).op === "limits")
949
+ resolutions++;
950
+ return helper(argv, init);
951
+ };
952
+ const handlers = new Map();
953
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
954
+ await handlers.get("session.start")(host, { isInteractive: true }, async (e) => e);
955
+ const submit = () => handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
956
+ assert.equal((await submit()).context, undefined);
957
+ tokens = 30_000;
958
+ assert.equal((await submit()).context, undefined);
959
+ assert.equal(resolutions, 1, "changing fill reuses the points");
960
+ model = "claude-b";
961
+ assert.equal((await submit()).context, undefined);
962
+ assert.equal(resolutions, 2, "a model change invalidates points even at the same capacity");
963
+ threshold = 67_000;
964
+ assert.equal((await submit()).context, undefined);
965
+ assert.equal(resolutions, 3, "a live threshold change invalidates points without a model change");
966
+ settings.notesoup.warningRunwayTokens = 30_000;
967
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
968
+ assert.equal(resolutions, 4, "settings changes apply without a session or capacity change");
969
+ });
859
970
  test("Claude Mod consumes a warning only after an accepted delivery and ignores stale generations", async (t) => {
860
971
  const { host, invoke } = await retainedFixture(t);
861
972
  const texts = await dispatch({ op: "texts" });
@@ -898,7 +1009,7 @@ test("Claude Mod keeps warning timing when auto-compact is off without clearing
898
1009
  let tokens = 155_423;
899
1010
  let compactions = 0;
900
1011
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
901
- 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 {}; };
902
1013
  await invoke("session.start", { cwd: home, isInteractive: true });
903
1014
  await invoke("turn.start");
904
1015
  await invoke("turn.complete", turnComplete());
@@ -918,14 +1029,14 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
918
1029
  t.after(() => rmSync(home, { recursive: true, force: true }));
919
1030
  const { host, notifications } = fakeEngine(home);
920
1031
  host.env = { get: async (name) => name === "NOTESOUP_HOME" ? home : name === "DISABLE_COMPACT" ? "1" : undefined };
921
- const timers = [];
922
- host.clock.after = (_ms, callback) => { timers.push(callback); };
1032
+ let prompts = 0;
1033
+ host.prompt.submit = async ({ text }) => { prompts++; return { text }; };
923
1034
  const handlers = new Map();
924
1035
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
925
1036
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
926
1037
  let compactions = 0;
927
1038
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
928
- host.session.compact = async () => { compactions++; return {}; };
1039
+ host.command.run = async () => { compactions++; return {}; };
929
1040
  await invoke("session.start", { cwd: home, isInteractive: true });
930
1041
  assert.equal(notifications.length, 1, "one startup line");
931
1042
  assert.match(notifications[0], /DISABLE_COMPACT/);
@@ -934,9 +1045,10 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
934
1045
  const tool = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "disabled-compact" });
935
1046
  assert.equal(tool.isError, true);
936
1047
  assert.match(tool.result, /DISABLE_COMPACT/);
937
- assert.equal(timers.length, 0, "no close-out turn is queued");
938
1048
  await invoke("turn.start");
939
1049
  await invoke("turn.complete", turnComplete());
1050
+ await settleHooks();
1051
+ assert.equal(prompts, 0, "no close-out turn is queued");
940
1052
  assert.equal(compactions, 0, "disabled reset requests never run");
941
1053
  assert.equal(notifications.length, 1, "detection logs once, not per turn");
942
1054
  const upstream = { result: "upstream", context: ["other plugin"] };
@@ -952,10 +1064,11 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
952
1064
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
953
1065
  let compactions = 0;
954
1066
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
955
- host.session.compact = async () => { compactions++; return {}; };
1067
+ host.command.run = async () => { compactions++; return {}; };
956
1068
  await invoke("session.start", { cwd: home, isInteractive: true });
957
1069
  await invoke("turn.start");
958
1070
  await invoke("turn.complete", turnComplete());
1071
+ await settleHooks();
959
1072
  await invoke("tool.call", { tool: "Read" });
960
1073
  assert.equal(compactions, 0, "an unresolvable point never resets");
961
1074
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
@@ -977,7 +1090,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
977
1090
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
978
1091
  let compactions = 0;
979
1092
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
980
- 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 {}; };
981
1094
  await invoke("session.start", { cwd: home, isInteractive: true });
982
1095
  await invoke("turn.start");
983
1096
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
@@ -985,6 +1098,7 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
985
1098
  await invoke("turn.complete", turnComplete({ agentId: "sub-1" }));
986
1099
  assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
987
1100
  await invoke("turn.complete", turnComplete());
1101
+ await settleHooks();
988
1102
  assert.equal(compactions, 1, "the main turn still resets at its own end");
989
1103
  });
990
1104
  test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
@@ -997,12 +1111,13 @@ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
997
1111
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
998
1112
  let compactions = 0;
999
1113
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1000
- 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 {}; };
1001
1115
  await invoke("session.start", { cwd: home, isInteractive: true });
1002
1116
  assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
1003
1117
  await invoke("turn.start");
1004
1118
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
1005
1119
  await invoke("turn.complete", turnComplete());
1120
+ await settleHooks();
1006
1121
  assert.equal(compactions, 1, "the explicit reset still runs");
1007
1122
  });
1008
1123
  test("Claude Mod retries an unresolvable warning threshold inside the same window", async (t) => {
@@ -1022,7 +1137,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1022
1137
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1023
1138
  let compactions = 0;
1024
1139
  host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1025
- 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 {}; };
1026
1141
  await invoke("session.start", { cwd: home, isInteractive: true });
1027
1142
  await invoke("turn.start");
1028
1143
  await invoke("turn.complete", turnComplete());
@@ -1040,7 +1155,7 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
1040
1155
  async function retainedFixture(t) {
1041
1156
  const home = mkdtempSync(join(tmpdir(), "claude-lifecycle-"));
1042
1157
  t.after(() => rmSync(home, { recursive: true, force: true }));
1043
- const { host } = fakeEngine(home);
1158
+ const { host, notifications } = fakeEngine(home);
1044
1159
  const boot = await dispatch({ op: "boot", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, window: 2, tools: {
1045
1160
  notes: "mcp__notesoup__notes_*", notesList: "mcp__notesoup__notes_list",
1046
1161
  history: "unavailable", remaining: "unavailable", wipe: "/fresh-window",
@@ -1052,10 +1167,10 @@ async function retainedFixture(t) {
1052
1167
  const context = async () => await invoke("prompt.context", {}, { blocks: [] });
1053
1168
  await invoke("session.start", { cwd: home, isInteractive: true });
1054
1169
  assert.deepEqual((await context()).blocks, [], "the existing boot is retained, not injected twice");
1055
- return { home, host, invoke, context, boot };
1170
+ return { home, host, invoke, context, boot, handlers, notifications };
1056
1171
  }
1057
- test("Claude empty_brain defers until main turn completion, carries last_word, and clears the request", async (t) => {
1058
- 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);
1059
1174
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
1060
1175
  const resets = [];
1061
1176
  const origins = [];
@@ -1066,33 +1181,315 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
1066
1181
  origins.push(request.origin);
1067
1182
  return run(argv, init);
1068
1183
  };
1069
- host.session.compact = async () => {
1070
- 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);
1071
1188
  resets.push(result);
1072
- return result;
1189
+ return {};
1073
1190
  };
1074
1191
  await invoke("turn.start");
1075
1192
  const call = (params = {}) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "wipe", ...params });
1076
1193
  const accepted = await call({ last_word: " next move: test " });
1077
1194
  assert.equal(accepted.isError, undefined);
1078
- assert.match(accepted.result, /End your turn now/);
1195
+ assert.match(accepted.result, /tool batch will finish/);
1079
1196
  await call({ last_word: "must not replace the first request" });
1080
1197
  await invoke("turn.complete", turnComplete({ agentId: "child" }));
1081
1198
  assert.equal(resets.length, 0, "neither tool execution nor a child completion resets a running main turn");
1082
1199
  await invoke("turn.complete", turnComplete());
1200
+ await settleHooks();
1083
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");
1084
1203
  assert.deepEqual(origins, ["normal"]);
1085
1204
  assert.ok(NORMAL_CONTINUATIONS.includes(resets[0].messages[1].text));
1086
1205
  assert.deepEqual(resets[0].messages.slice(2).map((row) => row.text), ["*You peel a sticky note off your forehead.*\nnext move: test"]);
1087
1206
  assert.match(resets[0].messages[0].text, /mcp__notesoup__empty_brain/);
1088
1207
  await invoke("turn.start");
1089
1208
  await invoke("turn.complete", turnComplete());
1209
+ await settleHooks();
1090
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");
1091
1212
  const forced = await invoke("session.compact", { trigger: "auto" });
1092
1213
  assert.deepEqual(origins, ["normal", "forced"]);
1093
1214
  assert.equal(forced.messages.length, 2, "the sticky note does not leak into the next reset");
1094
1215
  assert.ok(FORCED_CONTINUATIONS.includes(forced.messages[1].text));
1095
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
+ });
1096
1493
  test("Claude empty_brain accepts 500 code points", async (t) => {
1097
1494
  const { host, invoke } = await retainedFixture(t);
1098
1495
  host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
@@ -1103,18 +1500,27 @@ test("Claude empty_brain accepts 500 code points", async (t) => {
1103
1500
  assert.equal(result.messages[2].text, `*You peel a sticky note off your forehead.*\n${sticky}`);
1104
1501
  });
1105
1502
  test("Claude empty_brain refuses unsupported calls without queuing a reset", async (t) => {
1106
- const { host, invoke } = await retainedFixture(t);
1107
- let resets = 0;
1108
- 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 }; };
1109
1507
  await invoke("turn.start");
1110
1508
  const call = (params) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "bad-wipe", ...params });
1111
- 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/]]) {
1112
1510
  const refused = await call(params);
1113
1511
  assert.equal(refused.isError, true);
1114
1512
  assert.match(refused.result, reason);
1115
1513
  }
1116
1514
  await invoke("turn.complete", turnComplete());
1515
+ await settleHooks();
1117
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");
1118
1524
  });
1119
1525
  test("Claude asks for one handoff per compaction and reuses it when the same window retries", async (t) => {
1120
1526
  const { host, invoke } = await retainedFixture(t);
@@ -1131,22 +1537,20 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1131
1537
  await invoke("turn.start");
1132
1538
  await invoke("turn.complete", turnComplete());
1133
1539
  assert.equal(draws.length, 0, "only a reset draws, never a read");
1134
- const timers = [];
1135
1540
  const lines = [];
1136
- host.clock.after = (_ms, callback) => { timers.push(callback); };
1137
- host.prompt.submit = async () => { await invoke("turn.start"); };
1541
+ host.prompt.submit = async ({ text }) => { await invoke("turn.start"); return { text }; };
1138
1542
  // The host retries one plugin compaction for the same window: one artifact, one draw.
1139
- host.session.compact = async ({ instructions }) => {
1543
+ host.command.run = async ({ args }) => {
1140
1544
  for (let attempt = 0; attempt < 2; attempt++) {
1141
- const result = await invoke("session.compact", { trigger: "plugin", instructions: instructions ?? "" });
1545
+ const result = await invoke("session.compact", { trigger: "manual", instructions: args });
1142
1546
  lines.push(result.messages[1].text);
1143
1547
  }
1144
- return { skip: "test default" };
1548
+ return { text: "not committed" };
1145
1549
  };
1146
1550
  assert.equal((await invoke("command.run", { command: "fresh-window", args: "" })).text, "🥣 Dumping Brain");
1147
- await Promise.resolve();
1148
- await timers.shift()();
1551
+ await settleHooks();
1149
1552
  await invoke("turn.complete", turnComplete());
1553
+ await settleHooks();
1150
1554
  assert.equal(draws.length, 1, "a retried compaction adds no second draw");
1151
1555
  assert.equal(lines.length, 2, "both attempts returned a handoff");
1152
1556
  assert.equal(lines[0], lines[1], "both attempts carry the same artifact's paragraph");
@@ -1166,8 +1570,9 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1166
1570
  host.session.messages = async () => [];
1167
1571
  // Clear the old running-turn and queued-reset state, not just the retained boot.
1168
1572
  let compactions = 0;
1169
- host.session.compact = async () => { compactions++; return {}; };
1573
+ host.command.run = async () => { compactions++; return {}; };
1170
1574
  await invoke("turn.complete", turnComplete());
1575
+ await settleHooks();
1171
1576
  assert.equal(compactions, 0, "the old queued reset cannot spill into the new session");
1172
1577
  const fresh = await context();
1173
1578
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
@@ -1325,11 +1730,11 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1325
1730
  let release;
1326
1731
  const hold = new Promise((resolve) => { release = resolve; });
1327
1732
  host.session.usage = async () => ({ context: { tokens: 170_000, window: 200_000 } });
1328
- host.session.compact = async ({ instructions }) => {
1329
- const result = await invoke("session.compact", { trigger: "plugin", instructions });
1733
+ host.command.run = async ({ args }) => {
1734
+ await invoke("session.compact", { trigger: "manual", instructions: args });
1330
1735
  prepared();
1331
1736
  await hold;
1332
- return result;
1737
+ return {};
1333
1738
  };
1334
1739
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "in-flight" });
1335
1740
  const finishing = invoke("turn.complete", turnComplete());
@@ -1340,6 +1745,7 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1340
1745
  host.session.usage = async () => ({ context: {} });
1341
1746
  release();
1342
1747
  await finishing;
1748
+ await settleHooks();
1343
1749
  const fresh = await context();
1344
1750
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
1345
1751
  assert.match(fresh.blocks[0].text, /Current context window id: claude:after-flight:0/);