notesoup 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/claude/src/helper.js +22 -4
  3. package/dist/plugins/claude/src/text.d.ts +7 -0
  4. package/dist/plugins/claude/src/text.js +12 -1
  5. package/dist/plugins/pi/budget.d.ts +3 -0
  6. package/dist/plugins/pi/budget.js +32 -6
  7. package/dist/plugins/pi/entries.d.ts +1 -0
  8. package/dist/plugins/pi/entries.js +1 -0
  9. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  10. package/dist/plugins/pi/reset/artifacts.js +4 -4
  11. package/dist/plugins/pi/reset/lifecycle.d.ts +8 -1
  12. package/dist/plugins/pi/reset/lifecycle.js +101 -22
  13. package/dist/plugins/pi/runtime.js +4 -4
  14. package/dist/plugins/pi/tool-result.js +1 -1
  15. package/dist/plugins/pi/window.d.ts +2 -10
  16. package/dist/plugins/pi/window.js +32 -22
  17. package/dist/src/budget/text.d.ts +5 -1
  18. package/dist/src/budget/text.js +11 -2
  19. package/dist/src/index.d.ts +1 -1
  20. package/dist/test/agent-loop.test.js +197 -41
  21. package/dist/test/boot.integration.test.js +23 -1
  22. package/dist/test/budget-settings.integration.test.js +4 -4
  23. package/dist/test/claude-mod.test.js +192 -12
  24. package/dist/test/claude-validation.test.js +69 -2
  25. package/dist/test/dream-skill.test.js +3 -3
  26. package/dist/test/helpers/extension.d.ts +3 -1
  27. package/dist/test/helpers/extension.js +2 -2
  28. package/dist/test/model-facing-text.test.js +13 -3
  29. package/dist/test/reset-lifecycle.test.js +10 -0
  30. package/docs/claude-code-mod.md +6 -6
  31. package/docs/reset-lifecycle.md +1 -1
  32. package/docs/skills.md +2 -2
  33. package/package.json +1 -1
  34. package/plugins/antigravity/plugin.json +1 -1
  35. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  36. package/plugins/claude/dist/claude/helper.js +49 -5
  37. package/plugins/claude/hooks/register.ts +201 -61
  38. package/plugins/claude/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  39. package/plugins/claude/src/helper.ts +22 -4
  40. package/plugins/claude/src/text.ts +14 -1
  41. package/plugins/pi/budget.ts +28 -5
  42. package/plugins/pi/entries.ts +1 -0
  43. package/plugins/pi/reset/artifacts.ts +4 -3
  44. package/plugins/pi/reset/lifecycle.ts +116 -22
  45. package/plugins/pi/runtime.ts +4 -4
  46. package/plugins/pi/tool-result.ts +1 -1
  47. package/plugins/pi/window.ts +30 -19
  48. package/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  49. package/src/budget/text.ts +14 -2
  50. package/src/index.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
@@ -10,8 +10,8 @@ import { dispatch, handleLine } from "../plugins/claude/src/helper.js";
10
10
  import { DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, resolveClaudeLimits } from "../plugins/claude/src/thresholds.js";
11
11
  import { WARNING_RUNWAY_TOKENS } from "../src/budget/constants.js";
12
12
  import { MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG, PROTOCOL_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js";
13
- import { CLAUDE_WARNING_PROMPT } from "../plugins/claude/src/text.js";
14
- import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, NORMAL_CONTINUATIONS, warningNotice } from "../src/budget/text.js";
13
+ import { CLAUDE_WARNING_PROMPT, claudeCommandWarningContent } from "../plugins/claude/src/text.js";
14
+ import { BETWEEN_TURNS_CONTINUATIONS, COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, NORMAL_CONTINUATIONS, warningNotice } from "../src/budget/text.js";
15
15
  import { createNotesStore } from "../src/notes/index.js";
16
16
  import { resolveProjectNamespace } from "../src/notes/project-namespace.js";
17
17
  import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
@@ -74,10 +74,24 @@ async function loadHookModule(t) {
74
74
  on(event, ($, e, next) => Object.entries(matcherOrHandler).every(([key, value]) => Array.isArray(value) ? value.includes(e[key]) : e[key] === value) ? handler($, e, next) : next(e));
75
75
  }) };
76
76
  }
77
+ /** Plugin skill names whose bare slash-command aliases collide with $.command.register in Claude Code. */
78
+ function claudePluginOwnedBareCommands() {
79
+ const manifest = JSON.parse(readFileSync(join(process.cwd(), "plugins/claude/.claude-plugin/plugin.json"), "utf8"));
80
+ const skillsDir = join(process.cwd(), "plugins/claude/skills");
81
+ const names = new Set();
82
+ if (existsSync(skillsDir)) {
83
+ for (const entry of readdirSync(skillsDir, { withFileTypes: true })) {
84
+ if (entry.isDirectory() && entry.name === manifest.name)
85
+ names.add(entry.name);
86
+ }
87
+ }
88
+ return names;
89
+ }
77
90
  /** An engine that answers the hook by running the real helper against a throwaway notes home. */
78
91
  function fakeEngine(home) {
79
92
  const registered = [];
80
93
  const notifications = [];
94
+ const reservedCommands = claudePluginOwnedBareCommands();
81
95
  return {
82
96
  registered,
83
97
  notifications,
@@ -85,7 +99,15 @@ function fakeEngine(home) {
85
99
  env: { get: async (name) => name === "NOTESOUP_HOME" ? home : undefined },
86
100
  session: { id: async () => "hook-session", cwd: async () => home, model: async () => "claude", messages: async () => [], usage: async () => ({ context: {} }), compact: async () => ({ skip: "test default" }) },
87
101
  settings: { read: async () => ({}) },
88
- command: { run: async () => ({}), register: async (spec) => ({ command: spec.name }) },
102
+ command: {
103
+ run: async () => ({}),
104
+ register: async (spec) => {
105
+ if (reservedCommands.has(spec.name)) {
106
+ throw new Error(`notesoup: $.command.register: "/${spec.name}" refused: it is the plugin's /${spec.name}:${spec.name}`);
107
+ }
108
+ return { command: spec.name };
109
+ },
110
+ },
89
111
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
90
112
  prompt: { submit: async ({ text }) => ({ text }) },
91
113
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
@@ -524,7 +546,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
524
546
  const handlers = new Map();
525
547
  hooks.register((event, handler) => handlers.set(event, handler));
526
548
  await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async (event) => event);
527
- assert.deepEqual(registered.map((spec) => spec.name), ["empty_brain", "notes_write", "notes_update", "notes_read", "notes_list", "history_list", "history_search", "history_read"]);
549
+ assert.deepEqual(registered.map((spec) => spec.name), ["empty_brain", "get_context_remaining", "notes_write", "notes_update", "notes_read", "notes_list", "history_list", "history_search", "history_read"]);
528
550
  for (const spec of registered) {
529
551
  assert.equal(spec.isDeferred, false, `${spec.name} is available from the start without tool search`);
530
552
  assert.ok(spec.description.length > 20);
@@ -614,7 +636,7 @@ test("Claude Mod clears at the shared hard point after successful settlement and
614
636
  assert.match(kept[0].text, /Previous context window id: claude:hook-session:0/);
615
637
  assert.match(kept[0].text, /FRESH_NOTES_AT_RESET/);
616
638
  assert.doesNotMatch(kept[0].text, /OLD_SECRET/);
617
- assert.ok(FORCED_CONTINUATIONS.includes(kept[1].text), "the handoff comes from the shared forced pool");
639
+ assert.ok(BETWEEN_TURNS_CONTINUATIONS.includes(kept[1].text), "a post-answer hard clear uses the honest between-turns pool");
618
640
  assert.equal(compactions, 1, "invalidated tokens cannot immediately reset twice");
619
641
  const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
620
642
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => upstream), upstream, "the retained boot is not injected a second time");
@@ -731,7 +753,7 @@ test("Claude headless warns, automatically resets at the hard point, and support
731
753
  await settleHooks();
732
754
  }
733
755
  assert.equal(attempts, 3);
734
- assert.equal(prompts, 3, "one tool continuation and one close-out for each idle alias");
756
+ assert.equal(prompts, 2, "post-answer auto-reset submits no ghost continuation; only the two idle aliases submit close-outs");
735
757
  });
736
758
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
737
759
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -820,7 +842,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
820
842
  assert.equal(command.text, "🥣 Dumping Brain");
821
843
  await settleHooks();
822
844
  assert.equal(prompts.length, 1, "exactly one hidden normal-model close-out turn, not a summary");
823
- assert.equal(prompts[0], CLAUDE_WARNING_PROMPT, "the close-out is the same warning text the automatic path shows");
845
+ assert.equal(prompts[0], claudeCommandWarningContent(), "the manual close-out uses the command notice without false budget timing");
824
846
  assert.equal(compactions, 1);
825
847
  assert.equal(kept.length, 2);
826
848
  assert.match(kept[0].text, /Current context window id: claude:hook-session:1/);
@@ -832,9 +854,11 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
832
854
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] })), { blocks: [] }, "reload does not duplicate the already-retained boot");
833
855
  await invoke("turn.start");
834
856
  await invoke("command.run", { command: "empty" });
857
+ const busyTool = await invoke("tool.call", { tool: "Read" });
858
+ assert.deepEqual(busyTool.context, [claudeCommandWarningContent()], "busy /empty injects its close-out notice into the running turn's tool result");
835
859
  await invoke("turn.complete", turnComplete());
836
860
  await settleHooks();
837
- assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
861
+ assert.equal(prompts.length, 1, "a busy manual request that delivered its notice in-turn reuses the current turn instead of submitting another");
838
862
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
839
863
  });
840
864
  test("Claude failed close-outs release the request so manual reset can retry", async (t) => {
@@ -1063,7 +1087,12 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
1063
1087
  const home = mkdtempSync(join(tmpdir(), "claude-nolimits-home-"));
1064
1088
  t.after(() => rmSync(home, { recursive: true, force: true }));
1065
1089
  const { host, notifications } = fakeEngine(home);
1066
- host.process.run = async () => ({ exitCode: 1, stdout: "" });
1090
+ const run = host.process.run;
1091
+ host.process.run = async (argv, init) => {
1092
+ if (init?.stdin && JSON.parse(init.stdin).op === "limits")
1093
+ return { exitCode: 1, stdout: "" };
1094
+ return run(argv, init);
1095
+ };
1067
1096
  const handlers = new Map();
1068
1097
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1069
1098
  const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
@@ -1078,10 +1107,11 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
1078
1107
  assert.equal(compactions, 0, "an unresolvable point never resets");
1079
1108
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
1080
1109
  });
1081
- test("Claude skill projections stay byte-identical to canonical shared files", () => {
1082
- assert.deepEqual(readFileSync(join(process.cwd(), "plugins/claude/skills/notesoup/SKILL.md")), readFileSync(join(process.cwd(), "skills/notesoup/SKILL.md")));
1110
+ test("Claude skill projections stay byte-identical to canonical shared files and never collide with commands", () => {
1111
+ assert.deepEqual(readFileSync(join(process.cwd(), "plugins/claude/skills/notesoup-guide/SKILL.md")), readFileSync(join(process.cwd(), "skills/notesoup-guide/SKILL.md")));
1083
1112
  assert.deepEqual(readFileSync(join(process.cwd(), "plugins/claude/skills/dream/SKILL.md")), readFileSync(join(process.cwd(), "skills/dream/SKILL.md")));
1084
1113
  assert.deepEqual(readFileSync(join(process.cwd(), "plugins/claude/playbook.md")), readFileSync(join(process.cwd(), "playbook.md")));
1114
+ assert.equal(claudePluginOwnedBareCommands().size, 0, "no plugin skill shares the plugin's own bare slash-command name");
1085
1115
  const skill = readFileSync(join(process.cwd(), "plugins/claude/skills/dream/SKILL.md"), "utf8");
1086
1116
  assert.match(skill, /\.\.\/\.\.\/playbook\.md/);
1087
1117
  assert.doesNotMatch(skill, /Claude.*runner|dream runner/i);
@@ -1888,3 +1918,153 @@ test("Claude history without a documented path refuses honestly and keeps notes
1888
1918
  const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
1889
1919
  assert.match(boot.blocks[0].text, /History isn't available.*no main transcript_path/);
1890
1920
  });
1921
+ test("Claude Mod isolates command registration failures and disarms auto-reset when core tools fail to load", async (t) => {
1922
+ await t.test("command failure keeps all tools registered and logs/toasts loudly", async (t) => {
1923
+ const home = mkdtempSync(join(tmpdir(), "claude-cmd-fail-"));
1924
+ t.after(() => rmSync(home, { recursive: true, force: true }));
1925
+ const { host, registered, notifications } = fakeEngine(home);
1926
+ const toasts = [];
1927
+ host.ui.toast = async (text) => { toasts.push(text); };
1928
+ host.command.register = async (spec) => {
1929
+ throw new Error(`"/${spec.name}" refused`);
1930
+ };
1931
+ const handlers = new Map();
1932
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1933
+ await handlers.get("session.start")(host, { cwd: home, isInteractive: true }, async () => ({}));
1934
+ assert.equal(registered.length, 9, "every notesoup tool registers even when every slash command fails");
1935
+ for (const cmd of ["/notesoup", "/empty", "/fresh-window"]) {
1936
+ assert.ok(notifications.some((line) => line.includes(cmd) && line.includes("failed")), `log mentions ${cmd}`);
1937
+ assert.ok(toasts.some((line) => line.includes(cmd)), `toast mentions ${cmd}`);
1938
+ }
1939
+ });
1940
+ await t.test("core tool failure notifies, keeps native compaction, and never lies in boot or wipes blind", async (t) => {
1941
+ const home = mkdtempSync(join(tmpdir(), "claude-tools-degraded-"));
1942
+ t.after(() => rmSync(home, { recursive: true, force: true }));
1943
+ const { host, notifications } = fakeEngine(home);
1944
+ const run = host.process.run;
1945
+ host.process.run = async (argv, init) => {
1946
+ if (init?.stdin && JSON.parse(init.stdin).op === "schemas")
1947
+ return { exitCode: 1, stdout: "" };
1948
+ return run(argv, init);
1949
+ };
1950
+ let compactions = 0;
1951
+ host.session.usage = async () => ({ context: { tokens: 190_000, window: 200_000 } });
1952
+ host.command.run = async () => { compactions++; return {}; };
1953
+ const handlers = new Map();
1954
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1955
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1956
+ await invoke("session.start", { cwd: home, isInteractive: true });
1957
+ assert.ok(notifications.some((line) => line.includes("automatic brain reset disabled")));
1958
+ await invoke("turn.start");
1959
+ await invoke("turn.complete", turnComplete());
1960
+ await settleHooks();
1961
+ assert.equal(compactions, 0, "degraded startup never runs blind automatic reset");
1962
+ const nativeCompact = { messages: [{ role: "user", text: "native summary" }] };
1963
+ assert.deepEqual(await handlers.get("session.compact")(host, { trigger: "auto" }, async () => nativeCompact), nativeCompact, "auto compaction falls back to Claude's native summary when tools are missing");
1964
+ const boot = await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] }));
1965
+ assert.match(boot.blocks[0].text, /Notesoup tools failed to load/);
1966
+ assert.doesNotMatch(boot.blocks[0].text, /mcp__notesoup__notes_\*/);
1967
+ const emptyReply = await invoke("command.run", { command: "empty", args: "" });
1968
+ assert.match(emptyReply.text, /Notesoup tools unavailable/);
1969
+ const statusReply = await invoke("command.run", { command: "notesoup", args: "" });
1970
+ assert.match(statusReply.text, /degraded/);
1971
+ });
1972
+ });
1973
+ test("Claude Mod serves get_context_remaining, rich /notesoup status, and /empty args on idle and busy turns", async (t) => {
1974
+ const home = mkdtempSync(join(tmpdir(), "claude-ux-parity-"));
1975
+ t.after(() => rmSync(home, { recursive: true, force: true }));
1976
+ const { host } = fakeEngine(home);
1977
+ let tokens = 100_000;
1978
+ host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
1979
+ const prompts = [];
1980
+ host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
1981
+ const handlers = new Map();
1982
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1983
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
1984
+ await invoke("classic.SessionStart", { session_id: "hook-session", transcript_path: join(home, "t.jsonl") });
1985
+ await invoke("session.start", { cwd: home, isInteractive: true });
1986
+ const rem = await invoke("tool.call", { tool: "mcp__notesoup__get_context_remaining", tool_use_id: "rem-1" });
1987
+ assert.equal(rem.isError, undefined);
1988
+ assert.deepEqual(JSON.parse(rem.result), { remaining_tokens: CLAUDE_200K.reset - 100_000 });
1989
+ const subRem = await invoke("tool.call", { tool: "mcp__notesoup__get_context_remaining", tool_use_id: "rem-sub", agentId: "child" });
1990
+ assert.equal(subRem.isError, true);
1991
+ const status = await invoke("command.run", { command: "notesoup", args: "" });
1992
+ assert.match(status.text, /notesoup v/);
1993
+ assert.match(status.text, /cap off/);
1994
+ assert.match(status.text, /58,808 tokens left/);
1995
+ assert.match(status.text, /tools 9\/9/);
1996
+ assert.match(status.text, /history ready/);
1997
+ tokens = undefined;
1998
+ const unknownRem = await invoke("tool.call", { tool: "mcp__notesoup__get_context_remaining", tool_use_id: "rem-2" });
1999
+ assert.deepEqual(JSON.parse(unknownRem.result), { remaining_tokens: null });
2000
+ // Idle /empty <args> includes close-out context verbatim.
2001
+ assert.deepEqual(await invoke("command.run", { command: "empty", args: "keep Prefer untouched" }), { text: "🥣 Dumping Brain" });
2002
+ await settleHooks();
2003
+ assert.equal(prompts.length, 1);
2004
+ assert.equal(prompts[0], claudeCommandWarningContent("/empty keep Prefer untouched"));
2005
+ // Busy /empty <args> injects close-out context into the running turn's next tool result once.
2006
+ await invoke("turn.start", { turnId: "t-busy" });
2007
+ await invoke("turn.complete", turnComplete({ turnId: "t-busy", reason: "aborted" }));
2008
+ await invoke("turn.start", { turnId: "t-busy-2" });
2009
+ assert.deepEqual(await invoke("command.run", { command: "empty", args: "save frog findings" }), { text: "🥣 Dumping Brain" });
2010
+ const firstTool = await invoke("tool.call", { tool: "Read" });
2011
+ assert.deepEqual(firstTool.context, [claudeCommandWarningContent("/empty save frog findings")]);
2012
+ const secondTool = await invoke("tool.call", { tool: "Bash" });
2013
+ assert.equal(secondTool.context, undefined, "busy close-out notice is delivered once");
2014
+ await invoke("turn.complete", turnComplete({ turnId: "t-busy-2", reason: "aborted" }));
2015
+ // Busy /empty <args> when the turn finishes final text with NO further tool calls: runs one close-out turn so notes/args are never dropped.
2016
+ tokens = 50_000;
2017
+ let compactions = 0;
2018
+ host.command.run = async ({ args }) => {
2019
+ compactions++;
2020
+ await nativeCompaction(host, handlers, args);
2021
+ return {};
2022
+ };
2023
+ host.prompt.submit = async ({ text }) => {
2024
+ prompts.push(text);
2025
+ await invoke("turn.start", { turnId: "t-closeout-fallback" });
2026
+ await invoke("turn.complete", turnComplete({ turnId: "t-closeout-fallback" }));
2027
+ return { text };
2028
+ };
2029
+ await invoke("turn.start", { turnId: "t-text-only" });
2030
+ assert.deepEqual(await invoke("command.run", { command: "empty", args: "remember to fix A" }), { text: "🥣 Dumping Brain" });
2031
+ await invoke("turn.complete", turnComplete({ turnId: "t-text-only" }));
2032
+ await settleHooks();
2033
+ assert.equal(prompts.length, 2, "busy /empty without any tool call falls back to one close-out turn instead of dropping args");
2034
+ assert.equal(prompts[1], claudeCommandWarningContent("/empty remember to fix A"));
2035
+ assert.equal(compactions, 1, "close-out turn then commits one reset and stops");
2036
+ });
2037
+ test("Claude post-answer hard clear stays quiet while mid-turn cutoff resumes unfinished work", async (t) => {
2038
+ const { host, invoke, handlers } = await retainedFixture(t);
2039
+ let tokens = CLAUDE_200K.reset;
2040
+ host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
2041
+ const prompts = [];
2042
+ const continuations = [];
2043
+ host.prompt.submit = async ({ text }) => { prompts.push(text); return { text }; };
2044
+ host.command.run = async ({ args }) => {
2045
+ const result = await nativeCompaction(host, handlers, args);
2046
+ continuations.push(result.messages[1].text);
2047
+ tokens = undefined;
2048
+ return {};
2049
+ };
2050
+ // Post-answer hard clear (turn.complete with no turn.step cutoff): clears quietly without waking the model.
2051
+ await invoke("turn.start", { turnId: "post-answer" });
2052
+ await invoke("turn.complete", turnComplete({ turnId: "post-answer" }));
2053
+ await settleHooks();
2054
+ assert.equal(continuations.length, 1);
2055
+ assert.ok(BETWEEN_TURNS_CONTINUATIONS.includes(continuations[0]), "post-answer clear uses honest between-turns prose");
2056
+ assert.equal(prompts.length, 0, "post-answer clear never submits a ghost continuation turn");
2057
+ // Mid-turn cutoff (turn.step): stops the batch and resumes once with forced mid-flight prose.
2058
+ tokens = CLAUDE_200K.reset;
2059
+ await invoke("turn.start", { turnId: "mid-turn" });
2060
+ const step = handlers.get("turn.step");
2061
+ const chunks = [];
2062
+ for await (const chunk of step(host, { turnId: "mid-turn", index: 1 }, async function* () { yield { kind: "text", text: "nope" }; return {}; }))
2063
+ chunks.push(chunk);
2064
+ assert.deepEqual(chunks, [{ kind: "stop", stopReason: "end_turn", usage: null }]);
2065
+ await invoke("turn.complete", turnComplete({ turnId: "mid-turn" }));
2066
+ await settleHooks();
2067
+ assert.equal(continuations.length, 2);
2068
+ assert.ok(FORCED_CONTINUATIONS.includes(continuations[1]), "mid-turn cutoff keeps urgent forced prose");
2069
+ assert.equal(prompts.length, 1, "mid-turn cutoff continues once to finish the interrupted turn");
2070
+ });
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
- import { spawnSync } from "node:child_process";
3
- import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import test from "node:test";
@@ -73,3 +73,70 @@ for (const mutation of [
73
73
  assert.ok(result.report.contents.some((entry) => entry.errors.some((error) => error.path === "modules../register.ts")), result.stdout);
74
74
  });
75
75
  }
76
+ test("Claude mod loads cleanly in the installed engine and registers every tool and command", async (t) => {
77
+ const probe = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 10_000 });
78
+ if (probe.error?.code === "ENOENT") {
79
+ t.skip("Claude runtime load check skipped: claude is not installed (not found on PATH)");
80
+ return;
81
+ }
82
+ assert.ifError(probe.error);
83
+ const fixture = mkdtempSync(join(tmpdir(), "claude-runtime-load-"));
84
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
85
+ const debugFile = join(fixture, "claude-debug.log");
86
+ const child = spawn("claude", ["-p", "ok", "--plugin-dir", plugin, "--setting-sources", "", "--no-session-persistence", "--debug-file", debugFile], {
87
+ cwd: fixture,
88
+ stdio: ["ignore", "ignore", "ignore"],
89
+ env: {
90
+ ...process.env,
91
+ ANTHROPIC_BASE_URL: "http://127.0.0.1:1",
92
+ ANTHROPIC_AUTH_TOKEN: "notesoup-load-smoke",
93
+ API_TIMEOUT_MS: "2000",
94
+ NOTESOUP_HOME: join(fixture, "notes"),
95
+ },
96
+ });
97
+ t.after(() => {
98
+ if (child.exitCode === null && child.signalCode === null)
99
+ child.kill("SIGKILL");
100
+ });
101
+ const deadline = Date.now() + 20_000;
102
+ let log = "";
103
+ while (Date.now() < deadline) {
104
+ if (existsSync(debugFile)) {
105
+ log = readFileSync(debugFile, "utf8");
106
+ if (log.includes("session.start settled") && log.includes("notesoup"))
107
+ break;
108
+ if (log.includes("notesoup: session.start hook skipped"))
109
+ break;
110
+ }
111
+ if (child.exitCode !== null || child.signalCode !== null)
112
+ break;
113
+ await new Promise((resolve) => setTimeout(resolve, 100));
114
+ }
115
+ if (child.exitCode === null && child.signalCode === null) {
116
+ child.kill("SIGTERM");
117
+ await new Promise((resolve) => {
118
+ const timer = setTimeout(() => { child.kill("SIGKILL"); resolve(undefined); }, 2000);
119
+ child.once("exit", () => { clearTimeout(timer); resolve(undefined); });
120
+ });
121
+ }
122
+ if (existsSync(debugFile))
123
+ log = readFileSync(debugFile, "utf8");
124
+ assert.equal(log.includes("hook failed: notesoup"), false, `notesoup hook failed during session.start:\n${log}`);
125
+ assert.equal(log.includes("notesoup: session.start hook skipped"), false, `notesoup session.start skipped:\n${log}`);
126
+ for (const tool of [
127
+ "mcp__notesoup__empty_brain",
128
+ "mcp__notesoup__get_context_remaining",
129
+ "mcp__notesoup__notes_write",
130
+ "mcp__notesoup__notes_update",
131
+ "mcp__notesoup__notes_read",
132
+ "mcp__notesoup__notes_list",
133
+ "mcp__notesoup__history_list",
134
+ "mcp__notesoup__history_search",
135
+ "mcp__notesoup__history_read",
136
+ ]) {
137
+ assert.ok(log.includes(`$.tool.register (notesoup): ${tool}`), `missing tool registration ${tool}`);
138
+ }
139
+ for (const command of ["/notesoup", "/empty", "/fresh-window"]) {
140
+ assert.ok(log.includes(`$.command.register (notesoup): ${command} listed`), `missing command registration ${command}`);
141
+ }
142
+ });
@@ -29,7 +29,7 @@ test("dream skill is publicly discoverable and resolves the shared playbook", ()
29
29
  const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
30
30
  assert.deepEqual(manifest.pi.skills, ["./skills"]);
31
31
  assert.ok(manifest.files.includes("skills"));
32
- discoverSkill(join(root, "skills"), "notesoup");
32
+ discoverSkill(join(root, "skills"), "notesoup-guide");
33
33
  const skill = discoverSkill(join(root, "skills"), "dream");
34
34
  const reference = readFileSync(join(skill.baseDir, "SKILL.md"), "utf8").match(/`([^`]+playbook\.md)`/)?.[1];
35
35
  assert.ok(reference, "the skill links its playbook");
@@ -50,13 +50,13 @@ test("npm tarball keeps the skill's relative playbook path portable after extrac
50
50
  }))[0];
51
51
  const packedPaths = packed.files.map((file) => file.path);
52
52
  assert.ok(packedPaths.includes("skills/dream/SKILL.md"));
53
- assert.ok(packedPaths.includes("skills/notesoup/SKILL.md"));
53
+ assert.ok(packedPaths.includes("skills/notesoup-guide/SKILL.md"));
54
54
  assert.ok(packedPaths.includes("playbook.md"));
55
55
  const extracted = join(fixture, "extracted");
56
56
  execFileSync("mkdir", ["-p", extracted]);
57
57
  execFileSync("tar", ["-xzf", join(fixture, packed.filename), "-C", extracted]);
58
58
  const installedRoot = join(extracted, "package");
59
- discoverSkill(join(installedRoot, "skills"), "notesoup");
59
+ discoverSkill(join(installedRoot, "skills"), "notesoup-guide");
60
60
  const installedSkill = discoverSkill(join(installedRoot, "skills"), "dream");
61
61
  const reference = readFileSync(join(installedSkill.baseDir, "SKILL.md"), "utf8").match(/`([^`]+playbook\.md)`/)?.[1];
62
62
  assert.ok(reference, "the installed skill links its playbook");
@@ -182,7 +182,9 @@ export type ContextHookResult = {
182
182
  } | undefined;
183
183
  export declare function runContextHook(captured: Captured, ctx: ExtensionContext, eventOverride?: Record<string, unknown>): Promise<ContextHookResult>;
184
184
  export declare function runContextWithSystemHook(captured: Captured, ctx: ExtensionContext, messages: unknown[]): Promise<ContextHookResult>;
185
- export declare function commitTurnEndBoundary(captured: Captured, sessionManager: SessionManager, ctx: ExtensionContext): Promise<{
185
+ export declare function commitTurnEndBoundary(captured: Captured, sessionManager: SessionManager, ctx: ExtensionContext, options?: {
186
+ stopReason?: "stop" | "toolUse";
187
+ }): Promise<{
186
188
  entries: SessionBoundaryDraft[];
187
189
  continue: boolean;
188
190
  }>;
@@ -441,7 +441,7 @@ export async function runContextWithSystemHook(captured, ctx, messages) {
441
441
  }
442
442
  return result;
443
443
  }
444
- export async function commitTurnEndBoundary(captured, sessionManager, ctx) {
444
+ export async function commitTurnEndBoundary(captured, sessionManager, ctx, options) {
445
445
  let entries = [];
446
446
  let shouldContinue = false;
447
447
  const event = {
@@ -452,7 +452,7 @@ export async function commitTurnEndBoundary(captured, sessionManager, ctx) {
452
452
  outcome: "completed",
453
453
  turnIndex: 0,
454
454
  message: {
455
- role: "assistant", content: [], stopReason: "stop", timestamp: Date.now(),
455
+ role: "assistant", content: [], stopReason: options?.stopReason ?? "stop", timestamp: Date.now(),
456
456
  usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
457
457
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
458
458
  },
@@ -1,9 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { DEFAULT_BOOT_TOOL_NAMES, NOTES_PROTOCOL_CLOSE_TAG, renderProtocolBlock } from "../src/boot/text.js";
4
- import { CLAUDE_WARNING_PROMPT } from "../plugins/claude/src/text.js";
4
+ import { CLAUDE_COMMAND_NOTICE, CLAUDE_WARNING_PROMPT, claudeCommandWarningContent } from "../plugins/claude/src/text.js";
5
5
  import { COMMAND_NOTICE, PI_PRE_RESET_HINTS, commandWarningContent, warningContent } from "../plugins/pi/text.js";
6
- import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, WARNING_BODY, WARNING_CALL, WARNING_TIMING, selectContinuation, tokenBudgetGuidance } from "../src/budget/text.js";
6
+ import { BETWEEN_TURNS_CONTINUATIONS, COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, WARNING_BODY, WARNING_CALL, WARNING_TIMING, selectContinuation, tokenBudgetGuidance } from "../src/budget/text.js";
7
7
  test("early guidance binds the remaining room and the host's reset tool", () => {
8
8
  const guidance = tokenBudgetGuidance(1234, "forget_this");
9
9
  assert.ok(guidance.startsWith(`${GUIDANCE_OPEN_TAG}\n`));
@@ -27,6 +27,12 @@ test("the countdown closes the second-tier notice only, in both hosts", () => {
27
27
  assert.ok(CLAUDE_WARNING_PROMPT.endsWith(`\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`));
28
28
  assert.equal(prompted.includes(WARNING_TIMING), false, "manual requests replace the budget opening");
29
29
  assert.equal(tokenBudgetGuidance(100, "empty_brain").includes(COUNTDOWN_LINE), false, "the first tier never counts down");
30
+ const claudeBare = claudeCommandWarningContent();
31
+ const claudePrompted = claudeCommandWarningContent("/empty keep going");
32
+ assert.equal(claudeBare, `${GUIDANCE_OPEN_TAG}\n${CLAUDE_COMMAND_NOTICE.bare}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}`);
33
+ assert.equal(claudePrompted, `${GUIDANCE_OPEN_TAG}\n${CLAUDE_COMMAND_NOTICE.prompted}\n${WARNING_BODY}\n${WARNING_CALL}\n${COUNTDOWN_LINE}\n${GUIDANCE_CLOSE_TAG}\n/empty keep going`);
34
+ assert.equal(claudeBare.includes("erased afterward"), false, "Claude manual close-out never claims the chat view is erased");
35
+ assert.equal(claudeBare.includes(WARNING_TIMING), false, "Claude manual close-out omits budget timing");
30
36
  });
31
37
  test("only Pi's protocol explains that reset erases the human's view", () => {
32
38
  const pi = renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS });
@@ -42,19 +48,23 @@ test("only Pi's protocol explains that reset erases the human's view", () => {
42
48
  test("continuations draw a complete entry from the pool for their reset origin", () => {
43
49
  assert.ok(NORMAL_CONTINUATIONS.length > 0);
44
50
  assert.ok(FORCED_CONTINUATIONS.length > 0);
51
+ assert.ok(BETWEEN_TURNS_CONTINUATIONS.length > 0);
45
52
  const random = Math.random;
46
53
  try {
47
54
  Math.random = () => 0;
48
55
  assert.equal(selectContinuation("normal"), NORMAL_CONTINUATIONS[0]);
49
56
  assert.equal(selectContinuation("forced"), FORCED_CONTINUATIONS[0]);
57
+ assert.equal(selectContinuation("forced", { betweenTurns: true }), BETWEEN_TURNS_CONTINUATIONS[0]);
58
+ assert.equal(selectContinuation("normal", { betweenTurns: true }), NORMAL_CONTINUATIONS[0], "voluntary resets stay in the normal pool");
50
59
  Math.random = () => 0.999999;
51
60
  assert.equal(selectContinuation("normal"), NORMAL_CONTINUATIONS.at(-1), "the last entry is reachable without leaving the pool");
52
61
  assert.equal(selectContinuation("forced"), FORCED_CONTINUATIONS.at(-1));
62
+ assert.equal(selectContinuation("forced", { betweenTurns: true }), BETWEEN_TURNS_CONTINUATIONS.at(-1));
53
63
  }
54
64
  finally {
55
65
  Math.random = random;
56
66
  }
57
- for (const line of [...NORMAL_CONTINUATIONS, ...FORCED_CONTINUATIONS]) {
67
+ for (const line of [...NORMAL_CONTINUATIONS, ...FORCED_CONTINUATIONS, ...BETWEEN_TURNS_CONTINUATIONS]) {
58
68
  assert.ok(line.length > 0);
59
69
  assert.equal(/[\r\n]/.test(line), false, "a pool entry is one complete paragraph");
60
70
  assert.equal(line.trim(), line, "no entry carries stray surrounding whitespace");
@@ -140,6 +140,7 @@ function turnEndFacts(overrides = {}) {
140
140
  queued: false,
141
141
  automaticResetEnabled: true,
142
142
  hardReserveDue: false,
143
+ hasPendingWork: true,
143
144
  ...overrides,
144
145
  };
145
146
  }
@@ -808,6 +809,7 @@ test("reset-control: lazy guards preserve overflow policy ordering", () => {
808
809
  get queued() { calls.queued += 1; return false; },
809
810
  get automaticResetEnabled() { calls.automatic += 1; return true; },
810
811
  get hardReserveDue() { calls.hardReserve += 1; return true; },
812
+ hasPendingWork: true,
811
813
  };
812
814
  reduceResetControl(initialResetControl(), { type: "turn_end", facts });
813
815
  assert.deepEqual(calls, { queued: 1, automatic: 1, hardReserve: 0 }, "overflow checks never consult hard-reserve policy");
@@ -989,6 +991,14 @@ test("reset-control: the origin is the empty_brain call, independent of command
989
991
  const acknowledged = reduceResetControl(manual, { type: "tool_request", windowId }).state;
990
992
  assert.equal(boundaryIntent(reduceResetControl(acknowledged, { type: "before_settle", facts: beforeSettleFacts() })).origin, "normal", "a manual close-out the model actually wipes is normal but still stops");
991
993
  assert.equal(boundaryIntent(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) })).origin, "forced", "the hard cutoff happens without a call");
994
+ assert.equal(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true, hasPendingWork: false, deferBetweenTurns: true }) }).effect, "none", "a clean final answer defers rollover in TUI so the last reply stays visible");
995
+ const quietReset = boundaryIntent(reduceResetControl(initialResetControl(), { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true, hasPendingWork: false, deferBetweenTurns: false }) }));
996
+ assert.equal(quietReset.origin, "forced");
997
+ assert.equal(quietReset.betweenTurns, true);
998
+ assert.equal(quietReset.continueAfterReset, false, "non-TUI between-turns rollover does not wake a ghost turn");
999
+ const finalizedQuiet = finalizeResetBoundary(quietReset, initialResetControl().request);
1000
+ assert.equal(finalizedQuiet.resumeModel, false);
1001
+ assert.equal(finalizedQuiet.state.stopAfterReset, undefined, "clean between-turns reset installs no tool-followup stop latch");
992
1002
  const intent = boundaryIntent(reduceResetControl(acknowledged, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
993
1003
  assert.equal(intent.origin, "normal", "an acknowledged call survives the hard cutoff it was armed against");
994
1004
  const safety = finalizeResetBoundary(intent, acknowledged.request);
@@ -1,6 +1,6 @@
1
1
  # Claude Code Mod
2
2
 
3
- The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers four notes tools as `mcp__notesoup__notes_*`, two 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.
3
+ The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers four notes tools as `mcp__notesoup__notes_*`, three history tools as `mcp__notesoup__history_*`, `mcp__notesoup__empty_brain`, and `mcp__notesoup__get_context_remaining`, 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. Startup registers core tools before slash commands and isolates each registration: a broken command logs/toasts without killing tools, and if core notes/wipe tools fail to register the mod enters an explicit degraded state that notifies the human, disables automatic brain resets, passes compaction through to Claude natively, and avoids injecting false tool instructions.
4
4
 
5
5
  Warning and automatic clear use one budget policy. The existing warning and reset points are derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reach the sandboxed hooks module through the helper's `limits` operation. At the hard point, the next main `turn.step` ends the old turn after its whole tool batch; a successful main `turn.complete` also checks the point when no request is already pending. Both enter the existing non-held reset worker, without a separate cap-specific trigger. Measurement alone never clears context, child events cannot reset the main brain, and aborted/error/refusal turns do not commit a budget reset. The policy resolves its native point as follows:
6
6
 
@@ -10,23 +10,23 @@ Warning and automatic clear use one budget policy. The existing warning and rese
10
10
 
11
11
  The hard clear point is `resetMarginTokens` (default 8192) below the native point; the warning is another `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that. Resolved points are reused only while the current model, cap, threshold inputs and settings match; changing context fill alone does not invalidate them. 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 warning margins still apply, but automatic notesoup clears are disabled too. Explicit resets remain available. 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
- `/notesoup cap 100k` supplies a runtime-only capacity ceiling, clamped to the smaller model/configured window before the same reserves and margins are deducted. A reported native threshold can only be lowered, never raised. `/notesoup cap` (or bare `/notesoup`) shows the cap; `/notesoup cap off` restores the uncapped policy. Whole tokens and decimal `k`/`m` suffixes are accepted, with caps too small for reserves refused. The cap survives notesoup rollover and model changes but is cleared on plugin reload, session end or session identity change. It does not call `/autocompact`, alter the model, or write settings/environment variables. An already pending reset keeps its continuation/STOP policy when the cap changes.
13
+ `/notesoup cap 100k` supplies a runtime-only capacity ceiling, clamped to the smaller model/configured window before the same reserves and margins are deducted. A reported native threshold can only be lowered, never raised. `/notesoup cap` (or bare `/notesoup`) reports version, cap, remaining tokens to reset, tool count, and history readiness (or degraded status); `/notesoup cap off` restores the uncapped policy. Whole tokens and decimal `k`/`m` suffixes are accepted, with caps too small for reserves refused. The cap survives notesoup rollover and model changes but is cleared on plugin reload, session end or session identity change. It does not call `/autocompact`, alter the model, or write settings/environment variables. An already pending reset keeps its continuation/STOP policy when the cap changes. `mcp__notesoup__get_context_remaining` reports remaining tokens to the hard-reset line (`null` when unknown) and refuses subagents.
14
14
 
15
15
  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.
16
16
 
17
17
  The reset flow has three separate lifetimes. `ResetFlow.request` lasts until successful reset or cancellation; it owns the first valid tool call's sticky note and continuation policy. `ResetState.commit` lasts for one native command attempt and tracks proof that Claude kept the boot. The per-turn cutoff can outlive the request when native auto compaction consumes it before the next step. Successful explicit reset and automatic reset share the same window/boot bookkeeping. A failed compaction retains the request for retry; an aborted, failed, or refused main turn cancels it. Session changes discard the flow and invalidate asynchronous work by generation.
18
18
 
19
- `empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. The automatic hard point uses the same cutoff and commit path; a budget reset uses the forced handoff pool and continues once only after a confirmed commit, unless manual STOP or natural input takes over. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
19
+ `empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. Automatic hard-point clears distinguish mid-turn cutoffs from settled turns: a `turn.step` cutoff interrupts unfinished work, uses the forced mid-flight handoff pool, and continues once after a confirmed commit (unless manual STOP or natural input takes over); a `turn.complete` hard clear with no prior cutoff already delivered its final answer, so it rotates quietly to a fresh window with an honest between-turns handoff and `resume: false`, waiting for the human's next message without a ghost continuation. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation only when `resume` is true and neither `terminate: true`, manual STOP, nor natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
20
20
 
21
21
  Accepted natural input owns its continuation. Input received within the running turn, including input accepted before the first tool latch, releases the cutoff at the next step for the whole subsequent tool workflow. Input not yet delivered to a model request prevents reset work from starting. A separately queued natural turn also runs normally. No input is replayed. Native auto compaction consumes a pending request without resetting twice, while preserving its armed cutoff until turn completion or natural-input delivery; further auto compaction does not disarm it. Once that reset has completed and natural input releases its cutoff, a new `empty_brain` owns its own sticky and `terminate` policy. A consumed request's STOP does not carry into the new request.
22
22
 
23
- `/empty` and `/fresh-window` request STOP for the same pending or in-flight reset, including one first requested by a tool. While idle they start one hidden normal-model close-out using the shared budget warning, so the model can save notes; while busy they use the current turn. A close-out tool call may select the normal handoff pool and sticky but cannot undo manual STOP. If the warning cannot load, submission fails, or another hook drops it, the request is cancelled so the command can retry. STOP controls automatic continuation; handoff selection still follows actual tool origin (normal) or no tool origin (forced). `DISABLE_COMPACT` refuses explicit requests and suppresses warnings.
23
+ `/empty` and `/fresh-window` (with optional context text) request STOP for the same pending or in-flight reset, including one first requested by a tool. While idle they start one hidden normal-model close-out using Claude's manual close-out notice (with any trailing arguments verbatim as context for notes); while busy they inject that close-out notice into the running turn's next tool result once so the model can save notes before clearing, and if the running turn finishes without any further tool call while budget room remains, `turn.complete` runs one close-out turn before resetting so notes and any trailing context text are not lost. A close-out tool call may select the normal handoff pool and sticky but cannot undo manual STOP. If the warning cannot load, submission fails, or another hook drops it, the request is cancelled so the command can retry. STOP controls automatic continuation; handoff selection still follows actual tool origin (normal) or no tool origin (forced). `DISABLE_COMPACT` refuses explicit requests and suppresses warnings.
24
24
 
25
25
  Both interactive and headless (`-p` / SDK) resets use `$.command.run({command:"compact",args:...})`. A waiter armed in `session.start` runs this work outside held hooks and re-arms before submitting a close-out, avoiding prompt deadlock and lost completion signals. The command carries a unique instruction marker stored in its commit attempt; only matching manual compaction is admitted, while user `/compact` stays vetoed. Direct `$.session.compact` skips the calling mod's hook interactively and is unavailable headlessly. The command is enqueued before `turn.complete` returns, supporting single-prompt `-p` runs and open SDK streams.
26
26
 
27
- A command receipt and prepared boot are not commit evidence. On Claude Code 2.1.319, interactive completion exposes the installed boot through `$.session.messages()`. Headless completion still exposes the old request snapshot and precedes appends, so the worker waits for successful main `session.append` results: a kept compact boundary followed by the unchanged boot with its UUID. A missing or rewritten boot, veto, or rejected command cannot start continuation. Boot acquisition failure vetoes an explicit reset without advancing the window. After commit, a dropped or failed continuation is reported without compacting again. Native command/output rows remain alongside the fresh boot; no compaction model request is made. A Claude dream backend is not implemented, and budget reporting (`get_context_remaining`) remains Pi-only.
27
+ A command receipt and prepared boot are not commit evidence. On Claude Code 2.1.319, interactive completion exposes the installed boot through `$.session.messages()`. Headless completion still exposes the old request snapshot and precedes appends, so the worker waits for successful main `session.append` results: a kept compact boundary followed by the unchanged boot with its UUID. A missing or rewritten boot, veto, or rejected command cannot start continuation. Boot acquisition failure vetoes an explicit reset without advancing the window. After commit, a dropped or failed continuation is reported without compacting again. Native command/output rows remain alongside the fresh boot; no compaction model request is made. A Claude dream backend is not implemented.
28
28
 
29
- The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared notesoup and dream skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
29
+ The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared `notesoup-guide` and `dream` skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
30
30
 
31
31
  ## Persisted history
32
32
 
@@ -16,7 +16,7 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
16
16
  | Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once from notes, without replaying the failed request's input. |
17
17
  | Command close-out overflow | Force a reset even if automatic reset is disabled. Apply command policy: continue with separate carried input, otherwise stop. The recovery attempt is spent, so an oversized carried prompt cannot loop. |
18
18
  | Budget warning | Stage reminders when automatic reset is enabled. Warnings alone never authorize reset. |
19
- | Hard reserve | Independently reset at `turn_end` when automatic reset is enabled and continue without replaying submitted text/images. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
19
+ | Hard reserve | When automatic reset is enabled: mid-turn work (tool batch, pre-send cutoff, queued input, or manual close-out) resets at `turn_end` and continues without replaying already-submitted text/images. For a clean final answer: non-erasing modes (`rpc`, `json`, `print`) rotate quietly at `turn_end` with `betweenTurns: true` and `continue: false` (no ghost turn, no `input` interception); Pi TUI (`mode === "tui"`) keeps the reply visible on screen and rolls over cleanly on the next idle interactive input whenever that input would exceed hard reserve and still fits a fresh window (preserving `/skill:*` and prompt-template expansion), while an oversized paste falls back to pre-send history reset. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
20
20
  | Abort / ordinary error | Restore stashed originals as visible user-content custom messages before clearing command state. Explicit abort stays stopped; ordinary close-out errors trigger a turn for the restored input without forcing a reset. |
21
21
  | `/compact` while active | Cancel native compaction; manual attempts receive a `/fresh-window` notice. |
22
22
 
package/docs/skills.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Skills and dream
2
2
 
3
- ## Notesoup skill
3
+ ## Notesoup guide skill
4
4
 
5
- The package provides `/skill:notesoup`, a short self-contained guide to the notes and history tools: note addresses and notebooks, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; current-session history requires the documented main-session transcript path and a confirmed append head, while explicit `session` selectors use the local cross-harness corpus (offline Claude prefers non-attachment leaves, then the last leaf in transcript order).
5
+ The package provides `/skill:notesoup-guide`, a short self-contained guide to the notes and history tools: note addresses and notebooks, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; current-session history requires the documented main-session transcript path and a confirmed append head, while explicit `session` selectors use the local cross-harness corpus (offline Claude prefers non-attachment leaves, then the last leaf in transcript order).
6
6
 
7
7
  ## Dream
8
8
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.62.0",
3
+ "version": "0.63.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.62.0",
3
+ "version": "0.63.0",
4
4
  "description": "Session and durable notes with native conversation boot",
5
5
  "repository": "https://github.com/astrosheep-zero/notesoup"
6
6
  }