notesoup 0.58.0 → 0.58.1

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.
@@ -58,16 +58,6 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
58
58
  native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
59
59
  };
60
60
  }
61
- /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
62
- function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
63
- const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
64
- const native = pct === undefined ? base : Math.min(pct, base);
65
- const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
66
- return {
67
- source: "percent", autoCompact, unit: "percent",
68
- native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
69
- };
70
- }
71
61
  /**
72
62
  * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
73
63
  * so a missing or malformed one degrades to the next source and finally to the percent
@@ -98,20 +88,23 @@ export function resolveClaudeLimits(facts) {
98
88
  if (native > 0)
99
89
  return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
100
90
  }
101
- // (b) The same point computed from the reported window plus settings and environment. A real
102
- // window always answers here: falling through to the percent fallback would express the
103
- // points on an assumed 200K window, which is later than the window notesoup can see.
91
+ // (b/c) Compute once, using the classic 200K capacity only when the host reports none.
104
92
  const window = positiveNumber(usage.window);
105
- if (window !== undefined) {
106
- const configured = configuredWindow(settings, env, breakdown.model);
107
- const effective = Math.min(configured ?? window, window);
108
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
109
- const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
110
- const native = autoCompact
111
- ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold)
112
- : available;
113
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
114
- }
115
- // (c) Nothing usable but percentages.
116
- return percentLimits(autoCompact, pct, resetMargin, warningRunway);
93
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
94
+ const configured = configuredWindow(settings, env, breakdown.model);
95
+ const effective = Math.min(configured ?? capacity, capacity);
96
+ const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
97
+ const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
98
+ const native = autoCompact
99
+ ? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
100
+ : available;
101
+ const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
102
+ if (window !== undefined)
103
+ return limits;
104
+ return {
105
+ ...limits, unit: "percent",
106
+ native: limits.native / capacity * 100,
107
+ reset: Math.max(MIN_POINT_PERCENT, limits.reset / capacity * 100),
108
+ warn: Math.max(MIN_POINT_PERCENT, limits.warn / capacity * 100),
109
+ };
117
110
  }
@@ -66,7 +66,7 @@ function fakeEngine(home) {
66
66
  settings: { read: async () => ({}) },
67
67
  command: { run: async () => ({}), register: async (spec) => ({ command: spec.name }) },
68
68
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
69
- prompt: { submit: async () => undefined },
69
+ prompt: { submit: async ({ text }) => ({ text }) },
70
70
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
71
71
  ui: { toast: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
72
72
  process: { run: async (argv, init) => ({
@@ -237,7 +237,17 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
237
237
  assert.equal(percent.source, "percent");
238
238
  assert.equal(percent.unit, "percent");
239
239
  assert.ok(Math.abs(percent.native - 83.5) < 1e-9 && Math.abs(percent.reset - 79.404) < 1e-9 && Math.abs(percent.warn - 71.212) < 1e-9, "83.5 / 79.4 / 71.2 on 200K");
240
- assert.equal(limitPoints({ env: { pctOverride: "50" } }).native, 50);
240
+ for (const facts of [
241
+ { env: { pctOverride: "50" } },
242
+ { settings: { autoCompactEnabled: false }, env: { pctOverride: "10" } },
243
+ { settings: { autoCompactWindow: 100_000 } },
244
+ ]) {
245
+ const fallback = resolveClaudeLimits(facts);
246
+ const tokens = resolveClaudeLimits({ ...facts, usage: { window: 200_000 } });
247
+ for (const point of ["native", "reset", "warn"])
248
+ assert.ok(Math.abs(fallback[point] - tokens[point] / 200_000 * 100) < 1e-9, `${point}: percent fallback uses the same token derivation`);
249
+ assert.equal(fallback.autoCompact, tokens.autoCompact);
250
+ }
241
251
  // A real window is never re-expressed on the assumed 200K window, and no point is zero:
242
252
  // the mod treats `measured >= reset` as due, so a zero point would clear memory every turn.
243
253
  const tiny = limitPoints({ usage: { window: 8_000 } });
@@ -659,7 +669,7 @@ test("Claude headless warns without proactive resets and supports both manual al
659
669
  const timers = [];
660
670
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
661
671
  host.clock.after = (_ms, callback) => { timers.push(callback); };
662
- host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); };
672
+ host.prompt.submit = async ({ text }) => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); return { text }; };
663
673
  host.command.run = async ({ command }) => {
664
674
  attempts++;
665
675
  await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
@@ -688,12 +698,6 @@ test("Claude headless warns without proactive resets and supports both manual al
688
698
  }
689
699
  assert.equal(attempts, 3);
690
700
  assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
691
- host.prompt.submit = async () => { throw new Error("close-out unavailable"); };
692
- await invoke("command.run", { command: "empty" });
693
- await Promise.resolve();
694
- await timers.shift()();
695
- await invoke("turn.complete", turnComplete());
696
- assert.equal(attempts, 4, "a failed close-out also leaves the reset pending");
697
701
  });
698
702
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
699
703
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -768,6 +772,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
768
772
  prompts.push(text);
769
773
  await invoke("turn.start");
770
774
  await invoke("turn.complete", turnComplete());
775
+ return { text };
771
776
  };
772
777
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
773
778
  await invoke("session.start", { cwd: home, isInteractive: true });
@@ -797,6 +802,51 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
797
802
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
798
803
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
799
804
  });
805
+ test("Claude failed close-outs release the request so manual reset can retry", async (t) => {
806
+ for (const failure of ["texts", "submit", "drop"])
807
+ await t.test(failure, async (t) => {
808
+ const home = mkdtempSync(join(tmpdir(), "claude-closeout-retry-"));
809
+ t.after(() => rmSync(home, { recursive: true, force: true }));
810
+ const { host, notifications } = fakeEngine(home);
811
+ const helper = host.process.run;
812
+ let failing = true, resets = 0;
813
+ host.process.run = async (argv, init) => failing && failure === "texts" && JSON.parse(init.stdin).op === "texts"
814
+ ? { exitCode: 1, stdout: "" } : helper(argv, init);
815
+ const handlers = new Map();
816
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
817
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
818
+ const timers = [];
819
+ host.clock.after = (_ms, callback) => { timers.push(callback); };
820
+ host.prompt.submit = async ({ text }) => {
821
+ if (failing && failure === "submit")
822
+ throw new Error("submission unavailable");
823
+ if (failing && failure === "drop")
824
+ return { drop: "another plugin refused" };
825
+ await invoke("turn.start");
826
+ await invoke("turn.complete", turnComplete());
827
+ return { text };
828
+ };
829
+ host.session.compact = async ({ instructions }) => {
830
+ resets++;
831
+ return await invoke("session.compact", { trigger: "plugin", instructions });
832
+ };
833
+ await invoke("session.start", { isInteractive: true });
834
+ await invoke("command.run", { command: "fresh-window" });
835
+ await Promise.resolve();
836
+ await timers.shift()();
837
+ assert.equal(resets, 0);
838
+ assert.ok(notifications.some(text => text.includes("close-out")), "failure is visible");
839
+ await invoke("turn.start");
840
+ await invoke("turn.complete", turnComplete());
841
+ assert.equal(resets, 0, "a failed close-out must not spring a reset on an unrelated turn");
842
+ failing = false;
843
+ assert.deepEqual(await invoke("command.run", { command: "fresh-window" }), { text: "🥣 Dumping Brain" });
844
+ await Promise.resolve();
845
+ assert.equal(timers.length, 1, "retry schedules new work instead of claiming it is already running");
846
+ await timers.shift()();
847
+ assert.equal(resets, 1);
848
+ });
849
+ });
800
850
  test("Claude Mod delivers one warning per window through main tools or prompt submission, never boot", async (t) => {
801
851
  const { host, invoke, context } = await retainedFixture(t);
802
852
  const texts = await dispatch({ op: "texts" });
@@ -856,6 +906,40 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
856
906
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
857
907
  }
858
908
  });
909
+ test("Claude warning limits follow live model, threshold and settings changes without re-resolving for fill", async (t) => {
910
+ const home = mkdtempSync(join(tmpdir(), "claude-live-limits-"));
911
+ t.after(() => rmSync(home, { recursive: true, force: true }));
912
+ const { host } = fakeEngine(home);
913
+ let model = "claude-a", threshold = 167_000, tokens = 10_000;
914
+ const settings = { notesoup: { warningRunwayTokens: WARNING_RUNWAY_TOKENS } };
915
+ host.session.model = async () => model;
916
+ host.session.usage = async () => ({ context: { tokens, window: 200_000, breakdown: { model, autoCompactThreshold: threshold } } });
917
+ host.settings.read = async () => settings;
918
+ const helper = host.process.run;
919
+ let resolutions = 0;
920
+ host.process.run = async (argv, init) => {
921
+ if (JSON.parse(init.stdin).op === "limits")
922
+ resolutions++;
923
+ return helper(argv, init);
924
+ };
925
+ const handlers = new Map();
926
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
927
+ await handlers.get("session.start")(host, { isInteractive: true }, async (e) => e);
928
+ const submit = () => handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
929
+ assert.equal((await submit()).context, undefined);
930
+ tokens = 30_000;
931
+ assert.equal((await submit()).context, undefined);
932
+ assert.equal(resolutions, 1, "changing fill reuses the points");
933
+ model = "claude-b";
934
+ assert.equal((await submit()).context, undefined);
935
+ assert.equal(resolutions, 2, "a model change invalidates points even at the same capacity");
936
+ threshold = 67_000;
937
+ assert.equal((await submit()).context, undefined);
938
+ assert.equal(resolutions, 3, "a live threshold change invalidates points without a model change");
939
+ settings.notesoup.warningRunwayTokens = 30_000;
940
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
941
+ assert.equal(resolutions, 4, "settings changes apply without a session or capacity change");
942
+ });
859
943
  test("Claude Mod consumes a warning only after an accepted delivery and ignores stale generations", async (t) => {
860
944
  const { host, invoke } = await retainedFixture(t);
861
945
  const texts = await dispatch({ op: "texts" });
@@ -1134,7 +1218,7 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1134
1218
  const timers = [];
1135
1219
  const lines = [];
1136
1220
  host.clock.after = (_ms, callback) => { timers.push(callback); };
1137
- host.prompt.submit = async () => { await invoke("turn.start"); };
1221
+ host.prompt.submit = async ({ text }) => { await invoke("turn.start"); return { text }; };
1138
1222
  // The host retries one plugin compaction for the same window: one artifact, one draw.
1139
1223
  host.session.compact = async ({ instructions }) => {
1140
1224
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -6,15 +6,15 @@ There is no independent proactive automatic clear line: crossing a measured thre
6
6
 
7
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
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
- 3. otherwise the percent fallback, which expresses the same reserves on the classic 200K window.
9
+ 3. otherwise the percent fallback, which assumes a classic 200K capacity, applies the same configured-window caps and token derivation, then converts the points to percentages.
10
10
 
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.
11
+ The warning remains `resetMarginTokens` (default 8192) plus `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that point. Resolved points are reused only while the current model, threshold inputs and settings match; changing context fill alone does not invalidate them. 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
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
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
- `/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.
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. If that prompt cannot load, submission fails, or another hook drops it, the request is cancelled so `/fresh-window` can retry; an unrelated later turn does not reset on its behalf. 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. Once the close-out has started, rejected or vetoed compactions 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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.58.0",
3
+ "version": "0.58.1",
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.58.0",
3
+ "version": "0.58.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -11476,21 +11476,6 @@ function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
11476
11476
  warningRunway
11477
11477
  };
11478
11478
  }
11479
- function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
11480
- const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
11481
- const native = pct === void 0 ? base : Math.min(pct, base);
11482
- const reset = Math.max(MIN_POINT_PERCENT, native - resetMargin / ASSUMED_WINDOW_TOKENS * 100);
11483
- return {
11484
- source: "percent",
11485
- autoCompact,
11486
- unit: "percent",
11487
- native,
11488
- reset,
11489
- warn: Math.max(MIN_POINT_PERCENT, reset - warningRunway / ASSUMED_WINDOW_TOKENS * 100),
11490
- resetMargin,
11491
- warningRunway
11492
- };
11493
- }
11494
11479
  function resolveClaudeLimits(facts) {
11495
11480
  const root = isPlainObject(facts) ? facts : {};
11496
11481
  const usage = isPlainObject(root.usage) ? root.usage : {};
@@ -11504,19 +11489,25 @@ function resolveClaudeLimits(facts) {
11504
11489
  const pct = percent(env.pctOverride);
11505
11490
  const threshold = positiveNumber(breakdown.autoCompactThreshold);
11506
11491
  if (autoCompact && threshold !== void 0) {
11507
- const native = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
11508
- if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
11492
+ const native2 = pct === void 0 ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
11493
+ if (native2 > 0) return tokenLimits("auto-compact", true, native2, resetMargin, warningRunway);
11509
11494
  }
11510
11495
  const window = positiveNumber(usage.window);
11511
- if (window !== void 0) {
11512
- const configured = configuredWindow(settings2, env, breakdown.model);
11513
- const effective = Math.min(configured ?? window, window);
11514
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
11515
- const threshold2 = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
11516
- const native = autoCompact ? pct === void 0 ? threshold2 : Math.min(Math.floor(available * (pct / 100)), threshold2) : available;
11517
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
11518
- }
11519
- return percentLimits(autoCompact, pct, resetMargin, warningRunway);
11496
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
11497
+ const configured = configuredWindow(settings2, env, breakdown.model);
11498
+ const effective = Math.min(configured ?? capacity, capacity);
11499
+ const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
11500
+ const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
11501
+ const native = autoCompact ? pct === void 0 ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow) : available;
11502
+ const limits = tokenLimits(window === void 0 ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
11503
+ if (window !== void 0) return limits;
11504
+ return {
11505
+ ...limits,
11506
+ unit: "percent",
11507
+ native: limits.native / capacity * 100,
11508
+ reset: Math.max(MIN_POINT_PERCENT, limits.reset / capacity * 100),
11509
+ warn: Math.max(MIN_POINT_PERCENT, limits.warn / capacity * 100)
11510
+ };
11520
11511
  }
11521
11512
 
11522
11513
  // plugins/claude/src/helper.ts
@@ -22,7 +22,7 @@ type ResetState = {
22
22
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
23
23
  toolResetRequested?: boolean; lastWord?: string; manualCompacting?: boolean
24
24
  continuation?: string; continuationWindow?: number
25
- compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
25
+ compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsKey?: string
26
26
  limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
27
27
  }
28
28
  const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
@@ -131,11 +131,12 @@ async function breakdownContext($: Engine): Promise<Record<string, unknown> | un
131
131
  return typeof breakdown === "object" && breakdown !== null ? breakdown as unknown as Record<string, unknown> : undefined
132
132
  } catch { return undefined }
133
133
  }
134
- /** Everything the resolver may read: measured usage plus the raw settings and environment. */
134
+ /** Threshold inputs only: changing fill must not invalidate the resolved points. */
135
135
  async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Promise<Record<string, unknown>> {
136
+ const breakdown = await breakdownContext($)
136
137
  return {
137
- usage,
138
- breakdown: await breakdownContext($),
138
+ usage: { window: usage.window },
139
+ breakdown: { model: breakdown?.model, autoCompactThreshold: breakdown?.autoCompactThreshold, isAutoCompactEnabled: breakdown?.isAutoCompactEnabled },
139
140
  settings: await readSettings($, state),
140
141
  env: {
141
142
  pctOverride: await envPctOverride($),
@@ -144,35 +145,26 @@ async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Pr
144
145
  },
145
146
  }
146
147
  }
147
- /**
148
- * The points the current window is measured against, resolved by the helper's shared
149
- * derivation. One resolved result per reported window value: an unknown window resolves the
150
- * percent fallback, and a later real window re-resolves against it. A failed round trip is
151
- * retried a bounded number of times instead of disabling thresholds for the whole window.
152
- */
148
+ /** Reuse points only while their inputs match; bound retries per configuration, not capacity. */
153
149
  async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Promise<ClaudeLimits | undefined> {
154
- const window = usage.window !== undefined && usage.window > 0 ? usage.window : 0
155
- const sameWindow = state.limitsWindow === window
156
- if (sameWindow && state.limits !== undefined) return state.limits
157
- if (sameWindow && state.limitsAttempts >= MAX_LIMITS_ATTEMPTS) return undefined
158
150
  const generation = state.generation
159
151
  const facts = await limitFacts($, state, usage)
160
152
  if (generation !== state.generation) return undefined
153
+ const key = JSON.stringify([state.identity?.model, facts])
154
+ const sameFacts = state.limitsKey === key
155
+ if (sameFacts && state.limits !== undefined) return state.limits
156
+ if (sameFacts && state.limitsAttempts >= MAX_LIMITS_ATTEMPTS) return undefined
161
157
  const response = await run($, { op: "limits", facts })
162
158
  if (generation !== state.generation) return undefined
163
159
  const limits = response.ok ? limitsShape(response.result) : undefined
164
- state.limitsWindow = window
165
- if (limits) {
166
- state.limits = limits
167
- state.limitsAttempts = 0
168
- return limits
169
- }
170
- state.limitsAttempts = sameWindow ? state.limitsAttempts + 1 : 1
171
- if (!state.limitsFailureLogged) {
160
+ state.limitsKey = key
161
+ state.limits = limits
162
+ state.limitsAttempts = limits ? 0 : sameFacts ? state.limitsAttempts + 1 : 1
163
+ if (!limits && !state.limitsFailureLogged) {
172
164
  state.limitsFailureLogged = true
173
165
  log($, THRESHOLDS_UNAVAILABLE)
174
166
  }
175
- return undefined
167
+ return limits
176
168
  }
177
169
  /** The measured value the points are expressed in; tokens win, percent × window stands in. */
178
170
  function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | undefined {
@@ -255,7 +247,8 @@ function forgetSession(state: ResetState) {
255
247
  state.texts = state.limits = undefined
256
248
  state.continuation = undefined
257
249
  state.continuationWindow = undefined
258
- state.limitsAttempts = state.limitsWindow = 0
250
+ state.limitsAttempts = 0
251
+ state.limitsKey = undefined
259
252
  state.settingsFailureLogged = state.limitsFailureLogged = false
260
253
  state.warnedWindow = state.warningPending = undefined
261
254
  }
@@ -307,7 +300,7 @@ async function syncHistoryWindow($: Engine, state: ResetState) {
307
300
 
308
301
  export function register(on: On) {
309
302
  const manualSignal: { wake?: () => void } = {}
310
- const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: false }
303
+ const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, settingsFailureLogged: false }
311
304
  const registered = new Set<string>()
312
305
  let keepMemory = false
313
306
  // Classic SessionStart precedes typed session.start and startup appends. Keep this binding
@@ -593,13 +586,19 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
593
586
  const texts = await loadTexts($, state)
594
587
  if (generation !== state.generation) return
595
588
  if (texts?.warning === undefined) {
589
+ clearManualRequest(state)
596
590
  log($, "Brain still full: the close-out prompt didn't load")
597
591
  return
598
592
  }
599
- await $.prompt.submit({ text: texts.warning })
593
+ const result = await $.prompt.submit({ text: texts.warning })
594
+ if (generation === state.generation && result.drop !== undefined) {
595
+ clearManualRequest(state)
596
+ log($, "Brain still full: the close-out turn didn't start")
597
+ }
600
598
  }
601
599
  } catch {
602
600
  if (generation === state.generation) {
601
+ clearManualRequest(state)
603
602
  log($, "Brain still full: the close-out turn didn't start")
604
603
  }
605
604
  } finally { armManual($, state, signal) }
@@ -81,17 +81,6 @@ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: nu
81
81
  };
82
82
  }
83
83
 
84
- /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
85
- function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
86
- const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
87
- const native = pct === undefined ? base : Math.min(pct, base);
88
- const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
89
- return {
90
- source: "percent", autoCompact, unit: "percent",
91
- native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
92
- };
93
- }
94
-
95
84
  /**
96
85
  * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
97
86
  * so a missing or malformed one degrades to the next source and finally to the percent
@@ -125,21 +114,22 @@ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
125
114
  if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
126
115
  }
127
116
 
128
- // (b) The same point computed from the reported window plus settings and environment. A real
129
- // window always answers here: falling through to the percent fallback would express the
130
- // points on an assumed 200K window, which is later than the window notesoup can see.
117
+ // (b/c) Compute once, using the classic 200K capacity only when the host reports none.
131
118
  const window = positiveNumber(usage.window);
132
- if (window !== undefined) {
133
- const configured = configuredWindow(settings, env, breakdown.model);
134
- const effective = Math.min(configured ?? window, window);
135
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
136
- const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
137
- const native = autoCompact
138
- ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold)
139
- : available;
140
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
141
- }
142
-
143
- // (c) Nothing usable but percentages.
144
- return percentLimits(autoCompact, pct, resetMargin, warningRunway);
119
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
120
+ const configured = configuredWindow(settings, env, breakdown.model);
121
+ const effective = Math.min(configured ?? capacity, capacity);
122
+ const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
123
+ const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
124
+ const native = autoCompact
125
+ ? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
126
+ : available;
127
+ const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
128
+ if (window !== undefined) return limits;
129
+ return {
130
+ ...limits, unit: "percent",
131
+ native: limits.native / capacity * 100,
132
+ reset: Math.max(MIN_POINT_PERCENT, limits.reset / capacity * 100),
133
+ warn: Math.max(MIN_POINT_PERCENT, limits.warn / capacity * 100),
134
+ };
145
135
  }