context-doctor 0.47.0 → 0.49.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 (84) hide show
  1. package/README.md +17 -14
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +68 -26
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/budget.d.ts +5 -2
  9. package/dist/budget.js +21 -7
  10. package/dist/cache.js +3 -3
  11. package/dist/cachemisses.d.ts +3 -0
  12. package/dist/cachemisses.js +8 -0
  13. package/dist/cachettl.js +6 -2
  14. package/dist/ccost.d.ts +160 -0
  15. package/dist/ccost.js +304 -0
  16. package/dist/cli.js +154 -32
  17. package/dist/cline.d.ts +41 -0
  18. package/dist/cline.js +174 -0
  19. package/dist/coldresume.d.ts +11 -0
  20. package/dist/coldresume.js +3 -3
  21. package/dist/coldreturns.d.ts +145 -0
  22. package/dist/coldreturns.js +282 -0
  23. package/dist/compactcost.d.ts +10 -4
  24. package/dist/compactcost.js +12 -7
  25. package/dist/compactwindow.js +2 -2
  26. package/dist/copilotusage.d.ts +78 -0
  27. package/dist/copilotusage.js +193 -0
  28. package/dist/doctor.d.ts +6 -0
  29. package/dist/doctor.js +17 -4
  30. package/dist/fix.d.ts +35 -4
  31. package/dist/fix.js +55 -8
  32. package/dist/install.js +2 -0
  33. package/dist/limits.d.ts +222 -14
  34. package/dist/limits.js +684 -33
  35. package/dist/mcp.d.ts +4 -0
  36. package/dist/mcp.js +142 -98
  37. package/dist/mcpclient.js +73 -42
  38. package/dist/mcpdefer.d.ts +47 -0
  39. package/dist/mcpdefer.js +91 -0
  40. package/dist/mod/api.d.ts +72 -2
  41. package/dist/mod/api.js +5 -1
  42. package/dist/mod/logic.d.ts +281 -0
  43. package/dist/mod/logic.js +336 -0
  44. package/dist/mod/register.d.ts +35 -2
  45. package/dist/mod/register.js +283 -6
  46. package/dist/modelids.d.ts +58 -0
  47. package/dist/modelids.js +133 -1
  48. package/dist/modmeasure.d.ts +6 -4
  49. package/dist/modmeasure.js +8 -4
  50. package/dist/opencode.d.ts +57 -0
  51. package/dist/opencode.js +234 -0
  52. package/dist/orgrates.d.ts +7 -0
  53. package/dist/orgrates.js +19 -0
  54. package/dist/overhead.d.ts +3 -0
  55. package/dist/overhead.js +5 -1
  56. package/dist/pricing.d.ts +59 -2
  57. package/dist/pricing.js +139 -12
  58. package/dist/proxy.d.ts +8 -1
  59. package/dist/proxy.js +13 -1
  60. package/dist/savings.d.ts +5 -1
  61. package/dist/savings.js +11 -5
  62. package/dist/scan.d.ts +3 -1
  63. package/dist/scan.js +8 -1
  64. package/dist/sessionprice.d.ts +5 -0
  65. package/dist/sessionprice.js +5 -1
  66. package/dist/spend.d.ts +86 -3
  67. package/dist/spend.js +240 -23
  68. package/dist/spendplace.d.ts +40 -0
  69. package/dist/spendplace.js +93 -0
  70. package/dist/spendteam.d.ts +160 -0
  71. package/dist/spendteam.js +286 -0
  72. package/dist/starts.d.ts +106 -0
  73. package/dist/starts.js +406 -0
  74. package/dist/statusline.d.ts +2 -2
  75. package/dist/statusline.js +2 -2
  76. package/dist/subagentmodel.js +9 -7
  77. package/dist/subagentpay.d.ts +31 -2
  78. package/dist/subagentpay.js +232 -68
  79. package/dist/subagents.js +3 -3
  80. package/dist/tasks.js +3 -2
  81. package/dist/tooloutput.js +5 -5
  82. package/dist/usagepane.d.ts +77 -0
  83. package/dist/usagepane.js +287 -0
  84. package/package.json +6 -3
@@ -0,0 +1,193 @@
1
+ /**
2
+ * GitHub Copilot CLI's own record of what it sent: `session.usage_record`
3
+ * events in `~/.copilot/session-state/<session>/events.jsonl` (or
4
+ * `$COPILOT_HOME`), one per model call. Checked 2026-11-15 against the
5
+ * readers that parse them (GitHub's own agent-radar collector in
6
+ * github/awesome-copilot, qualitylayer, tokscale, agentsview) and
7
+ * ccusage#2069 (1,142 records and no shutdown in one user's sessions).
8
+ * GitHub documents none of it; the shape:
9
+ *
10
+ * {"type":"session.usage_record","id":"…","timestamp":"…","data":{"usage":{
11
+ * "model":"claude-opus-4.6-1m","inputTokens":…,"outputTokens":…,
12
+ * "cacheReadTokens":…,"cacheWriteTokens":…,"reasoningTokens":…,
13
+ * "cost":1,"duration":…,"apiCallId":"…","isByok":false,
14
+ * "accounting":{"sourceSessionId":"…","usageId":"…"},
15
+ * "copilotUsage":{"totalNanoAiu":…}}}}
16
+ *
17
+ * - `inputTokens` holds the cached tokens too (read and written): the
18
+ * uncached input is what is left after both.
19
+ * - `reasoningTokens` is part of `outputTokens`, not added again.
20
+ * - `cost` is the request's premium-request multiplier (1, or 14 for a
21
+ * premium model), not dollars. `copilotUsage.totalNanoAiu` is the AI
22
+ * credits it used, in billionths: one credit is $0.01.
23
+ * - The same call can be written twice (Copilot CLI 1.0.108: "count each
24
+ * newly recorded model call once, even when its usage event is received
25
+ * again"): one call is its accounting id, else its API call id, else the
26
+ * event's id.
27
+ * - A compaction (`session.compaction_complete`, `compactionTokensUsed`) is
28
+ * a model call of its own, unless a usage record already names its
29
+ * request.
30
+ * - Where it ran: `session.start` (and `session.resume`) carry
31
+ * `data.context` with `cwd`, `gitRoot`, `branch` and `repository`.
32
+ *
33
+ * Sessions from Copilot CLI versions that write no usage records (only
34
+ * cumulative `session.shutdown` totals) are not read: their per-resume
35
+ * figures cannot be told apart reliably (ccusage's notes on it run a page).
36
+ */
37
+ import { existsSync, readdirSync, statSync } from "node:fs";
38
+ import { homedir } from "node:os";
39
+ import { join } from "node:path";
40
+ import { pick, rowsOf } from "./scan.js";
41
+ /** Copilot's home: $COPILOT_HOME when set (and `home` is this user's), else <home>/.copilot. */
42
+ export function copilotDataDir(home = homedir()) {
43
+ return home === homedir() && process.env.COPILOT_HOME ? process.env.COPILOT_HOME : join(home, ".copilot");
44
+ }
45
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
46
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
47
+ /** "claude-opus-4.6-1m" -> "claude-opus-4.6"; "<provider uuid>/gpt-x" -> "gpt-x". */
48
+ export function copilotModel(raw) {
49
+ return raw.replace(/^[0-9a-f]{8}-[0-9a-f-]{27}\//i, "").replace(/-1m(?:-internal)?$/i, "");
50
+ }
51
+ /**
52
+ * What `spend` takes from a Copilot CLI session: each usage record's
53
+ * numbers and ids, each compaction's, and each start's context. No message
54
+ * text, no tool call.
55
+ */
56
+ export const COPILOT_USAGE_ROWS = {
57
+ id: "copilot-usage.1",
58
+ init: () => ({}),
59
+ line(line, row, out) {
60
+ if (!line.includes('"session.usage_record"') && !line.includes('"session.compaction_complete"') && !line.includes('"session.start"') && !line.includes('"session.resume"'))
61
+ return;
62
+ let e;
63
+ try {
64
+ e = row();
65
+ }
66
+ catch {
67
+ return;
68
+ }
69
+ const d = e?.data;
70
+ if (!d || typeof d !== "object")
71
+ return;
72
+ if (e.type === "session.start" || e.type === "session.resume") {
73
+ const c = d.context;
74
+ if (c && typeof c === "object")
75
+ out.push({ k: "ctx", ...pick(c, ["cwd", "gitRoot", "branch", "repository"]) });
76
+ return;
77
+ }
78
+ const ts = typeof e.timestamp === "string" ? e.timestamp : "";
79
+ if (e.type === "session.usage_record") {
80
+ const u = d.usage;
81
+ if (!u || typeof u !== "object")
82
+ return;
83
+ const acc = u.accounting && typeof u.accounting === "object" ? u.accounting : {};
84
+ out.push({
85
+ k: "u", ts, ...(typeof e.id === "string" ? { id: e.id } : {}),
86
+ ...pick(u, ["model", "inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "cost", "apiCallId", "isByok"]),
87
+ ...(text(acc.sourceSessionId) && text(acc.usageId) ? { acc: `${acc.sourceSessionId}\u0000${acc.usageId}`, usageId: acc.usageId } : {}),
88
+ ...(typeof u.copilotUsage?.totalNanoAiu === "number" ? { nano: u.copilotUsage.totalNanoAiu } : {}),
89
+ ...(u.provider && typeof u.provider === "object" && typeof u.provider.kind === "string" ? { provider: u.provider.kind } : {}),
90
+ });
91
+ return;
92
+ }
93
+ if (e.type === "session.compaction_complete" && d.compactionTokensUsed && typeof d.compactionTokensUsed === "object") {
94
+ const u = d.compactionTokensUsed;
95
+ out.push({
96
+ k: "c", ts, ...(typeof e.id === "string" ? { id: e.id } : {}), ...(text(d.requestId) ? { requestId: d.requestId } : {}),
97
+ ...(text(d.behaviorModelId) ? { behavior: d.behaviorModelId } : {}),
98
+ ...pick(u, ["model", "inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]),
99
+ ...(typeof u.copilotUsage?.totalNanoAiu === "number" ? { nano: u.copilotUsage.totalNanoAiu } : {}),
100
+ });
101
+ }
102
+ },
103
+ };
104
+ /** A record's call, priced by nobody yet. */
105
+ function call(r, session, ctx) {
106
+ const ts = Date.parse(r.ts);
107
+ const model = text(r.model) ?? text(r.behavior);
108
+ if (!Number.isFinite(ts))
109
+ return undefined;
110
+ const read = num(r.cacheReadTokens), write = num(r.cacheWriteTokens);
111
+ const c = { ts, session, model: model ? copilotModel(model) : "unknown", input: Math.max(0, num(r.inputTokens) - read - write), read, write, output: num(r.outputTokens) };
112
+ if (c.input + c.read + c.write + c.output === 0 && !num(r.nano))
113
+ return undefined;
114
+ if (typeof r.nano === "number" && r.nano >= 0)
115
+ c.credits = r.nano / 1e9;
116
+ if (typeof r.cost === "number" && r.cost >= 0)
117
+ c.premium = r.cost;
118
+ if (r.isByok === true || (typeof r.provider === "string" && r.provider !== "copilot" && r.provider !== "loki"))
119
+ c.byok = true;
120
+ if (ctx.cwd)
121
+ c.cwd = ctx.cwd;
122
+ if (ctx.gitRoot)
123
+ c.gitRoot = ctx.gitRoot;
124
+ if (ctx.branch)
125
+ c.branch = ctx.branch;
126
+ return c;
127
+ }
128
+ /** The model calls of one session's events file between `since` and `until`, each once. Throws when it cannot be read. */
129
+ export function copilotFileCalls(file, session, since, until = Infinity) {
130
+ const calls = new Map();
131
+ const compactions = [];
132
+ const named = new Set();
133
+ let ctx = {};
134
+ let anon = 0;
135
+ for (const r of rowsOf(file, COPILOT_USAGE_ROWS)) {
136
+ if (r.k === "ctx") {
137
+ ctx = { ...ctx, ...Object.fromEntries(Object.entries(r).filter(([k, v]) => k !== "k" && typeof v === "string")) };
138
+ continue;
139
+ }
140
+ const c = call(r, session, ctx);
141
+ if (r.k === "u") {
142
+ for (const id of [r.apiCallId, r.usageId])
143
+ if (text(id))
144
+ named.add(id);
145
+ if (!c)
146
+ continue;
147
+ // The same call written again replaces the first copy.
148
+ calls.set(r.acc ?? text(r.apiCallId) ?? text(r.id) ?? `#${anon++}`, c);
149
+ }
150
+ else if (r.k === "c" && c)
151
+ compactions.push([text(r.requestId), c]);
152
+ }
153
+ for (const [req, c] of compactions)
154
+ if (!req || !named.has(req))
155
+ calls.set(`compaction\u0000${req ?? anon++}`, c);
156
+ return [...calls.values()].filter((c) => c.ts >= since && c.ts <= until).sort((a, b) => a.ts - b.ts);
157
+ }
158
+ /** Each session's events file written since `since`: `session-state/<id>/events.jsonl`, and the flat `session-state/<id>.jsonl` some versions write. */
159
+ export function copilotSessionFiles(since, home = homedir()) {
160
+ const root = join(copilotDataDir(home), "session-state");
161
+ if (!existsSync(root))
162
+ return [];
163
+ const out = [];
164
+ let names;
165
+ try {
166
+ names = readdirSync(root);
167
+ }
168
+ catch {
169
+ return [];
170
+ }
171
+ for (const name of names) {
172
+ const flat = name.endsWith(".jsonl");
173
+ const file = flat ? join(root, name) : join(root, name, "events.jsonl");
174
+ try {
175
+ const st = statSync(file);
176
+ if (st.isFile() && st.mtimeMs >= since)
177
+ out.push({ file, session: flat ? name.slice(0, -6) : name });
178
+ }
179
+ catch { /* not a session */ }
180
+ }
181
+ return out;
182
+ }
183
+ /** Every Copilot CLI model call between `since` and `until`. An unreadable session is skipped. */
184
+ export function copilotCalls(since, until = Infinity, home = homedir()) {
185
+ const out = [];
186
+ for (const { file, session } of copilotSessionFiles(since, home)) {
187
+ try {
188
+ out.push(...copilotFileCalls(file, session, since, until));
189
+ }
190
+ catch { /* unreadable: skipped */ }
191
+ }
192
+ return out;
193
+ }
package/dist/doctor.d.ts CHANGED
@@ -33,6 +33,12 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
33
33
  * a second doctor cheap. Undefined when nothing ran in the period; ids that
34
34
  * are never billed (`<synthetic>`) are not named.
35
35
  */
36
+ /**
37
+ * Our price of Claude Code's sessions against its own figure (ccost.ts):
38
+ * the sessions of the last `days` that recorded one (`cost-state`), each
39
+ * from its start to its last record. Undefined when none did.
40
+ */
41
+ export declare function claudeCodeCostCheck(days?: number, now?: number): Check | undefined;
36
42
  export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
37
43
  /**
38
44
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
package/dist/doctor.js CHANGED
@@ -32,6 +32,8 @@ import { codexDir } from "./codexdir.js";
32
32
  import { periodSpend, readBudget } from "./budget.js";
33
33
  import { sessionPriceThresholds } from "./sessionprice.js";
34
34
  import { claudeSpend, codexSpend } from "./spend.js";
35
+ import { claudeUsageFiles } from "./limits.js";
36
+ import { compareSessions, comparisonCheck } from "./ccost.js";
35
37
  import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
36
38
  import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
37
39
  function claudeDesktopConfigPath() {
@@ -265,7 +267,7 @@ function claudeRouteChecks(layers, plugin, now = Date.now()) {
265
267
  };
266
268
  let mod;
267
269
  const act = modActivity();
268
- const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro and Max plans)";
270
+ const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro, Max and Ultra plans)";
269
271
  if (process.env.CONTEXT_DOCTOR_NO_MOD === "1") {
270
272
  mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
271
273
  }
@@ -362,6 +364,17 @@ export function cacheTtlCheck(home = homedir(), env = process.env) {
362
364
  * a second doctor cheap. Undefined when nothing ran in the period; ids that
363
365
  * are never billed (`<synthetic>`) are not named.
364
366
  */
367
+ /**
368
+ * Our price of Claude Code's sessions against its own figure (ccost.ts):
369
+ * the sessions of the last `days` that recorded one (`cost-state`), each
370
+ * from its start to its last record. Undefined when none did.
371
+ */
372
+ export function claudeCodeCostCheck(days = 30, now = Date.now()) {
373
+ const since = now - days * 86_400_000;
374
+ const items = claudeSpend(since, now);
375
+ const tops = [...new Set(claudeUsageFiles(since).filter((f) => !f.subagent).map((f) => f.top))];
376
+ return comparisonCheck(compareSessions(tops, items, since, now), days);
377
+ }
365
378
  export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir()) {
366
379
  const label = "Model prices";
367
380
  const since = now - days * 86_400_000;
@@ -821,14 +834,14 @@ export async function runDoctor() {
821
834
  /* settings.json unreadable is already reported by the hook check */
822
835
  }
823
836
  }
824
- // The plugin's mod: our session price against Claude Code's own cost, where it measured any.
837
+ // Our price against Claude Code's own cost: its cost-state records in the transcripts, else what the plugin's mod measured.
825
838
  try {
826
- const c = costCheck();
839
+ const c = claudeCodeCostCheck() ?? costCheck();
827
840
  if (c)
828
841
  checks.push(c);
829
842
  }
830
843
  catch {
831
- /* an unreadable ledger is no finding */
844
+ /* an unreadable transcript or ledger is no finding */
832
845
  }
833
846
  // Skill
834
847
  const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
package/dist/fix.d.ts CHANGED
@@ -33,18 +33,22 @@
33
33
  * variable), estimated as `spend` estimates them (progresssummaries.ts).
34
34
  *
35
35
  * The subagents' model is the one lever with a quality cost `fix` cannot
36
- * measure: it is offered with that said, applied only when named (never by
37
- * `--apply all`), and never over a value the user set.
36
+ * measure from history: its quality line quotes the newest `ab --via
37
+ * claude-code` comparison when there is one (abstore.ts), and says so when
38
+ * there is none. It is applied only when named (never by `--apply all`),
39
+ * and never over a value the user set.
38
40
  */
39
41
  import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
40
42
  import { type ClaudeCodeInstall } from "./modelswitch.js";
41
43
  import { type ProjectPlan } from "./prune.js";
44
+ import { type DeferEntry } from "./mcpdefer.js";
42
45
  import { readLedger } from "./ledger.js";
46
+ import { type AbStoredResult } from "./abstore.js";
43
47
  import { type SubagentModelReplay } from "./subagentmodel.js";
44
48
  import { type ToolOutputReplay } from "./tooloutput.js";
45
49
  import { type ProgressSummaryEstimate } from "./progresssummaries.js";
46
50
  import { type CodexCompactReport } from "./codexcompact.js";
47
- export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries";
51
+ export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries" | "mcp-defer";
48
52
  export interface Fix {
49
53
  id: FixId;
50
54
  title: string;
@@ -111,6 +115,8 @@ export interface FixInputs {
111
115
  recordProblem?: string;
112
116
  /** Every subagent request replayed at Sonnet 5.5 (subagentmodel.ts). */
113
117
  subagentModel?: SubagentModelReplay;
118
+ /** The newest kept `ab --via claude-code` comparison of the candidate with another model (abstore.ts): the subagent-model line quotes it. */
119
+ abComparison?: AbStoredResult;
114
120
  /** CLAUDE_CODE_SUBAGENT_MODEL as the user set it (their settings.json env, or the environment fix runs in): never overwritten. */
115
121
  subagentModelSet?: {
116
122
  value: string;
@@ -122,6 +128,14 @@ export interface FixInputs {
122
128
  returns: number;
123
129
  hooked: boolean;
124
130
  };
131
+ /** Keeping the cache warm while away, at the cap that nets most on this history (coldreturns.ts): a per-session command of the plugin's mod, not a setting. */
132
+ keepWarm?: {
133
+ hours: number;
134
+ netUsd: number;
135
+ pingUsd: number;
136
+ keptWarm: number;
137
+ returns: number;
138
+ };
125
139
  /** Every Bash and MCP result replayed at lower caps (tooloutput.ts). */
126
140
  toolOutput?: ToolOutputReplay;
127
141
  /** bashOutputMaxChars in the user's settings.json, or BASH_MAX_OUTPUT_LENGTH as the user set it (the setting would replace it): never overwritten. */
@@ -146,6 +160,20 @@ export interface FixInputs {
146
160
  value: string;
147
161
  where: string;
148
162
  };
163
+ /**
164
+ * MCP servers in the user's own config whose tool definitions went whole
165
+ * into session and subagent starts (starts.ts), each with its share of what
166
+ * re-reading them cost over the period.
167
+ */
168
+ mcpDefer?: {
169
+ servers: Array<{
170
+ name: string;
171
+ scope: string;
172
+ tokens: number;
173
+ usd: number;
174
+ }>;
175
+ days: number;
176
+ };
149
177
  }
150
178
  export declare const money: (n: number) => string;
151
179
  /** " (48%)", or " (37% of subagents)" for a share of something else. */
@@ -171,6 +199,8 @@ export interface FixRecord {
171
199
  oneHourShareBefore?: number;
172
200
  /** For prune: the project folder. */
173
201
  cwd?: string;
202
+ /** For mcp-defer: each alwaysLoad key it set in ~/.claude.json, and what was there before. */
203
+ entries?: DeferEntry[];
174
204
  /** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
175
205
  modelsBefore?: Record<string, number>;
176
206
  }
@@ -212,6 +242,7 @@ export declare function applyFix(fix: Fix, deps?: FixDeps, context?: {
212
242
  oneHourShare?: number;
213
243
  prune?: ProjectPlan;
214
244
  modelsBefore?: Record<string, number>;
245
+ mcpDefer?: FixInputs["mcpDefer"];
215
246
  }): Promise<{
216
247
  ok: boolean;
217
248
  lines: string[];
@@ -267,7 +298,7 @@ export declare function savedSince(records: FixRecord[], opts?: {
267
298
  }): SinceResult[];
268
299
  /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
269
300
  export declare function overlaps(fixes: Fix[]): string[];
270
- export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
301
+ export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number, keepWarm?: FixInputs["keepWarm"]): string;
271
302
  export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[], codexBilledUsd?: number): string;
272
303
  export declare function parseFixIds(raw: string, fixes: Fix[]): {
273
304
  ids: FixId[];
package/dist/fix.js CHANGED
@@ -33,8 +33,10 @@
33
33
  * variable), estimated as `spend` estimates them (progresssummaries.ts).
34
34
  *
35
35
  * The subagents' model is the one lever with a quality cost `fix` cannot
36
- * measure: it is offered with that said, applied only when named (never by
37
- * `--apply all`), and never over a value the user set.
36
+ * measure from history: its quality line quotes the newest `ab --via
37
+ * claude-code` comparison when there is one (abstore.ts), and says so when
38
+ * there is none. It is applied only when named (never by `--apply all`),
39
+ * and never over a value the user set.
38
40
  */
39
41
  import { existsSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
40
42
  import { homedir } from "node:os";
@@ -47,10 +49,12 @@ import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl, subagentTranscripts } fro
47
49
  import { compareVersions, describeInstalls } from "./modelswitch.js";
48
50
  import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
49
51
  import { compactWindowOverrides, effectiveEnv, processEnvWhere, settingsSources, shellSet, ttlOverrides, underClaudeCode } from "./effective.js";
50
- import { tilde } from "./claudedir.js";
52
+ import { claudeJsonPath, tilde } from "./claudedir.js";
51
53
  import { applyPrune, undoPrune } from "./prune.js";
54
+ import { applyMcpDefer, MCP_DEFER_SINCE, undoMcpDefer } from "./mcpdefer.js";
52
55
  import { fallbackStateDir, readLedger } from "./ledger.js";
53
56
  import { claudeDir } from "./claudedir.js";
57
+ import { comparisonLine } from "./abstore.js";
54
58
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
55
59
  import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
56
60
  import { disablesSummaries, estimateProgressSummaries, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE } from "./progresssummaries.js";
@@ -63,7 +67,7 @@ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCom
63
67
  * the subagent variable ahead of agent definitions there). autoCompactWindow
64
68
  * is not in 2.1.62 and the changelog does not say when it came: not named.
65
69
  */
66
- const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
70
+ const SINCE = { "mcp-defer": MCP_DEFER_SINCE, "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
67
71
  /** Below this a priced fix is not worth a setting. */
68
72
  const MIN_USD = 1;
69
73
  export const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
@@ -184,7 +188,7 @@ export function planFixes(i) {
184
188
  // The subagents' own bill, not the main conversations' input the plan's first line names.
185
189
  shareOf: "of subagents",
186
190
  basis: `${reqs.toLocaleString("en-US")} subagent requests priced at ${SUBAGENT_CANDIDATE_NAME} with the token counts they had (${money(sm.billedUsd)} billed for all ${sm.agents} subagents); an estimate: another model tokenizes and works differently`,
187
- quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`,
191
+ quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); ${i.abComparison ? `measured by context-doctor ab ${comparisonLine(i.abComparison)} (${i.abComparison.tasks} small coding tasks, ${i.abComparison.repeat} run${i.abComparison.repeat === 1 ? "" : "s"} each; your subagents' own work may differ)` : `the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`}`,
188
192
  change: `${where}: env.${SUBAGENT_MODEL_ENV} = "${SUBAGENT_CANDIDATE}"`,
189
193
  state: "available",
190
194
  value: SUBAGENT_CANDIDATE,
@@ -267,6 +271,20 @@ export function planFixes(i) {
267
271
  const n = ps.none.host;
268
272
  fixes.push({ id: "progress-summaries", title: "Subagent progress summaries", basis: "", quality: "", change: "", state: "not-here", note: `your ${n} background subagent${n === 1 ? "" : "s"} ran in ${ps.hosts.map(hostName).join(" and ")}, where Claude Code writes no progress summaries: nothing to turn off` });
269
273
  }
274
+ const md = i.mcpDefer?.servers.filter((s) => s.scope === "user" || s.scope === "project") ?? [];
275
+ if (md.length) {
276
+ const usd = md.reduce((t, s) => t + s.usd, 0);
277
+ fixes.push({
278
+ id: "mcp-defer",
279
+ title: `Keep ${md.length === 1 ? `the MCP server ${md[0].name}` : `${md.length} MCP servers`} behind tool search`,
280
+ ...(usd > 0 ? { savedUsd: usd } : {}),
281
+ basis: `${md.map((s) => `${s.name} (~${k(s.tokens)} tokens)`).join(", ")} went whole into every session and subagent start that loaded ${md.length === 1 ? "it" : "them"}, re-read at each step: what that cost in ${i.mcpDefer.days} days, at most (the tool names stay)`,
282
+ quality: "Claude loads one of their tools through tool search when it needs it: one more step the first time in a conversation. Not measured here: applied only when named",
283
+ change: `${tilde(claudeJsonPath())}: "alwaysLoad": false on ${md.map((s) => s.name).join(", ")}`,
284
+ state: "available",
285
+ value: "false",
286
+ });
287
+ }
270
288
  for (const f of fixes) {
271
289
  const o = i.overrides?.[f.id];
272
290
  if (o?.length && f.state === "available")
@@ -349,7 +367,7 @@ const YOURS = new Set(["subagent-model", "tool-output", "progress-summaries"]);
349
367
  /** The environment variable a settings fix writes, when the shell's own value is the user's too. */
350
368
  const SHELL_ENV = { "subagent-model": SUBAGENT_MODEL_ENV, "progress-summaries": PROGRESS_SUMMARIES_ENV };
351
369
  /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
352
- const NAMED_ONLY = new Set(["subagent-model"]);
370
+ const NAMED_ONLY = new Set(["subagent-model", "mcp-defer"]);
353
371
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
354
372
  export function fixOverrides(id, deps = {}) {
355
373
  // Codex reads its own config.toml: a profile's value, or a project's file.
@@ -545,6 +563,23 @@ export async function applyFix(fix, deps = {}, context = {}) {
545
563
  withLock(lockPath(home), () => writeFixRecords([...loadFixRecords(home).filter((x) => x.id !== "autopilot"), { id: "autopilot", at }], home));
546
564
  return r;
547
565
  }
566
+ if (fix.id === "mcp-defer") {
567
+ const servers = context.mcpDefer?.servers ?? [];
568
+ if (!servers.length)
569
+ return { ok: false, lines: ["mcp-defer: no MCP server of yours went whole into a start"] };
570
+ return withLock(lockPath(home), () => {
571
+ const records = loadFixRecords(home);
572
+ const r = applyMcpDefer(servers, { home, cwd: deps.cwd });
573
+ if (r.entries.length) {
574
+ const old = records.find((x) => x.id === "mcp-defer");
575
+ // A second apply keeps the first one's entries (their earlier values) and adds the new keys.
576
+ const same = (a, b) => a.key.join("/") === b.key.join("/");
577
+ const entries = [...(old?.entries ?? []).filter((e) => !r.entries.some((n) => same(n, e))), ...r.entries.map((n) => old?.entries?.find((e) => same(e, n)) ?? n)];
578
+ writeFixRecords([...records.filter((x) => x.id !== "mcp-defer"), { id: "mcp-defer", at: old?.at ?? at, file: r.file, entries }], home);
579
+ }
580
+ return { ok: true, lines: r.lines };
581
+ });
582
+ }
548
583
  if (fix.id === "prune") {
549
584
  if (!context.prune)
550
585
  return { ok: false, lines: ["prune: no plan for this folder"] };
@@ -650,6 +685,9 @@ export async function undoFixes(ids, deps = {}) {
650
685
  done = false;
651
686
  }
652
687
  }
688
+ else if (r.id === "mcp-defer") {
689
+ lines.push(...withLock(lockPath(home), () => undoMcpDefer(r.file ?? claudeJsonPath(home), r.entries ?? [])));
690
+ }
653
691
  else if (r.id === "prune") {
654
692
  const u = r.cwd ? undoPrune(r.cwd) : undefined;
655
693
  lines.push(u ? `✓ switched back on in ${u.file}: ${u.removed.join(", ") || "nothing left to remove"}` : "✓ prune: nothing left to undo");
@@ -845,6 +883,7 @@ const LABEL = {
845
883
  "tool-output": "Long Bash output",
846
884
  "codex-compact": "Codex auto-compact limit",
847
885
  "progress-summaries": "Subagent progress summaries",
886
+ "mcp-defer": "MCP servers sent whole",
848
887
  };
849
888
  /**
850
889
  * Priced levers that save part of the same dollars, and why: each is
@@ -867,7 +906,7 @@ export function overlaps(fixes) {
867
906
  const priced = new Set(fixes.filter((f) => f.savedUsd !== undefined).map((f) => f.id));
868
907
  return OVERLAPS.filter(([a, b]) => priced.has(a) && priced.has(b)).map(([a, b, why]) => `${a} and ${b}: ${why}.`);
869
908
  }
870
- export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
909
+ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0, keepWarm) {
871
910
  const out = [];
872
911
  if (recordProblem)
873
912
  out.push(`⚠ ${recordProblem}`);
@@ -922,14 +961,22 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
922
961
  const elsewhere = fixes.filter((f) => f.state === "not-here");
923
962
  for (const f of elsewhere)
924
963
  out.push(` - ${LABEL[f.id]}: ${f.note}`);
925
- if (coldResume && coldResume.netUsd >= MIN_USD) {
964
+ const compactAdvice = coldResume !== undefined && coldResume.netUsd >= MIN_USD;
965
+ const warmAdvice = keepWarm !== undefined && keepWarm.netUsd >= MIN_USD;
966
+ if (compactAdvice || warmAdvice) {
926
967
  out.push("");
927
968
  out.push("Advice you act on");
969
+ }
970
+ if (compactAdvice) {
928
971
  out.push(` /compact when you come back to a big session after the cache expired: ${money(coldResume.netUsd)} over ${coldResume.returns} returns.`);
929
972
  out.push(coldResume.hooked
930
973
  ? " The every-prompt hook offers it at those moments; say yes when it does."
931
974
  : ` Nothing points those moments out yet: ${command("install")} (or the Claude Code plugin) adds the hook that does.`);
932
975
  }
976
+ if (warmAdvice) {
977
+ out.push(` Keep the cache warm while you step away, up to ${keepWarm.hours} h: ${money(keepWarm.netUsd)} net of ${money(keepWarm.pingUsd)} in pings (${keepWarm.keptWarm} of ${keepWarm.returns} cold returns kept warm).`);
978
+ out.push(` /context-doctor-keep-warm ${keepWarm.hours}h in Claude Code with the plugin, each time you leave; on a subscription the pings use your limit too. By gap: ${command("cache-misses")}`);
979
+ }
933
980
  out.push("");
934
981
  if (avail.length) {
935
982
  out.push(`Apply: ${command("fix")} in a terminal asks about each one; or ${command(`fix --apply ${avail.map((f) => f.id).join(",")}`)}`);
package/dist/install.js CHANGED
@@ -1631,6 +1631,8 @@ const OUR_CLAUDE_FILES = [
1631
1631
  ".context-doctor-budget.json",
1632
1632
  ".context-doctor-budget-state.json",
1633
1633
  ".context-doctor-budget-said.d",
1634
+ // ab --via claude-code's kept comparisons (abstore.ts), which fix quotes.
1635
+ ".context-doctor-ab.json",
1634
1636
  ];
1635
1637
  export async function runUninstall() {
1636
1638
  changes = 0;