context-doctor 0.50.0 → 0.52.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.
package/dist/credits.js CHANGED
@@ -21,10 +21,11 @@
21
21
  * Dollars are each request at API list prices, as `spend` prices it.
22
22
  * Whether usage credits are billed at exactly those prices is not verified
23
23
  * here, so every figure is said to be an estimate. Read only by commands
24
- * the user runs (`limits`, `spend`, `doctor`): nothing is drawn or sent.
24
+ * the user runs (`limits`, `spend`, `doctor`, `budget`), and by the
25
+ * budget's hook at a threshold it already speaks at: nothing is drawn or sent.
25
26
  */
26
27
  import { readExtraUsage } from "./claudedir.js";
27
- import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, readClaudeReadings, readOverageReadings } from "./limits.js";
28
+ import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, modelLabel, readClaudeReadings, readOverageReadings, windowStatus } from "./limits.js";
28
29
  const MIN = 60_000;
29
30
  const HOUR = 60 * MIN;
30
31
  const DAY = 24 * HOUR;
@@ -185,7 +186,11 @@ export function nothingPast(inp) {
185
186
  */
186
187
  export function creditsReport(days = 30, opts = {}) {
187
188
  const now = opts.now ?? Date.now();
188
- const since = now - days * DAY;
189
+ return creditsSince(now - days * DAY, { ...opts, now });
190
+ }
191
+ /** The same from `since` to now (`budget`'s day or week). Undefined when nothing was past the limit. */
192
+ export function creditsSince(since, opts = {}) {
193
+ const now = opts.now ?? Date.now();
189
194
  const inp = creditsInputs(since, { ...opts, now });
190
195
  if (nothingPast(inp))
191
196
  return undefined;
@@ -194,6 +199,86 @@ export function creditsReport(days = 30, opts = {}) {
194
199
  const s = creditsOf(usage, inp);
195
200
  return s.requests ? { ...s, ...(inp.extraUsage ? { extraUsage: inp.extraUsage } : {}) } : undefined;
196
201
  }
202
+ /** The look-back the dollars an hour are read over: the same day `limits`' recent pace is. */
203
+ const AHEAD_LOOKBACK_MS = DAY;
204
+ /** Extra usage on, and nothing in `~/.claude.json` saying credits are not paying now. */
205
+ export function extraUsageOn(x) {
206
+ if (x?.enabled !== true)
207
+ return false;
208
+ return !(typeof x.disabledReason === "string" && x.disabledReason !== "fetch_error" && x.disabledReason !== "unknown");
209
+ }
210
+ /**
211
+ * The weekly window's run-out and what the hours past it would cost. Pure:
212
+ * `usage` is the last 24 hours' requests. Undefined unless extra usage is on
213
+ * and the weekly window, read recently, runs out before its reset at the
214
+ * recent pace, with dollars to price the hours at.
215
+ */
216
+ export function creditsAhead(status, extra, usage, now) {
217
+ if (!status || status.app !== "claude" || status.window !== "seven_day" || status.resetSince || status.stale)
218
+ return undefined;
219
+ if (status.runsOutAt === undefined || !status.beforeReset || status.resetsAt === undefined || !extraUsageOn(extra))
220
+ return undefined;
221
+ const from = now - AHEAD_LOOKBACK_MS;
222
+ const recent = usage.filter((p) => p.ts > from && p.ts <= now);
223
+ const total = recent.reduce((a, p) => a + p.usd, 0);
224
+ if (!(total > 0))
225
+ return undefined;
226
+ const usdPerHour = total / (AHEAD_LOOKBACK_MS / HOUR);
227
+ const hours = Math.max(0, status.resetsAt - Math.max(status.runsOutAt, now)) / HOUR;
228
+ if (!(hours > 0))
229
+ return undefined;
230
+ const byModel = new Map();
231
+ for (const p of recent)
232
+ if (p.model)
233
+ byModel.set(p.model, (byModel.get(p.model) ?? 0) + p.usd);
234
+ const [top] = [...byModel].sort((a, b) => b[1] - a[1]);
235
+ const out = { runsOutAt: status.runsOutAt, resetsAt: status.resetsAt, hours, usdPerHour, usd: hours * usdPerHour };
236
+ if (top && top[1] / total >= 0.5) {
237
+ out.model = top[0];
238
+ out.modelShare = top[1] / total;
239
+ }
240
+ if (status.averagePerHour !== undefined && status.averagePerHour > 0) {
241
+ out.averagePerHour = status.averagePerHour;
242
+ out.averageLasts = status.at + ((100 - status.pct) / status.averagePerHour) * HOUR >= status.resetsAt;
243
+ }
244
+ return out;
245
+ }
246
+ /**
247
+ * creditsAhead from this machine: `~/.claude.json` first, then the ledger's
248
+ * weekly window, and the transcripts of the last day only when both say it
249
+ * applies. Never throws: a command's own figures must not be lost to it.
250
+ */
251
+ export function creditsAheadNow(opts = {}) {
252
+ try {
253
+ const now = opts.now ?? Date.now();
254
+ const extra = opts.extraUsage === null ? undefined : opts.extraUsage ?? readExtraUsage(opts.home);
255
+ if (!extraUsageOn(extra))
256
+ return undefined;
257
+ const status = opts.status ?? windowStatus(cleanReadings(readClaudeReadings(now - 8 * DAY, opts.logPath ?? limitsLogPath()).filter((r) => r.window === "seven_day")), now);
258
+ if (!status?.beforeReset || status.runsOutAt === undefined || status.stale)
259
+ return undefined;
260
+ return creditsAhead(status, extra, claudeUsage(now - AHEAD_LOOKBACK_MS, now, opts.claudePaths), now);
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ /**
267
+ * One line: "Extra usage is on: at this pace your weekly limit runs out on
268
+ * Thu, Nov 26 at 18:19, 46 hours before it resets, and Claude Code would
269
+ * keep working on usage credits until then: about $1,234 at API list prices
270
+ * (an estimate), at your last 24 hours' $26.80 an hour, mostly Fable 5.2.
271
+ * At this week's average pace (0.55% an hour) it lasts until the reset."
272
+ */
273
+ export function creditsAheadLine(a, now) {
274
+ const hours = a.hours >= 10 ? Math.round(a.hours) : Math.round(a.hours * 10) / 10;
275
+ const mostly = a.model ? `, mostly ${modelLabel(a.model)}` : "";
276
+ const avg = a.averagePerHour === undefined ? ""
277
+ : a.averageLasts ? ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it lasts until the reset.`
278
+ : ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it runs out before the reset too.`;
279
+ return `Extra usage is on: at this pace your weekly limit runs out ${whenText(a.runsOutAt, now)}, ${hours} hour${hours === 1 ? "" : "s"} before it resets, and Claude Code would keep working on usage credits until then: about ${dollars(a.usd)} ${AT_LIST_PRICES}, at your last 24 hours' ${dollars(a.usdPerHour)} an hour${mostly}.${avg}`;
280
+ }
281
+ const pace = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
197
282
  // ---------------------------------------------------------------------------
198
283
  // Words
199
284
  // ---------------------------------------------------------------------------
package/dist/doctor.d.ts CHANGED
@@ -40,6 +40,24 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
40
40
  */
41
41
  export declare function claudeCodeCostCheck(days?: number, now?: number): Check | undefined;
42
42
  export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
43
+ /**
44
+ * The Desktop app's answer to its own auto-compact offer (appwindow.ts),
45
+ * only when one is on file: what it offered and what you chose. A fact, not
46
+ * a fault.
47
+ */
48
+ export declare function appWindowCheck(home?: string): Check | undefined;
49
+ /**
50
+ * Extra usage (usage credits past a plan's limit), as Claude Code cached it
51
+ * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
52
+ * not a fault: "ok" either way. Undefined when the file says nothing.
53
+ */
54
+ export declare function extraUsageCheck(home?: string): Check | undefined;
55
+ /**
56
+ * The MCP servers the newest Desktop session handed context-doctor's mod
57
+ * (apptools.ts), their type and placement, and what desktop-tools-defer
58
+ * would do with them. A fact, not a fault: only when one is on file.
59
+ */
60
+ export declare function appToolsCheck(path?: string, now?: number): Check | undefined;
43
61
  /**
44
62
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
45
63
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
@@ -51,12 +69,6 @@ export declare function unpricedModelsCheck(days?: number, now?: number, home?:
51
69
  * does not (Desktop) and has no transcript to measure either way: say that,
52
70
  * rather than nothing or a false "ok".
53
71
  */
54
- /**
55
- * Extra usage (usage credits past a plan's limit), as Claude Code cached it
56
- * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
57
- * not a fault: "ok" either way. Undefined when the file says nothing.
58
- */
59
- export declare function extraUsageCheck(home?: string): Check | undefined;
60
72
  export declare function devinCheck(home?: string): Check;
61
73
  /**
62
74
  * How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
package/dist/doctor.js CHANGED
@@ -12,7 +12,7 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "
12
12
  import { homedir, platform } from "node:os";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
- import { ledgerPath, readLedger } from "./ledger.js";
15
+ import { ledgerPath, readLedger, statePath } from "./ledger.js";
16
16
  import { costCheck } from "./modmeasure.js";
17
17
  import { ago, MOD_SINCE, modActivity, modReadiness, PLUGIN_KEY, pluginStage, readPluginMarker } from "./claudeplugin.js";
18
18
  import { loadConfig } from "./config.js";
@@ -29,6 +29,7 @@ import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "
29
29
  import { describeCosts, subagentCostsPath } from "./fanout.js";
30
30
  import { claudeCodePresent, claudeDir, claudeJsonPath, readExtraUsage } from "./claudedir.js";
31
31
  import { extraUsageText } from "./credits.js";
32
+ import { appAnswerText, readAppWindows } from "./appwindow.js";
32
33
  import { codexDir } from "./codexdir.js";
33
34
  import { periodSpend, readBudget } from "./budget.js";
34
35
  import { sessionPriceThresholds } from "./sessionprice.js";
@@ -37,6 +38,8 @@ import { claudeUsageFiles } from "./limits.js";
37
38
  import { compareSessions, comparisonCheck } from "./ccost.js";
38
39
  import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
39
40
  import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
41
+ import { uncachedCheck } from "./cachemisses.js";
42
+ import { appToolsCheckText, recentToolLines } from "./apptools.js";
40
43
  function claudeDesktopConfigPath() {
41
44
  switch (platform()) {
42
45
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -273,7 +276,8 @@ function claudeRouteChecks(layers, plugin, now = Date.now()) {
273
276
  mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
274
277
  }
275
278
  else if (act.cost && now - act.cost < MOD_FRESH_MS) {
276
- mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (~/.claude/.context-doctor-session-cost.jsonl)${limits}` };
279
+ // Where the mod writes it (modmeasure.ts costLogPath): beside our state, ~/.claude only by default.
280
+ mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (${tilde(join(dirname(statePath()), ".context-doctor-session-cost.jsonl"))})${limits}` };
277
281
  }
278
282
  else if (act.cost) {
279
283
  mod = { label: "Mod", status: "warn", detail: `last measured ${ago(act.cost, now)}: no session that loaded the plugin since, or the mod stopped${limits}` };
@@ -413,16 +417,20 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
413
417
  };
414
418
  }
415
419
  /**
416
- * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
417
- * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
418
- * ~/.claude/settings.json in Claude Code's format while its
419
- * `read_config_from.claude` is on (the default), with session_id and
420
- * prompt_id but no transcript_path in the input; the desktop app's Cascade
421
- * hooks (~/.codeium/windsurf/hooks.json) pass a transcript only to
422
- * post_cascade_response_with_transcript. So in Devin our hook runs (CLI) or
423
- * does not (Desktop) and has no transcript to measure either way: say that,
424
- * rather than nothing or a false "ok".
420
+ * The Desktop app's answer to its own auto-compact offer (appwindow.ts),
421
+ * only when one is on file: what it offered and what you chose. A fact, not
422
+ * a fault.
425
423
  */
424
+ export function appWindowCheck(home) {
425
+ let text;
426
+ try {
427
+ text = appAnswerText(readAppWindows({ home }));
428
+ }
429
+ catch {
430
+ return undefined;
431
+ }
432
+ return text ? { label: "Desktop compact offer", status: "ok", detail: text } : undefined;
433
+ }
426
434
  /**
427
435
  * Extra usage (usage credits past a plan's limit), as Claude Code cached it
428
436
  * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
@@ -432,6 +440,26 @@ export function extraUsageCheck(home) {
432
440
  const t = extraUsageText(readExtraUsage(home));
433
441
  return t ? { label: "Extra usage", status: "ok", detail: t.text } : undefined;
434
442
  }
443
+ /**
444
+ * The MCP servers the newest Desktop session handed context-doctor's mod
445
+ * (apptools.ts), their type and placement, and what desktop-tools-defer
446
+ * would do with them. A fact, not a fault: only when one is on file.
447
+ */
448
+ export function appToolsCheck(path, now = Date.now()) {
449
+ const text = appToolsCheckText(recentToolLines(30, now, path));
450
+ return text ? { label: "Desktop app tools", status: "ok", detail: text } : undefined;
451
+ }
452
+ /**
453
+ * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
454
+ * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
455
+ * ~/.claude/settings.json in Claude Code's format while its
456
+ * `read_config_from.claude` is on (the default), with session_id and
457
+ * prompt_id but no transcript_path in the input; the desktop app's Cascade
458
+ * hooks (~/.codeium/windsurf/hooks.json) pass a transcript only to
459
+ * post_cascade_response_with_transcript. So in Devin our hook runs (CLI) or
460
+ * does not (Desktop) and has no transcript to measure either way: say that,
461
+ * rather than nothing or a false "ok".
462
+ */
435
463
  export function devinCheck(home = homedir()) {
436
464
  const label = "Devin";
437
465
  const app = [join("/Applications", "Devin.app"), join(home, "Applications", "Devin.app"), join(home, "Library", "Application Support", "Devin"), join(home, ".devin")].find((p) => existsSync(p));
@@ -685,6 +713,14 @@ export async function runDoctor() {
685
713
  const xu = extraUsageCheck();
686
714
  if (xu)
687
715
  checks.push(xu);
716
+ // What the Desktop app offered for auto-compact and what you answered, only when an answer is on file.
717
+ const aw = appWindowCheck();
718
+ if (aw)
719
+ checks.push(aw);
720
+ // Which servers the Desktop app hands context-doctor's mod, and whether desktop-tools-defer reaches them.
721
+ const at = appToolsCheck();
722
+ if (at)
723
+ checks.push(at);
688
724
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
689
725
  const codexHome = codexDir();
690
726
  if (existsSync(codexHome)) {
@@ -927,6 +963,15 @@ export async function runDoctor() {
927
963
  else if (hooked)
928
964
  checks.push({ label: "Session price", status: "ok", detail: `said once when a session passes ${at.map((t) => `$${t.toLocaleString("en-US")}`).join(", ").replace(/, ([^,]+)$/, " and $1")} (CONTEXT_DOCTOR_SESSION_PRICE to change; CONTEXT_DOCTOR_NO_SESSION_PRICE=1 for off)` });
929
965
  }
966
+ // Requests the prompt cache never saw (anthropics/claude-code#111948), named by Claude Code version.
967
+ try {
968
+ const c = uncachedCheck();
969
+ if (c)
970
+ checks.push(c);
971
+ }
972
+ catch {
973
+ /* an unreadable transcript is no finding */
974
+ }
930
975
  // Models in the last 30 days with no list price of their own: their dollars everywhere are a guess or missing.
931
976
  {
932
977
  const c = unpricedModelsCheck();
@@ -1047,12 +1092,35 @@ export async function runDoctor() {
1047
1092
  const warns = checks.filter((c) => c.status === "warn");
1048
1093
  if (fails.length > 0)
1049
1094
  process.exitCode = 1;
1095
+ // "All good" must mean something is actually protected. A clean bill on an
1096
+ // empty machine is not that: say what is missing instead of reassuring.
1097
+ // Presence is what each section above already decides: the app's config or
1098
+ // home folder, its binary. (The app rows cannot be re-read for this — the
1099
+ // Claude Code row watches ~/.claude.json while the app lives in ~/.claude.)
1100
+ const home = homedir();
1101
+ const appsDetected = existsSync(claudeDesktopConfigPath()) ||
1102
+ claudeCodePresent() ||
1103
+ existsSync(join(claudeDir(), "settings.json")) ||
1104
+ existsSync(join(home, ".cursor")) ||
1105
+ existsSync(codexDir()) ||
1106
+ geminiCliPresent() ||
1107
+ antigravityPresent() ||
1108
+ copilotPresent() ||
1109
+ devinCheck(home).status !== "skip";
1110
+ // An ok that means a workflow is protected, not internal plumbing (the
1111
+ // ledger, the MCP handshake with itself, optional config files existing).
1112
+ const INTERNAL_OK = new Set(["Ledger", "MCP server handshake", "Project config", "Spend budget", "Desktop chat tool use", "Extra usage", "Desktop app tools", "Desktop compact offer", "Autopilot port"]);
1113
+ const protecting = checks.filter((c) => c.status === "ok" && !INTERNAL_OK.has(c.label));
1050
1114
  console.log("");
1051
1115
  console.log(fails.length > 0
1052
1116
  ? `${fails.length} issue(s) found — fixes suggested above.`
1053
- : warns.length > 0
1054
- ? `No problems; ${warns.length} note(s) marked ! above.`
1055
- : "All good.");
1117
+ : protecting.length === 0
1118
+ ? !appsDetected
1119
+ ? withInvocation("Installed and healthy, but no supported AI app was found on this machine: nothing is being measured or protected yet. On a machine with Claude Code, Cursor, Codex or Gemini CLI, `context-doctor install` wires it (`context-doctor uninstall` removes it).")
1120
+ : withInvocation("Installed and healthy, but nothing is wired up yet: context-doctor is not actively protecting any workflow. `context-doctor install` wires the apps on this machine (`context-doctor uninstall` removes it).")
1121
+ : warns.length > 0
1122
+ ? `No problems; ${warns.length} note(s) marked ! above.`
1123
+ : "All good.");
1056
1124
  }
1057
1125
  /** "3.18.25" >= major.minor. */
1058
1126
  function versionAtLeast(v, major, minor) {
@@ -171,11 +171,20 @@ function getOnce(url, env, deadline, maxBytes) {
171
171
  };
172
172
  const timeout = Math.max(1, deadline - monotonicNow());
173
173
  // The socket timeout is an idle timeout; a server dripping a byte at a
174
- // time would never trip it. This one bounds the whole download.
175
- const overall = setTimeout(() => {
174
+ // time would never trip it. This one bounds the whole download. A timer
175
+ // can fire before the monotonic clock reaches the deadline (a busy loop):
176
+ // it waits out the rest, so a download gives up only at the deadline and
177
+ // the call's next file finds the budget spent (CI read one in those ms).
178
+ const expire = () => {
179
+ const left = deadline - monotonicNow();
180
+ if (left > 0) {
181
+ overall = setTimeout(expire, Math.ceil(left));
182
+ return;
183
+ }
176
184
  req.destroy();
177
185
  done({ status: 0, error: "timed out" });
178
- }, timeout);
186
+ };
187
+ let overall = setTimeout(expire, timeout);
179
188
  const req = request(url, { method: "GET", lookup: guardedLookup(allowLoopback), timeout, headers: { accept: "*/*", "user-agent": "context-doctor" } }, (res) => {
180
189
  const status = res.statusCode ?? 0;
181
190
  if (status >= 300 && status < 400) {
@@ -211,6 +220,9 @@ function getOnce(url, env, deadline, maxBytes) {
211
220
  res.on("error", (e) => done({ status, error: e.message }));
212
221
  });
213
222
  req.on("timeout", () => {
223
+ // Idle as long as the whole budget, fired early: the overall timer ends it at the deadline.
224
+ if (deadline - monotonicNow() > 0)
225
+ return;
214
226
  req.destroy();
215
227
  done({ status: 0, error: "timed out" });
216
228
  });
package/dist/fix.d.ts CHANGED
@@ -42,11 +42,12 @@ import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
42
42
  import { type ClaudeCodeInstall } from "./modelswitch.js";
43
43
  import { type ProjectPlan } from "./prune.js";
44
44
  import { type DeferEntry } from "./mcpdefer.js";
45
+ import { type ToolsLine } from "./apptools.js";
45
46
  import { readLedger } from "./ledger.js";
46
47
  import { type AbStoredResult } from "./abstore.js";
47
48
  import { type SubagentModelReplay } from "./subagentmodel.js";
48
49
  import { type ToolOutputReplay } from "./tooloutput.js";
49
- import { type ProgressSummaryEstimate } from "./progresssummaries.js";
50
+ import { type ProgressSummaryEstimate, type SummaryRoute } from "./progresssummaries.js";
50
51
  import { type CodexCompactReport } from "./codexcompact.js";
51
52
  export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries" | "mcp-defer" | "desktop-tools-defer";
52
53
  export interface Fix {
@@ -208,6 +209,12 @@ export interface FixInputs {
208
209
  value: string;
209
210
  where: string;
210
211
  };
212
+ /**
213
+ * The MCP servers context-doctor's mod saw Claude Code hand over, one line
214
+ * per session (apptools.ts): whether the lever reaches the app's servers
215
+ * here, and after applying, the sessions it moved them in.
216
+ */
217
+ appToolsSeen?: ToolsLine[];
211
218
  }
212
219
  /** The Claude Code version whose `tool.describe` names a tool's MCP server and lets a mod answer `isDeferred`. */
213
220
  export declare const DESKTOP_TOOLS_DEFER_SINCE = "2.1.326";
@@ -306,9 +313,10 @@ export declare function progressSummariesState(deps?: {
306
313
  };
307
314
  offSince?: number;
308
315
  forkGateOff: boolean;
316
+ route: SummaryRoute;
309
317
  };
310
318
  /** The summaries fix's variable stopped since `at`: the background subagents on Claude Code 2.1.318+ since, estimated as if it were not set. */
311
- export declare function progressSummariesSavedSince(at: number, subagentPaths?: string[], forkGateOff?: boolean): ProgressSummaryEstimate;
319
+ export declare function progressSummariesSavedSince(at: number, subagentPaths?: string[], forkGateOff?: boolean, route?: SummaryRoute): ProgressSummaryEstimate;
312
320
  export interface SinceResult {
313
321
  id: FixId;
314
322
  at: number;
@@ -331,6 +339,7 @@ export declare function savedSince(records: FixRecord[], opts?: {
331
339
  subagentPaths?: string[];
332
340
  codexPaths?: string[];
333
341
  ledger?: ReturnType<typeof readLedger>;
342
+ progressRoute?: SummaryRoute;
334
343
  }): SinceResult[];
335
344
  /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
336
345
  export declare function overlaps(fixes: Fix[]): string[];
package/dist/fix.js CHANGED
@@ -53,12 +53,13 @@ import { claudeJsonPath, tilde } from "./claudedir.js";
53
53
  import { applyPrune, undoPrune } from "./prune.js";
54
54
  import { applyMcpDefer, MCP_DEFER_SINCE, undoMcpDefer } from "./mcpdefer.js";
55
55
  import { DEFER_APP_TOOLS_ENV, deferredServers, KEEP_APP_SERVERS } from "./mod/logic.js";
56
+ import { appToolsVerdict, movedSessions, verdictLines } from "./apptools.js";
56
57
  import { fallbackStateDir, readLedger } from "./ledger.js";
57
58
  import { claudeDir } from "./claudedir.js";
58
59
  import { comparisonLine } from "./abstore.js";
59
60
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
60
61
  import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
61
- import { disablesSummaries, estimateProgressSummaries, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE, SMALL_FAST_MODEL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
62
+ import { disablesSummaries, estimateProgressSummaries, formWords, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE, SMALL_FAST_MODEL_NAME, SMALL_NOTES_SINCE, summaryRoute } from "./progresssummaries.js";
62
63
  import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
63
64
  /** The Claude Code version whose `tool.describe` names a tool's MCP server and lets a mod answer `isDeferred`. */
64
65
  export const DESKTOP_TOOLS_DEFER_SINCE = "2.1.326";
@@ -257,18 +258,20 @@ export function planFixes(i) {
257
258
  const psSet = i.progressSummariesSet;
258
259
  if (psSet) {
259
260
  const off = disablesSummaries(psSet.value);
260
- const less = !off && ps && ps.notesUsd >= MIN_USD ? ` (turning them off would have saved about ${money(ps.notesUsd)})` : "";
261
+ const worth = ps ? psValue(ps) : 0;
262
+ const less = !off && ps && worth >= MIN_USD ? ` (turning them off would have saved about ${money(worth)})` : "";
261
263
  fixes.push({ id: "progress-summaries", title: "Subagent progress summaries", basis: "set", quality: "", change: `env.${PROGRESS_SUMMARIES_ENV}`, state: off ? "applied" : "not-here", note: `${PROGRESS_SUMMARIES_ENV}=${psSet.value} in ${psSet.where}${off ? "" : `: left as you set it${less}`}`, value: psSet.value });
262
264
  }
263
- else if (ps && ps.summarized > 0 && ps.notesUsd >= MIN_USD) {
265
+ else if (ps && ps.summarized > 0 && psValue(ps) >= MIN_USD) {
264
266
  const billed = i.subagentModel?.billedUsd ?? 0;
267
+ const value = psValue(ps);
265
268
  fixes.push({
266
269
  id: "progress-summaries",
267
270
  title: "Subagent progress summaries off",
268
- savedUsd: ps.notesUsd,
269
- savedShare: billed > 0 ? ps.notesUsd / billed : undefined,
271
+ savedUsd: value,
272
+ savedShare: billed > 0 ? value / billed : undefined,
270
273
  shareOf: "of subagents",
271
- basis: `${ps.calls.toLocaleString("en-US")} summaries for ${ps.summarized} background subagent${ps.summarized === 1 ? "" : "s"}, one each 30 s while one ran and its transcript changed; no transcript records them, so an estimate: ${ps.smallCalls === ps.calls ? `~1,850 tokens of notes each, written by ${SMALL_FAST_MODEL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+)` : `~1,850 tokens of notes each (what Anthropic serves since November 2026)${ps.smallCalls ? `, by ${SMALL_FAST_MODEL_NAME} for the ${ps.smallCalls.toLocaleString("en-US")} on Claude Code ${SMALL_NOTES_SINCE}+` : ""}, ${money(ps.forkUsd)} if each sent the whole context, as before`}`,
274
+ basis: `${ps.calls.toLocaleString("en-US")} summaries for ${ps.summarized} background subagent${ps.summarized === 1 ? "" : "s"}, one each 30 s while one ran and its transcript changed; no transcript records them, so an estimate: ${psBasis(ps)}`,
272
275
  quality: "none to the work: a summary never enters the subagent's context; you lose the 3-5 word progress line on a running subagent's task row",
273
276
  qualityFree: true,
274
277
  change: `${where}: env.${PROGRESS_SUMMARIES_ENV} = "${PROGRESS_SUMMARIES_OFF}" (Claude Code ${PROGRESS_SUMMARIES_SINCE}+)`,
@@ -297,14 +300,24 @@ export function planFixes(i) {
297
300
  const dt = i.desktopTools;
298
301
  if (i.desktopToolsSet) {
299
302
  const named = deferredServers(i.desktopToolsSet.value);
300
- fixes.push({ id: "desktop-tools-defer", title: "The Desktop app's own tools behind tool search", basis: "set", quality: "", change: `env.${DEFER_APP_TOOLS_ENV}`, state: named.length ? "applied" : "not-here", note: named.length ? `context-doctor's mod keeps ${named.join(", ")} behind tool search (${i.desktopToolsSet.where})` : `${i.desktopToolsSet.where} names no server: left as you set it`, value: i.desktopToolsSet.value });
303
+ // What the mod recorded since: the sessions it moved them in, or that none has yet.
304
+ const moved = movedSessions(i.appToolsSeen ?? []);
305
+ const seen = moved.sessions ? `; moved behind tool search in ${moved.sessions} session${moved.sessions === 1 ? "" : "s"} since ${new Date(moved.since).toISOString().slice(0, 10)}` : named.length && i.appToolsSeen?.length ? "; no session moved them yet (it takes a new Desktop session)" : "";
306
+ fixes.push({ id: "desktop-tools-defer", title: "The Desktop app's own tools behind tool search", basis: "set", quality: "", change: `env.${DEFER_APP_TOOLS_ENV}`, state: named.length ? "applied" : "not-here", note: named.length ? `context-doctor's mod keeps ${named.join(", ")} behind tool search (${i.desktopToolsSet.where})${seen}` : `${i.desktopToolsSet.where} names no server: left as you set it`, value: i.desktopToolsSet.value });
301
307
  }
302
308
  else if (dt) {
303
309
  // A server called in at least half the starts it went into would cost a tool-search step in most of them: kept in front.
304
- const pick = dt.servers.filter((s) => !KEEP_APP_SERVERS.includes(s.name) && s.calledStarts * 2 < s.starts && s.unusedUsd > 0).sort((a, b) => b.unusedUsd - a.unusedUsd);
310
+ const candidates = dt.servers.filter((s) => !KEEP_APP_SERVERS.includes(s.name) && s.calledStarts * 2 < s.starts && s.unusedUsd > 0).sort((a, b) => b.unusedUsd - a.unusedUsd);
311
+ // What the mod saw in the newest Desktop session: only the servers that arrive whole, with their server named, are offered.
312
+ const verdict = i.appToolsSeen ? appToolsVerdict(i.appToolsSeen, candidates.map((s) => s.name)) : undefined;
313
+ const pick = verdict ? candidates.filter((s) => verdict.reach.some((r) => r.server === s.name)) : candidates;
305
314
  const kept = dt.servers.filter((s) => !pick.includes(s)).map((s) => s.name);
306
315
  const usd = pick.reduce((t, s) => t + s.unusedUsd, 0);
307
- if (pick.length && usd >= MIN_USD) {
316
+ if (verdict && candidates.length && !pick.length) {
317
+ // Withdrawn before anyone applies it, with the reason the mod saw.
318
+ fixes.push({ id: "desktop-tools-defer", title: "The Desktop app's own tools behind tool search", basis: "", quality: "", change: "", state: "not-here", note: `not offered: ${verdictLines(verdict).join(" ")}` });
319
+ }
320
+ else if (pick.length && usd >= MIN_USD) {
308
321
  // Counted as the headline is, start by start: overhead's per-server share is spread by tokens and can come out below it.
309
322
  const exact = pick.every((s) => s.calledUsd !== undefined);
310
323
  const all = pick.reduce((t, s) => t + (exact ? s.unusedUsd + s.calledUsd : s.usd), 0);
@@ -318,8 +331,10 @@ export function planFixes(i) {
318
331
  change: `${where}: env.${DEFER_APP_TOOLS_ENV} = "${value}", read by context-doctor's mod (its plugin, Claude Code ${DESKTOP_TOOLS_DEFER_SINCE}+)`,
319
332
  state: "available",
320
333
  value,
321
- // Built from Claude Code's mods declarations; whether the app's in-process servers raise tool.describe is not yet seen on a live session.
322
- detail: ["Not yet confirmed on a live Desktop session: after applying, start a new session and run context-doctor overhead; these servers should no longer be listed as sent whole."],
334
+ // Confirmed (or narrowed) by what the mod saw in the newest Desktop session; with none on record, said so.
335
+ detail: verdict
336
+ ? verdictLines(verdict)
337
+ : [`Not yet confirmed on this machine: context-doctor's mod notes which servers the Desktop app hands it after the first reply of a new Desktop session (Claude Code ${DESKTOP_TOOLS_DEFER_SINCE}+, with the plugin); run fix again after one.`],
323
338
  });
324
339
  }
325
340
  }
@@ -457,6 +472,24 @@ export function fixOverrides(id, deps = {}) {
457
472
  }
458
473
  return [];
459
474
  }
475
+ /** What turning the summaries off saves: the notes before 2.1.328, the form's figure from it, a range's high end. */
476
+ function psValue(ps) {
477
+ return ps.routes?.length && ps.valueUsd !== undefined ? ps.valueUsd : ps.notesUsd;
478
+ }
479
+ /** How the summaries were priced, in words: each 2.1.328+ form with its count and why, then the older ones. */
480
+ function psBasis(ps) {
481
+ if (!ps.routes?.length)
482
+ return ps.smallCalls === ps.calls ? `~1,850 tokens of notes each, written by ${SMALL_FAST_MODEL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+)` : `~1,850 tokens of notes each (what Anthropic serves since November 2026)${ps.smallCalls ? `, by ${SMALL_FAST_MODEL_NAME} for the ${ps.smallCalls.toLocaleString("en-US")} on Claude Code ${SMALL_NOTES_SINCE}+` : ""}, ${money(ps.forkUsd)} if each sent the whole context, as before`;
483
+ const parts = [];
484
+ if (ps.smallCalls)
485
+ parts.push(`${ps.smallCalls.toLocaleString("en-US")} as ${formWords("haiku")}`);
486
+ for (const g of ps.routes)
487
+ parts.push(`${g.calls.toLocaleString("en-US")} as ${formWords(g.form)}, ${g.form === "range" ? `counted at the high end (${money(g.lowUsd)} at the low end: context-doctor cannot tell which)` : money(g.highUsd)}, because ${g.why}`);
488
+ const old = ps.calls - ps.smallCalls - ps.routes.reduce((n, g) => n + g.calls, 0);
489
+ if (old > 0)
490
+ parts.push(`${old.toLocaleString("en-US")} before Claude Code ${SMALL_NOTES_SINCE} as ~1,850 tokens of notes each, more if they sent the whole context`);
491
+ return parts.join("; ");
492
+ }
460
493
  /** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
461
494
  function applySetting(fix, home, at, extra) {
462
495
  const key = KEY_PATH[fix.id];
@@ -783,24 +816,26 @@ export function progressSummariesState(deps = {}) {
783
816
  const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
784
817
  const fork = effectiveEnv("CLAUDE_CODE_FORK_SUBAGENT", sources, env);
785
818
  const forkGateOff = !!fork && ["0", "false", "no", "off"].includes(fork.value.trim().toLowerCase());
819
+ // How 2.1.328+ wrote them where the transcript does not say: the provider, model overrides and API address set now.
820
+ const route = summaryRoute({ home: deps.home, env, sources });
786
821
  const rec = readFixRecords(deps.home).find((r) => r.id === "progress-summaries");
787
- const off = (value, where) => ({ set: { value, where }, ...(disablesSummaries(value) && rec ? { offSince: rec.at } : {}), forkGateOff });
822
+ const off = (value, where) => ({ set: { value, where }, ...(disablesSummaries(value) && rec ? { offSince: rec.at } : {}), forkGateOff, route });
788
823
  for (const s of sources) {
789
824
  const v = s.settings.env?.[PROGRESS_SUMMARIES_ENV];
790
825
  if (v === undefined || v === null || String(v).trim() === "")
791
826
  continue;
792
827
  if (disablesSummaries(v) || s.name === "user")
793
828
  return off(String(v), `${tilde(s.path)} env`);
794
- return { forkGateOff };
829
+ return { forkGateOff, route };
795
830
  }
796
831
  // The shell's value, unless it is fix's own copied into a session started before an undo.
797
832
  if (shellSet(PROGRESS_SUMMARIES_ENV, sources, env, PROGRESS_SUMMARIES_OFF))
798
833
  return off(env[PROGRESS_SUMMARIES_ENV], underClaudeCode(env) ? "this Claude Code session's environment" : "the environment");
799
- return { forkGateOff };
834
+ return { forkGateOff, route };
800
835
  }
801
836
  /** The summaries fix's variable stopped since `at`: the background subagents on Claude Code 2.1.318+ since, estimated as if it were not set. */
802
- export function progressSummariesSavedSince(at, subagentPaths, forkGateOff = false) {
803
- return estimateProgressSummaries(subagentPaths ?? subagentTranscripts(at), { since: at, minVersion: PROGRESS_SUMMARIES_SINCE, forkGateOff });
837
+ export function progressSummariesSavedSince(at, subagentPaths, forkGateOff = false, route) {
838
+ return estimateProgressSummaries(subagentPaths ?? subagentTranscripts(at), { since: at, minVersion: PROGRESS_SUMMARIES_SINCE, forkGateOff, route });
804
839
  }
805
840
  /**
806
841
  * Compactions since `since` that came before the old window, priced: every
@@ -907,8 +942,8 @@ export function savedSince(records, opts = {}) {
907
942
  out.push({ id: r.id, at: r.at, savedUsd: s.moved ? s.savedUsd : undefined, detail: s.moved ? `estimated: ${s.moved.toLocaleString("en-US")} Bash results moved to a file that were inline before, priced at the requests that would have re-read them; files the model opened again not counted` : "no Bash output over the cap since" });
908
943
  }
909
944
  else if (r.id === "progress-summaries") {
910
- const s = progressSummariesSavedSince(r.at, opts.subagentPaths);
911
- out.push({ id: r.id, at: r.at, savedUsd: s.summarized ? s.notesUsd : undefined, detail: s.summarized ? `estimated: ${s.calls.toLocaleString("en-US")} summaries it stopped for ${s.summarized} background subagent${s.summarized === 1 ? "" : "s"} on Claude Code ${PROGRESS_SUMMARIES_SINCE}+, as notes${s.smallCalls === s.calls ? ` by ${SMALL_FAST_MODEL_NAME} (${SMALL_NOTES_SINCE}+)` : ` (${money(s.forkUsd)} at the whole context)`}` : "no background subagent in a terminal session since" });
945
+ const s = progressSummariesSavedSince(r.at, opts.subagentPaths, false, opts.progressRoute);
946
+ out.push({ id: r.id, at: r.at, savedUsd: s.summarized ? psValue(s) : undefined, detail: s.summarized ? `estimated: ${s.calls.toLocaleString("en-US")} summaries it stopped for ${s.summarized} background subagent${s.summarized === 1 ? "" : "s"} on Claude Code ${PROGRESS_SUMMARIES_SINCE}+, ${s.routes?.length ? psBasis(s) : `as notes${s.smallCalls === s.calls ? ` by ${SMALL_FAST_MODEL_NAME} (${SMALL_NOTES_SINCE}+)` : ` (${money(s.forkUsd)} at the whole context)`}`}` : "no background subagent in a terminal session since" });
912
947
  }
913
948
  else if (r.id === "autopilot") {
914
949
  const ledger = opts.ledger ?? readLedger();
package/dist/limits.d.ts CHANGED
@@ -455,6 +455,41 @@ export interface SlopeChange {
455
455
  sigma: number;
456
456
  versionsBefore: string[];
457
457
  versionsAfter: string[];
458
+ /** The model mix on each side, when the transcripts carry models (mixOf). */
459
+ mix?: MixShift;
460
+ /**
461
+ * What the mix alone predicts: the after side's dollars per 1% over the
462
+ * before side's, at fixed per-model rates. Undefined when the mix moved
463
+ * and no per-model rates were good enough to say.
464
+ */
465
+ mixFactor?: number;
466
+ /** factor / mixFactor: the part of the move the mix does not explain (under 1: per model, 1% buys less). */
467
+ residual?: number;
468
+ /** How many standard errors the residual is (log scale, the two sides' errors). */
469
+ residualSigma?: number;
470
+ /**
471
+ * In words: "limit", the move is the limit's own (the mix held, or what is
472
+ * left past it is 1.5x or more beyond its error); "mix", the mix explains
473
+ * it; "both", a mix move and a residual move; "unclear", the mix moved and
474
+ * per-model rates are too thin to split the two.
475
+ */
476
+ cause?: "limit" | "mix" | "both" | "unclear";
477
+ }
478
+ /** Dollar shares by model on each side of a move, and the model whose share moved most. */
479
+ export interface MixShift {
480
+ /** reportModel keys, 0-1 of each side's dollars. */
481
+ before: Record<string, number>;
482
+ after: Record<string, number>;
483
+ /** The model whose share grew most, and the one whose share shrank most. */
484
+ grew: string;
485
+ shrank?: string;
486
+ /** Half the summed share changes, 0-1: 0 when the mix held. */
487
+ moved: number;
488
+ /** % of the limit per list-price dollar by model, as used for the prediction. */
489
+ pctPerUsd?: Record<string, number>;
490
+ /** The mix alone, at those rates: dollars per 1% on each side. */
491
+ predictedBefore?: number;
492
+ predictedAfter?: number;
458
493
  }
459
494
  /**
460
495
  * Each reset window of one weekly window's readings: % used, dollars and
@@ -476,7 +511,9 @@ export declare function reportModel(model: string | undefined): string;
476
511
  * figure (dated at the reset), and inside a window at the one split of its
477
512
  * stretches that separates two rates best (dated at that stretch). Reported
478
513
  * from a 1.5x move either way, beyond 3 standard errors between windows and
479
- * 4 inside one (the split is searched for).
514
+ * 4 inside one (the split is searched for). Each move is checked against
515
+ * the model mix on its two sides (explainMove; needs `readings` to find the
516
+ * stretches): `cause` says whether the limit moved or the mix did.
480
517
  */
481
518
  export declare function slopeChanges(windows: ResetWindow[], usage?: UsagePoint[], readings?: LimitReading[], stretchMs?: number): SlopeChange[];
482
519
  export interface LimitsReport {
@@ -549,12 +586,16 @@ export declare function limitSavingsLines(fit: LimitFit | undefined, items: Arra
549
586
  * Code), or the autopilot proxy (from the API's rate-limit headers).
550
587
  */
551
588
  export declare const HOW_TO_RECORD = "To record them: `context-doctor install` (the plugin's mod writes them after each turn, Claude Code 2.1.286+; `install --statusline` on older ones), or `context-doctor autopilot on` (its proxy reads them from the API's replies).";
589
+ /** "claude-fable-5-2" as "Fable 5.2"; any other id as it is. */
590
+ export declare function modelLabel(key: string | undefined): string;
552
591
  /**
553
592
  * The full `limits` report. `pastLimit`: lines on requests paid from usage
554
593
  * credits past a limit (credits.ts creditsLines), placed under the windows;
555
- * none when nothing went past one.
594
+ * none when nothing went past one. `ahead`: the line on what running out
595
+ * before the weekly reset would cost on usage credits (credits.ts
596
+ * creditsAheadLine), under the weekly window's run-out.
556
597
  */
557
- export declare function renderLimits(r: LimitsReport, pastLimit?: string[]): string;
598
+ export declare function renderLimits(r: LimitsReport, pastLimit?: string[], ahead?: string): string;
558
599
  /**
559
600
  * `limits --report`: a block to paste into a GitHub issue. Per weekly
560
601
  * window: % used, dollars and tokens per 1%, the split by entrypoint and