notesoup 0.53.1 → 0.53.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.
@@ -55,7 +55,7 @@ function fakeEngine(home) {
55
55
  env: { get: async (name) => name === "NOTESOUP_HOME" ? home : undefined },
56
56
  session: { id: async () => "hook-session", cwd: async () => home, model: async () => "claude", messages: async () => [], usage: async () => ({ context: {} }), compact: async () => ({ skip: "test default" }) },
57
57
  settings: { read: async () => ({}) },
58
- command: { register: async (spec) => ({ command: spec.name }) },
58
+ command: { run: async () => ({}), register: async (spec) => ({ command: spec.name }) },
59
59
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
60
60
  prompt: { submit: async () => undefined },
61
61
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
@@ -172,7 +172,7 @@ function limitPoints(facts) {
172
172
  const limits = resolveClaudeLimits(facts);
173
173
  return { source: limits.source, unit: limits.unit, autoCompact: limits.autoCompact, native: limits.native, reset: limits.reset, warn: limits.warn };
174
174
  }
175
- // Claude compacts at min(floor((W-20000)*pct/100), W-20000-13000); notesoup resets 8192 below
175
+ // Claude compacts at min(floor((W-20000)*pct/100), W-20000-13000); warning math uses the old reset intermediate 8192 below
176
176
  // that and warns 16384 earlier. These are the numbers, not prose.
177
177
  const CLAUDE_200K = { native: 167_000, reset: 158_808, warn: 142_424 };
178
178
  test("Claude limits derive from Claude's own auto-compact point, never a fixed percent", () => {
@@ -192,8 +192,18 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
192
192
  env: { autoCompactWindow: "400000" },
193
193
  settings: { autoCompactWindow: 500_000, modelSettings: { "claude-opus-4-6": { autoCompactWindow: 300_000 } } },
194
194
  }).native, 267_000, "the smallest configured window wins");
195
+ for (const [pctOverride, native, warn] of [["65", 117_000, 92_424], ["75", 135_000, 110_424]]) {
196
+ assert.equal(resolveClaudeLimits({ ...fromBreakdown, env: { pctOverride } }).warn, warn);
197
+ const fallback = resolveClaudeLimits({ usage: { window: 200_000 }, env: { pctOverride, autoCompactWindow: "200000" } });
198
+ assert.equal(fallback.source, "window");
199
+ assert.equal(fallback.native, native);
200
+ assert.equal(fallback.warn, warn);
201
+ }
202
+ for (const pctOverride of ["0", "101", "abc", "", "96"])
203
+ assert.equal(resolveClaudeLimits({ usage: { window: 200_000 }, env: { pctOverride } }).native, 167_000);
195
204
  // Auto-compact off: the point moves to the hard window, and the margins stay.
196
205
  const offSettings = { usage: { tokens: 171_808, window: 200_000 }, settings: { autoCompactEnabled: false } };
206
+ assert.deepEqual(limitPoints({ ...offSettings, env: { pctOverride: "65" } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 }, "disabled auto-compaction ignores pct");
197
207
  assert.deepEqual(limitPoints(offSettings), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
198
208
  assert.deepEqual(limitPoints({ usage: { window: 200_000 }, env: { disableAutoCompact: "1" } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
199
209
  assert.deepEqual(limitPoints({ usage: { window: 200_000 }, breakdown: { isAutoCompactEnabled: false } }), { source: "window", unit: "tokens", autoCompact: false, native: 180_000, reset: 171_808, warn: 155_424 });
@@ -352,8 +362,7 @@ test("Claude Mod with NOTESOUP_DISABLED registers nothing and passes every event
352
362
  assert.equal(compact, native, "native compaction runs exactly as if the mod were absent");
353
363
  const completed = await handlers.get("turn.complete")(host, {}, async () => ({ done: true }));
354
364
  assert.deepEqual(completed, { done: true }, "turn.complete passes through without a reset");
355
- const measured = await handlers.get("session.measure")(host, {}, async () => ({ marks: true }));
356
- assert.deepEqual(measured, { marks: true }, "session.measure passes through without a reset");
365
+ assert.equal(handlers.has("session.measure"), false, "measure has no reset hook");
357
366
  assert.equal(helperCalls, 0, "the helper never runs while disabled");
358
367
  const event = { text: "continue", context: ["upstream"] };
359
368
  assert.equal(await handlers.get("prompt.submit")(host, event, async (e) => e), event);
@@ -476,14 +485,15 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
476
485
  assert.equal(crashed.isError, true);
477
486
  assert.match(String(crashed.result), /^notesoup: helper execution failed: Error: spawn timed out after 10000ms$/, "the host's own reason survives the catch");
478
487
  });
479
- test("Claude Mod resets at Claude's resolved point after the turn, retains one fresh boot and deduplicates measure", async (t) => {
488
+ test("Claude Mod crosses old reset thresholds without clearing and retains one fresh boot on request", async (t) => {
480
489
  const home = mkdtempSync(join(tmpdir(), "claude-reset-home-"));
481
490
  t.after(() => rmSync(home, { recursive: true, force: true }));
482
491
  const { host, registered, notifications } = fakeEngine(home);
483
492
  const handlers = new Map();
484
493
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
485
494
  const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
486
- // A 200K window resolves to Claude's 167 000 point, so notesoup resets 8 192 below it.
495
+ assert.equal(handlers.has("session.measure"), false, "measure has no reset hook");
496
+ // The old proactive point was 158808; crossing it must no longer clear.
487
497
  let tokens = 140_000;
488
498
  let compactions = 0;
489
499
  let kept = [];
@@ -502,13 +512,12 @@ test("Claude Mod resets at Claude's resolved point after the turn, retains one f
502
512
  assert.equal(initial.blocks.length, 1, "below the warn point no warning joins the boot");
503
513
  assert.match(initial.blocks[0].text, /Current context window id: claude:hook-session:0/);
504
514
  await invoke("turn.start");
505
- await invoke("session.measure");
506
515
  await invoke("turn.complete");
507
516
  assert.equal(compactions, 0, "140000 is below every resolved point");
508
517
  host.session.usage = async () => { throw new Error("usage unavailable"); };
509
- await invoke("session.measure");
510
518
  await invoke("turn.complete");
511
- assert.equal(notifications.filter((text) => text.includes("Brain fullness unknown")).length, 1, "usage failure logs once per session");
519
+ await invoke("tool.call", { tool: "Read" });
520
+ assert.equal(notifications.filter((text) => text.includes("Brain fullness unknown")).length, 1, "warning usage failure logs once per session");
512
521
  host.session.usage = async () => measured();
513
522
  await dispatch({ op: "tool", tool: "notes_write", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, params: { address: "@human/MAP.md", content: "FRESH_NOTES_AT_RESET" } });
514
523
  await invoke("turn.start");
@@ -517,9 +526,16 @@ test("Claude Mod resets at Claude's resolved point after the turn, retains one f
517
526
  assert.equal(compactions, 0, "one token below the resolved reset point");
518
527
  await invoke("turn.start");
519
528
  tokens = 158_808;
520
- await invoke("session.measure");
521
529
  assert.equal(compactions, 0, "measure cannot compact under a running turn");
522
530
  assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" });
531
+ assert.equal(compactions, 0, "the old reset point no longer clears at turn completion");
532
+ tokens = 190_000;
533
+ await invoke("turn.start");
534
+ await invoke("turn.complete");
535
+ assert.equal(compactions, 0, "even beyond the native threshold, only a native auto event or explicit request resets");
536
+ await invoke("turn.start");
537
+ await invoke("command.run", { command: "empty" });
538
+ await invoke("turn.complete");
523
539
  assert.equal(compactions, 1);
524
540
  assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
525
541
  assert.equal(kept[0].role, "user");
@@ -528,44 +544,109 @@ test("Claude Mod resets at Claude's resolved point after the turn, retains one f
528
544
  assert.match(kept[0].text, /FRESH_NOTES_AT_RESET/);
529
545
  assert.doesNotMatch(kept[0].text, /OLD_SECRET/);
530
546
  assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text), "the handoff comes from the shared forced pool");
531
- await invoke("session.measure");
532
547
  assert.equal(compactions, 1, "invalidated tokens cannot immediately reset twice");
533
548
  const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
534
549
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => upstream), upstream, "the retained boot is not injected a second time");
535
550
  });
536
- test("Claude Mod headless detection skips compaction and logs once", async (t) => {
551
+ test("Claude headless resets through its own manual command, retries failure and keeps user compact vetoed", async (t) => {
537
552
  const home = mkdtempSync(join(tmpdir(), "claude-headless-home-"));
538
553
  t.after(() => rmSync(home, { recursive: true, force: true }));
539
554
  const { host, notifications } = fakeEngine(home);
540
555
  const handlers = new Map();
541
556
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
542
- const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({ sentinel: name }));
543
- let tokens;
557
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
558
+ let kept = [];
544
559
  let attempts = 0;
560
+ let reject = true;
561
+ host.session.messages = async () => kept;
562
+ host.session.compact = async () => { throw new Error("headless must not call session.compact"); };
563
+ host.command.run = async ({ command }) => {
564
+ attempts++;
565
+ assert.equal(command, "compact");
566
+ if (reject)
567
+ throw new Error("command unavailable");
568
+ return { text: "Not compacted" };
569
+ };
570
+ // Exercise the user veto before the internally owned command is in flight.
571
+ await invoke("session.start", { cwd: home, isInteractive: false });
572
+ assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
573
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", last_word: "STICKY", tool_use_id: "reset" });
574
+ await invoke("turn.complete");
575
+ assert.equal(attempts, 1);
576
+ assert.ok(notifications.some(x => x.includes("command unavailable")));
577
+ reject = false;
578
+ await invoke("turn.complete");
579
+ assert.equal(attempts, 2, "failed requests remain pending");
580
+ assert.ok(notifications.some(x => x.includes("Brain not emptied")));
581
+ // Core dispatches the admitted manual event within our command hook.
582
+ host.command.run = async ({ command }) => {
583
+ attempts++;
584
+ const user = await handlers.get("command.run")(host, { command, origin: { kind: "user" } }, async () => invoke("session.compact", { trigger: "manual" }));
585
+ assert.match(JSON.stringify(user), /use \/fresh-window/, "a pending reset does not admit the user's command");
586
+ await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
587
+ kept = (await invoke("session.compact", { trigger: "manual" })).messages;
588
+ return {};
589
+ });
590
+ return {};
591
+ };
592
+ await invoke("turn.complete");
593
+ assert.match(kept[0].text, /claude:hook-session:1/);
594
+ assert.equal(kept[2].text, "*You peel a sticky note off your forehead.*\nSTICKY");
595
+ await invoke("turn.complete");
596
+ assert.equal(attempts, 3, "success clears pending exactly once");
597
+ assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
598
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "reset2" });
599
+ await invoke("turn.complete");
600
+ assert.match(kept[0].text, /claude:hook-session:2/);
601
+ assert.equal(kept.length, 2, "sticky is consumed once");
602
+ });
603
+ test("Claude headless warns without proactive resets and supports both manual aliases", async (t) => {
604
+ const home = mkdtempSync(join(tmpdir(), "claude-headless-auto-"));
605
+ t.after(() => rmSync(home, { recursive: true, force: true }));
606
+ const { host } = fakeEngine(home);
607
+ const handlers = new Map();
608
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
609
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
610
+ let tokens = CLAUDE_200K.warn;
611
+ let attempts = 0, prompts = 0;
612
+ const timers = [];
545
613
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
546
- host.session.compact = async () => { attempts++; throw new Error("not available in a headless (-p / SDK) session yet"); };
614
+ host.clock.after = (_ms, callback) => { timers.push(callback); };
615
+ host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete"); };
616
+ host.command.run = async ({ command }) => {
617
+ attempts++;
618
+ await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
619
+ const result = await invoke("session.compact", { trigger: "manual" });
620
+ assert.match(result.messages[0].text, new RegExp(`claude:hook-session:${attempts}`));
621
+ tokens = undefined;
622
+ return {};
623
+ });
624
+ return {};
625
+ };
547
626
  await invoke("session.start", { cwd: home, isInteractive: false });
627
+ const warning = await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
628
+ assert.deepEqual(warning.context, [CLAUDE_WARNING_PROMPT]);
629
+ tokens = CLAUDE_200K.reset;
548
630
  await invoke("turn.start");
631
+ assert.equal(attempts, 0);
549
632
  await invoke("turn.complete");
550
- await invoke("session.measure");
551
- assert.equal(attempts, 0, "no measured tokens means no automatic reset");
552
- tokens = 190_000;
553
- await invoke("turn.start");
554
- assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" }, "a rejection does not break the turn chain");
555
- await invoke("session.measure");
633
+ assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
634
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
556
635
  await invoke("turn.complete");
557
- assert.equal(attempts, 0, "headless sessions skip the unsupported capability from startup");
558
- assert.deepEqual(notifications, ["🥣 No brain when headless"]);
559
- const manual = await invoke("command.run", { command: "empty" });
560
- assert.match(manual.text, /No brain when headless/);
561
- const tool = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "headless" });
562
- assert.equal(tool.isError, true);
563
- assert.match(tool.result, /No brain when headless/);
564
- assert.equal(notifications.length, 1);
565
- const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
566
- assert.match(boot.blocks[0].text, /Current context window id: claude:hook-session:0/);
567
- const event = { text: "continue" };
568
- assert.equal(await handlers.get("prompt.submit")(host, event, async (e) => e), event, "headless prompts never warn");
636
+ assert.equal(attempts, 1);
637
+ for (const command of ["empty", "fresh-window"]) {
638
+ assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
639
+ await Promise.resolve();
640
+ await timers.shift()();
641
+ }
642
+ assert.equal(attempts, 3);
643
+ assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
644
+ host.prompt.submit = async () => { throw new Error("close-out unavailable"); };
645
+ await invoke("command.run", { command: "empty" });
646
+ await Promise.resolve();
647
+ await timers.shift()();
648
+ await invoke("turn.complete");
649
+ assert.equal(attempts, 4, "a failed close-out also leaves the reset pending");
569
650
  });
570
651
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
571
652
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -605,6 +686,7 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
605
686
  let result = {};
606
687
  host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
607
688
  await invoke("turn.start");
689
+ await invoke("command.run", { command: "empty" });
608
690
  await invoke("turn.complete");
609
691
  assert.match(result.skip, /notes didn't load/);
610
692
  assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
@@ -646,7 +728,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
646
728
  assert.deepEqual(await invoke("command.run", { command: "empty-brain" }), {}, "the retired spelling passes through instead of resetting");
647
729
  assert.equal(timers.length, 0);
648
730
  const command = await invoke("command.run", { command: "empty" });
649
- assert.match(command.text, /Brain being emptied/);
731
+ assert.equal(command.text, "🥣 Dumping Brain");
650
732
  await Promise.resolve();
651
733
  assert.equal(compactions, 0, "command.run must not call compact under its held turn");
652
734
  assert.equal(timers.length, 1);
@@ -697,6 +779,36 @@ test("Claude Mod delivers one warning per window through main tools or prompt su
697
779
  assert.equal(await tool(), foreign, "prompt delivery wins over the later tool route");
698
780
  assert.deepEqual((await context()).blocks, [], "no notesoup:warning block is ever added to prompt context");
699
781
  });
782
+ test("Claude warnings read the public nested breakdown and apply pct even without its threshold", async (t) => {
783
+ for (const threshold of [167_000, undefined]) {
784
+ const { host, invoke } = await retainedFixture(t);
785
+ const env = host.env.get;
786
+ host.env.get = async (name) => name === "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE" ? "65" : name === "CLAUDE_CODE_AUTO_COMPACT_WINDOW" ? "200000" : env(name);
787
+ let tokens = 92_423;
788
+ host.session.usage = async (options) => ({ context: {
789
+ tokens, window: 200_000,
790
+ ...(options?.breakdown ? { breakdown: { autoCompactThreshold: threshold, isAutoCompactEnabled: true, model: "claude" } } : {}),
791
+ } });
792
+ const run = host.process.run;
793
+ host.process.run = async (argv, init) => {
794
+ const request = JSON.parse(init?.stdin ?? "{}");
795
+ if (request.op === "limits")
796
+ assert.deepEqual(request.facts.breakdown, { ...(threshold === undefined ? {} : { autoCompactThreshold: threshold }), isAutoCompactEnabled: true, model: "claude" });
797
+ return run(argv, init);
798
+ };
799
+ let resets = 0;
800
+ host.session.compact = async () => { resets++; return {}; };
801
+ const submit = () => invoke("prompt.submit", { text: "continue" }, {}, async (e) => e);
802
+ assert.equal((await submit()).context, undefined);
803
+ tokens++;
804
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
805
+ assert.equal((await submit()).context, undefined, "one warning per window");
806
+ await invoke("turn.complete");
807
+ assert.equal(resets, 0, "warning and turn completion never proactively clear");
808
+ assert.equal((await invoke("session.compact", { trigger: "auto" })).messages.length, 2);
809
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
810
+ }
811
+ });
700
812
  test("Claude Mod consumes a warning only after an accepted delivery and ignores stale generations", async (t) => {
701
813
  const { host, invoke } = await retainedFixture(t);
702
814
  const texts = await dispatch({ op: "texts" });
@@ -728,7 +840,7 @@ test("Claude Mod consumes a warning only after an accepted delivery and ignores
728
840
  assert.deepEqual(delivered.context, [...event.context, texts.warning], "an old delivery cannot mark the new generation warned");
729
841
  assert.equal(await invoke("prompt.submit", event, event), event, "only an accepted delivery consumes the new window");
730
842
  });
731
- test("Claude Mod moves the reset point to the hard window when auto-compact is off", async (t) => {
843
+ test("Claude Mod keeps warning timing when auto-compact is off without clearing at the old reset point", async (t) => {
732
844
  const home = mkdtempSync(join(tmpdir(), "claude-off-home-"));
733
845
  t.after(() => rmSync(home, { recursive: true, force: true }));
734
846
  const { host, notifications } = fakeEngine(home);
@@ -736,21 +848,25 @@ test("Claude Mod moves the reset point to the hard window when auto-compact is o
736
848
  const handlers = new Map();
737
849
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
738
850
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
739
- let tokens = 171_807;
851
+ let tokens = 155_423;
740
852
  let compactions = 0;
741
853
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
742
854
  host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
743
855
  await invoke("session.start", { cwd: home, isInteractive: true });
744
856
  await invoke("turn.start");
745
857
  await invoke("turn.complete");
746
- assert.equal(compactions, 0, "171807 is below the hard-window point");
858
+ const submit = () => handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
859
+ assert.equal((await submit()).context, undefined);
860
+ tokens = 155_424;
861
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "the hard-window warning point stays 180000 - 8192 - 16384");
862
+ assert.equal(compactions, 0);
747
863
  await invoke("turn.start");
748
864
  tokens = 171_808;
749
865
  await invoke("turn.complete");
750
- assert.equal(compactions, 1, "200000 - 20000 - 8192");
866
+ assert.equal(compactions, 0, "the former 200000 - 20000 - 8192 reset point is not a clear trigger");
751
867
  assert.deepEqual(notifications.filter((text) => text.includes("unavailable") || text.includes("Couldn't")), [], "a resolvable configuration logs no failure");
752
868
  });
753
- test("Claude Mod stops the automatic reset and the manual command under DISABLE_COMPACT", async (t) => {
869
+ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_COMPACT", async (t) => {
754
870
  const home = mkdtempSync(join(tmpdir(), "claude-disabled-home-"));
755
871
  t.after(() => rmSync(home, { recursive: true, force: true }));
756
872
  const { host, notifications } = fakeEngine(home);
@@ -773,15 +889,13 @@ test("Claude Mod stops the automatic reset and the manual command under DISABLE_
773
889
  assert.match(tool.result, /DISABLE_COMPACT/);
774
890
  assert.equal(timers.length, 0, "no close-out turn is queued");
775
891
  await invoke("turn.start");
776
- await invoke("session.measure");
777
892
  await invoke("turn.complete");
778
- await invoke("session.measure");
779
- assert.equal(compactions, 0, "the automatic reset is off and does not retry");
893
+ assert.equal(compactions, 0, "disabled reset requests never run");
780
894
  assert.equal(notifications.length, 1, "detection logs once, not per turn");
781
895
  const upstream = { result: "upstream", context: ["other plugin"] };
782
896
  assert.equal(await handlers.get("tool.call")(host, { tool: "Read" }, async () => upstream), upstream, "DISABLE_COMPACT also suppresses warnings");
783
897
  });
784
- test("Claude Mod skips the automatic reset when thresholds cannot be resolved", async (t) => {
898
+ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t) => {
785
899
  const home = mkdtempSync(join(tmpdir(), "claude-nolimits-home-"));
786
900
  t.after(() => rmSync(home, { recursive: true, force: true }));
787
901
  const { host, notifications } = fakeEngine(home);
@@ -794,9 +908,8 @@ test("Claude Mod skips the automatic reset when thresholds cannot be resolved",
794
908
  host.session.compact = async () => { compactions++; return {}; };
795
909
  await invoke("session.start", { cwd: home, isInteractive: true });
796
910
  await invoke("turn.start");
797
- await invoke("session.measure");
798
911
  await invoke("turn.complete");
799
- await invoke("session.measure");
912
+ await invoke("tool.call", { tool: "Read" });
800
913
  assert.equal(compactions, 0, "an unresolvable point never resets");
801
914
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
802
915
  });
@@ -820,9 +933,9 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
820
933
  host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
821
934
  await invoke("session.start", { cwd: home, isInteractive: true });
822
935
  await invoke("turn.start");
936
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
823
937
  await invoke("turn.start", { agentId: "sub-1" });
824
938
  await invoke("turn.complete", { agentId: "sub-1" });
825
- await invoke("session.measure");
826
939
  assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
827
940
  await invoke("turn.complete");
828
941
  assert.equal(compactions, 1, "the main turn still resets at its own end");
@@ -841,10 +954,11 @@ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
841
954
  await invoke("session.start", { cwd: home, isInteractive: true });
842
955
  assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
843
956
  await invoke("turn.start");
957
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
844
958
  await invoke("turn.complete");
845
- assert.equal(compactions, 1, "the automatic reset still runs");
959
+ assert.equal(compactions, 1, "the explicit reset still runs");
846
960
  });
847
- test("Claude Mod retries an unresolvable threshold inside the same window", async (t) => {
961
+ test("Claude Mod retries an unresolvable warning threshold inside the same window", async (t) => {
848
962
  const home = mkdtempSync(join(tmpdir(), "claude-retry-home-"));
849
963
  t.after(() => rmSync(home, { recursive: true, force: true }));
850
964
  const { host } = fakeEngine(home);
@@ -865,12 +979,15 @@ test("Claude Mod retries an unresolvable threshold inside the same window", asyn
865
979
  await invoke("session.start", { cwd: home, isInteractive: true });
866
980
  await invoke("turn.start");
867
981
  await invoke("turn.complete");
982
+ await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
868
983
  assert.equal(limitsCalls, 1, "the first limits round trip failed");
869
984
  assert.equal(compactions, 0, "one failed resolution does not disable the window");
870
985
  await invoke("turn.start");
871
986
  await invoke("turn.complete");
987
+ const retried = await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
988
+ assert.deepEqual(retried.context, [CLAUDE_WARNING_PROMPT]);
872
989
  assert.equal(limitsCalls, 2, "the retry runs in the same window");
873
- assert.equal(compactions, 1, "the retried resolution resets at the turn's end");
990
+ assert.equal(compactions, 0, "warning threshold resolution never resets");
874
991
  });
875
992
  /** Start from a real retained boot, as after notesoup reset or a plugin reload. */
876
993
  async function retainedFixture(t) {
@@ -913,7 +1030,6 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
913
1030
  assert.equal(accepted.isError, undefined);
914
1031
  assert.match(accepted.result, /End your turn now/);
915
1032
  await call({ last_word: "must not replace the first request" });
916
- await invoke("session.measure");
917
1033
  await invoke("turn.complete", { agentId: "child" });
918
1034
  assert.equal(resets.length, 0, "neither tool execution nor a child completion resets a running main turn");
919
1035
  await invoke("turn.complete");
@@ -930,13 +1046,22 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
930
1046
  assert.equal(forced.messages.length, 2, "the sticky note does not leak into the next reset");
931
1047
  assert.ok(FORCED_CONTINUATIONS.includes(forced.messages[1].text));
932
1048
  });
1049
+ test("Claude empty_brain accepts 500 code points", async (t) => {
1050
+ const { host, invoke } = await retainedFixture(t);
1051
+ host.session.usage = async () => ({ context: { tokens: 100, window: 200_000 } });
1052
+ const sticky = "🐟".repeat(500);
1053
+ const accepted = await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "limit-wipe", last_word: ` ${sticky} ` });
1054
+ assert.equal(accepted.isError, undefined);
1055
+ const result = await invoke("session.compact", { trigger: "auto" });
1056
+ assert.equal(result.messages[2].text, `*You peel a sticky note off your forehead.*\n${sticky}`);
1057
+ });
933
1058
  test("Claude empty_brain refuses unsupported calls without queuing a reset", async (t) => {
934
1059
  const { host, invoke } = await retainedFixture(t);
935
1060
  let resets = 0;
936
1061
  host.session.compact = async () => { resets++; return {}; };
937
1062
  await invoke("turn.start");
938
1063
  const call = (params) => invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "bad-wipe", ...params });
939
- for (const [params, reason] of [[{ agentId: "child" }, /only the main agent/], [{ last_word: "x".repeat(301) }, /Shorten it/], [{ last_word: 7 }, /must be a string/]]) {
1064
+ 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/]]) {
940
1065
  const refused = await call(params);
941
1066
  assert.equal(refused.isError, true);
942
1067
  assert.match(refused.result, reason);
@@ -956,7 +1081,6 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
956
1081
  };
957
1082
  // Every read path stays pure: no boot, warning, context, or measure draws a handoff.
958
1083
  await invoke("prompt.context", {}, { blocks: [] });
959
- await invoke("session.measure");
960
1084
  await invoke("turn.start");
961
1085
  await invoke("turn.complete");
962
1086
  assert.equal(draws.length, 0, "only a reset draws, never a read");
@@ -972,7 +1096,7 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
972
1096
  }
973
1097
  return { skip: "test default" };
974
1098
  };
975
- assert.match((await invoke("command.run", { command: "fresh-window", args: "" })).text, /Brain being emptied/);
1099
+ assert.equal((await invoke("command.run", { command: "fresh-window", args: "" })).text, "🥣 Dumping Brain");
976
1100
  await Promise.resolve();
977
1101
  await timers.shift()();
978
1102
  await invoke("turn.complete");
@@ -1160,6 +1284,7 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1160
1284
  await hold;
1161
1285
  return result;
1162
1286
  };
1287
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "in-flight" });
1163
1288
  const finishing = invoke("turn.complete");
1164
1289
  await ready;
1165
1290
  await invoke("session.end", { reason: "clear", sessionId: "hook-session" });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { BOOT_TYPE, CONTINUATION_TYPE, MARKER_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
5
+ import { nextHistorySeq } from "../plugins/pi/history.js";
6
+ import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
7
+ import { appendText, context, installExtensionTestEnvironment, makeExtension, runCommand, runHandlers, sentOf } from "./helpers/extension.js";
8
+ const env = installExtensionTestEnvironment("notesoup-marker-test");
9
+ test.beforeEach(env.beforeEach);
10
+ test.afterEach(env.afterEach);
11
+ test.after(env.dispose);
12
+ function turnStart(captured, ctx) {
13
+ return runHandlers(captured, "turn_start", { type: "turn_start" }, ctx);
14
+ }
15
+ test("marker stamps its own seq once the interval is reached, then holds", async () => {
16
+ const sessionManager = managerWithMessages(49);
17
+ const captured = makeExtension(sessionManager);
18
+ const ctx = context(sessionManager);
19
+ await turnStart(captured, ctx);
20
+ const sent = sentOf(captured, MARKER_TYPE);
21
+ assert.equal(sent.length, 1);
22
+ assert.deepEqual(sent[0].message.details, { seq: 50 });
23
+ assert.equal(sent[0].message.display, false);
24
+ assert.equal(sent[0].options?.triggerTurn, false);
25
+ assert.equal(sent[0].message.content, '<notesoup:marker seq="50" />');
26
+ assert.equal(nextHistorySeq(ctx), 51, "the marker occupies the seq it names");
27
+ // An immediate second turn is only one seq later: no new marker.
28
+ await turnStart(captured, ctx);
29
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 1);
30
+ // The next marker lands exactly one interval after the last.
31
+ appendText(sessionManager, "user", "x".repeat(1));
32
+ for (let i = 0; i < 48; i++)
33
+ appendText(sessionManager, "assistant", "y");
34
+ await turnStart(captured, ctx);
35
+ const all = sentOf(captured, MARKER_TYPE);
36
+ assert.equal(all.length, 2);
37
+ assert.deepEqual(all[1].message.details, { seq: 100 });
38
+ });
39
+ test("no marker before the interval", async () => {
40
+ const sessionManager = managerWithMessages(48);
41
+ const captured = makeExtension(sessionManager);
42
+ await turnStart(captured, context(sessionManager));
43
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
44
+ assert.equal(MARKER_INTERVAL, 50);
45
+ });
46
+ test("a reset tail awaiting repair closes the road to markers, then reopens it", async () => {
47
+ const sessionManager = managerWithMessages(49);
48
+ const captured = makeExtension(sessionManager);
49
+ const ctx = context(sessionManager);
50
+ // A marker with neither boot nor continuation still expects repair; stay out of its tail.
51
+ sessionManager.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:test:w1" });
52
+ await turnStart(captured, ctx);
53
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
54
+ // Boot alone is still an open tail.
55
+ sessionManager.appendCustomMessageEntry(BOOT_TYPE, "boot", false, { windowId: "pcw:test:w1" });
56
+ await turnStart(captured, ctx);
57
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
58
+ // Once the shape is closed, the odometer continues across the reset: seq never restarted.
59
+ sessionManager.appendCustomMessageEntry(CONTINUATION_TYPE, "continued", false);
60
+ await turnStart(captured, ctx);
61
+ const sent = sentOf(captured, MARKER_TYPE);
62
+ assert.equal(sent.length, 1);
63
+ assert.deepEqual(sent[0].message.details, { seq: 52 });
64
+ });
65
+ test("notesoup off silences the odometer", async () => {
66
+ const sessionManager = managerWithMessages(49);
67
+ const captured = makeExtension(sessionManager);
68
+ const ctx = context(sessionManager);
69
+ await runCommand(captured, "notesoup", "off", ctx);
70
+ await turnStart(captured, ctx);
71
+ assert.equal(sentOf(captured, MARKER_TYPE).length, 0);
72
+ });
73
+ function managerWithMessages(count) {
74
+ const sessionManager = SessionManager.inMemory("/private/tmp/notesoup-marker-test");
75
+ for (let i = 0; i < count; i++)
76
+ appendText(sessionManager, i % 2 === 0 ? "user" : "assistant", `m${i}`);
77
+ return sessionManager;
78
+ }
@@ -910,6 +910,18 @@ test("empty_brain trims the last word, refuses an oversized one, and a blank per
910
910
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
911
911
  assert.equal(boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a blank last word persists no entry");
912
912
  });
913
+ test("empty_brain accepts a 500-code-point sticky note without truncation", async () => {
914
+ assert.equal(MAX_LAST_WORD_CHARS, 500);
915
+ const h = harness();
916
+ h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
917
+ const sticky = "🐟".repeat(500);
918
+ const accepted = await h.callTool("empty_brain", { last_word: ` ${sticky} ` });
919
+ assert.notEqual(accepted.isError, true);
920
+ const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
921
+ const entry = boundary.entries.find((row) => row.type === "custom_message" && row.customType === RESET_LAST_WORD_TYPE);
922
+ assert.ok(entry && entry.type === "custom_message");
923
+ assert.equal(entry.content, `${LAST_WORD_PREFIX}${sticky}`);
924
+ });
913
925
  test("empty_brain's schema admits whitespace-wrapped notes and leaves length to the handler", async () => {
914
926
  const parameters = harness().toolParameters("empty_brain");
915
927
  const padded = " ".repeat(300) + "x";
@@ -48,7 +48,7 @@ Boot and reminder deduplication inspect the current branch-local window. Reloadi
48
48
 
49
49
  Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. A bare command settles and stops unless later human input arrives; a command with text settles and continues, with its text supplied to the closing window and carried verbatim into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
50
50
 
51
- Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. Only an actual context reset produces a brain-cleared notice through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
51
+ Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. `/empty` and `/fresh-window` acknowledge a new request with `🥣 Dumping Brain`. Normal reset completion is silent; only forced reset completion produces `🥣 Brain forcibly emptied: overflow` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
52
52
 
53
53
  The Pi history adapter decodes the selected raw session branch on demand without a cache. It allocates stable seq values from the session's append-order entry list, then selects current-branch-only visibility, so navigation cannot expose a sibling's history. Shared history pairs and queries those decoded events; it neither traverses SessionReader nor reconstructs inference messages. The public stream combines each tool call with its result at the call seq; paired result slots are not public event addresses, and unpaired results retain their own seq. Summaries and injected messages project as `context`. List pages chronologically with seq anchors and an explicit `from`. Tool executions retain structured call/result facts and any native nested-call metadata. A deterministic event document supplies both query-match positions and read windows. Nested calls have no independent seq and never imply that unrecorded child outputs are available.
54
54
 
@@ -2,19 +2,19 @@
2
2
 
3
3
  The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*`, three history tools as `mcp__notesoup__history_*`, and `mcp__notesoup__empty_brain` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `plugins/claude/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
4
4
 
5
- In interactive sessions it resets automatically when the measured context reaches notesoup's reset point, checking after `session.measure` and `turn.complete` and waiting for a running turn to complete. That point is derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
5
+ There is no independent proactive automatic clear line: crossing a measured threshold, `session.measure`, or completing an unrequested turn never clears context. `turn.complete` resets only an explicit pending request from `empty_brain`, `/empty`, or `/fresh-window`. Budget warning timing is unchanged and is derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
6
6
 
7
- 1. `$.session.usage({breakdown:"summary"}).context.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
8
- 2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer;
7
+ 1. `$.session.usage({breakdown:"summary"}).context.breakdown.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
8
+ 2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer; `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` lowers this fallback point by the same formula. With auto-compaction off, the percent override is ignored;
9
9
  3. otherwise the percent fallback, which expresses the same reserves on the classic 200K window.
10
10
 
11
- Notesoup resets one `resetMarginTokens` (default 8192) below that point, and warns one `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below the reset. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the automatic reset. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, disables the automatic reset, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
11
+ The warning remains `resetMarginTokens` (default 8192) plus `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that point. The internal reset-derived intermediate is only warning math, not a clear trigger. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the budget warning. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, suppresses budget warnings and explicit resets, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
12
12
 
13
- Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry — the same boot-then-handoff order as Pi — while `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
13
+ Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry — the same boot-then-handoff order as Pi — while user `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
14
14
 
15
- The model can request the same reset through `empty_brain`, optionally passing a short `last_word` that is retained after the boot and handoff. The tool queues the reset and tells the model to end its turn; compaction runs at main-agent `turn.complete`, never inside a running tool call. Subagents cannot reset the main brain, and headless or `DISABLE_COMPACT` sessions refuse the tool without queuing a reset. Successful reset or session change clears the pending request and sticky note.
15
+ The model can request the same reset through `empty_brain`, optionally passing a short `last_word` that is retained after the boot and handoff. The tool queues the reset and tells the model to end its turn; compaction runs at main-agent `turn.complete`, never inside a running tool call. Subagents cannot reset the main brain, and `DISABLE_COMPACT` sessions refuse the tool without queuing a reset. Successful reset or session change clears the pending request and sticky note.
16
16
 
17
- `/fresh-window` requests the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. This is necessary in Claude Code 2.1.295: `command.run` holds a turn, and calling compact from a detached timer skips the plugin's own compact hook. The timer only schedules the close-out prompt, never compaction. The headless (`-p` / SDK) compact capability is unsupported: automatic attempts are caught and logged once, and the manual command skips without submitting a model turn. Boot acquisition failure vetoes reset, leaving the current window intact. A Claude dream backend is not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the reset points and the one warning per window now follow Claude's own configuration.
17
+ `/empty` and its alias `/fresh-window` request the same reset. While idle it submits one hidden normal-model close-out turn to let the model save notes, then resets at `turn.complete`; while busy it waits for the current turn instead. The close-out prompt is the same shared warning text the automatic path shows. Interactive resets use `$.session.compact`. Headless (`-p` / SDK) resets instead queue the native command with `$.command.run({command:"compact"})` after `turn.complete`; Claude Code 2.1.299 runs this command non-interactively and invokes the same plugin's compact hook. Only that internally initiated command admits the manual trigger; user `/compact` remains vetoed. The command receipt is not a compaction result: successful completion also requires the hook to have prepared the notes boot. Rejected or vetoed resets keep their pending request and sticky note for retry. Native command/caveat/output rows remain in the next request alongside the fresh boot; no compaction model request is made. Boot acquisition failure vetoes reset, leaving the current window intact. A Claude dream backend is not implemented; budget reporting (`get_context_remaining`) remains Pi-only, while the one warning per window follows Claude's own configuration.
18
18
 
19
19
  The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared memory and dream skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
20
20