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,511 @@
1
+ /**
2
+ * `context-doctor ab --via claude-code`: the A/B suite's tasks run through
3
+ * the person's own Claude Code (`claude -p`), on the person's own sign-in,
4
+ * one arm per model. No API key: on a claude.ai plan the runs draw on the
5
+ * plan's usage limits, not dollars. It answers the question the subagent
6
+ * lever (`fix`'s subagent-model) could not: does Sonnet 5.5 do the work Opus
7
+ * 5.5 did, here, on this plan?
8
+ *
9
+ * Each run gets a fresh temporary copy of the task's tiny repository and one
10
+ * `claude -p` in it, with every flag verified on Claude Code 2.1.311, 2.1.321
11
+ * and 2.1.325 against a local mock Messages API (docs/ab.md):
12
+ *
13
+ * --print, the prompt on stdin (no positional after a variadic flag)
14
+ * --model <id> the arm
15
+ * --output-format stream-json --verbose
16
+ * the init event (version, tools, auth
17
+ * source), rate_limit_event, and the
18
+ * result: total_cost_usd, usage, num_turns
19
+ * --max-turns <n> (hidden; result subtype error_max_turns)
20
+ * --restricted file tools confined to the working
21
+ * directory; user, project and local
22
+ * settings ignored (their hooks and
23
+ * permission rules too)
24
+ * --safe-mode no CLAUDE.md, skills, plugins, hooks,
25
+ * MCP servers, agents or output styles
26
+ * --strict-mcp-config no MCP server at all
27
+ * --disable-slash-commands
28
+ * --no-session-persistence no transcript in ~/.claude/projects
29
+ * (nothing for the reports to count)
30
+ * --tools Read,Edit,Write,Glob,Grep,Bash
31
+ * --allowedTools "Read Edit Write Glob Grep Bash(node test.mjs)"
32
+ * --disallowedTools "Edit(test.mjs) Write(test.mjs)"
33
+ * --permission-mode dontAsk --permission-prompts none
34
+ * anything not allowed above is denied,
35
+ * nobody is asked
36
+ * --settings {"sandbox":{...}} Claude Code's sandbox on, failing
37
+ * closed: the code `node test.mjs` runs
38
+ * cannot write outside the run folder
39
+ * and temp, or reach the network
40
+ * --max-budget-usd <usd> only with --budget
41
+ *
42
+ * The hidden check scores the run as the Messages API arms are scored. The
43
+ * tokens and cost are Claude Code's own (the result's usage and
44
+ * total_cost_usd: on a plan, the list-price equivalent). A run past its time
45
+ * limit is killed with its process group; Ctrl-C kills every run and removes
46
+ * every folder. A usage limit reached mid-run (a rejected rate_limit_event,
47
+ * or a result with API status 429) or a refused sign-in stops the suite: no
48
+ * further run starts.
49
+ *
50
+ * A finished comparison is kept (the newest 20) beside the other state
51
+ * files, so `fix` can quote it on the subagent-model line.
52
+ */
53
+ import { spawn, spawnSync } from "node:child_process";
54
+ import { writeFileSync } from "node:fs";
55
+ import { AB_TASKS } from "./abtasks.js";
56
+ import { CHECK_TIMEOUT_MS, DEFAULT_AB_MODEL, estimateAb, killTree, makeRun, outProblem, removeRoot, STOPPED_EARLY, stopOnSignal, taskPrompt, verifyRun } from "./ab.js";
57
+ import { claudeLimitFit, limitsReport } from "./limits.js";
58
+ import { abResultsPath, appendAbResult, onPlan, passLine } from "./abstore.js";
59
+ import { exactClaudePricingFor, formatUsd } from "./pricing.js";
60
+ import { SUBAGENT_CANDIDATE } from "./subagentpay.js";
61
+ import { modelName } from "./subagentmodel.js";
62
+ import { formatTokens } from "./tokens.js";
63
+ import { toolCwd } from "./toolcwd.js";
64
+ /** The arms when none are named: the subagent lever's question. */
65
+ export const DEFAULT_CC_MODEL = SUBAGENT_CANDIDATE;
66
+ export const DEFAULT_CC_COMPARE = DEFAULT_AB_MODEL;
67
+ /** Claude Code turns a run may take (it reads, edits and runs the check one tool at a time). */
68
+ export const DEFAULT_CC_MAX_TURNS = 30;
69
+ /** A run still going after this long is killed. */
70
+ export const DEFAULT_CC_TIMEOUT_S = 600;
71
+ /** Runs in flight: two, so a plan's limits are not raced. */
72
+ const DEFAULT_CC_CONCURRENCY = 2;
73
+ /**
74
+ * The estimate's shape for a Claude Code run: its own system prompt, the six
75
+ * tools and the reminders on the first message came to ~29k characters
76
+ * (~9k tokens) on 2.1.325 with these flags, and it takes about ten requests
77
+ * where the Messages API harness takes six.
78
+ */
79
+ const CC_SHAPE = { requests: 10, baseTokens: 9000 };
80
+ /** The flags ab needs, as `claude --help` lists them (--max-turns is accepted but not listed). */
81
+ export const REQUIRED_FLAGS = ["--print", "--model", "--output-format", "--verbose", "--restricted", "--safe-mode", "--strict-mcp-config", "--no-session-persistence", "--disable-slash-commands", "--tools", "--allowedTools", "--disallowedTools", "--permission-mode", "--permission-prompts", "--settings", "dontAsk"];
82
+ const SMOKE = "test.mjs";
83
+ const ALLOWED = ["Read", "Edit", "Write", "Glob", "Grep", `Bash(node ${SMOKE})`];
84
+ /** The sandbox, failing closed: no writes outside the working folder and temp, no network, nothing run outside it. */
85
+ const SANDBOX_SETTINGS = { sandbox: { enabled: true, failIfUnavailable: true, autoAllowBashIfSandboxed: false, allowUnsandboxedCommands: false } };
86
+ /** What the run asks, after the task itself: the Messages API harness's system prompt, in Claude Code's words. */
87
+ const INSTRUCTIONS = "Make the smallest correct change; the work is judged by a hidden test of the behaviour the request and the repository's documents describe. " +
88
+ `\`node ${SMOKE}\` is the smoke test: it shows the code loads and runs, not that the results are right, and it cannot be changed. ` +
89
+ `When you think the task is done, run \`node ${SMOKE}\`; once it passes, reply with one sentence saying what you changed.`;
90
+ /** The arguments of one run's `claude -p` (the prompt goes on stdin). */
91
+ export function claudeArgs(model, maxTurns, maxBudgetUsd) {
92
+ return [
93
+ "-p",
94
+ "--model", model,
95
+ "--output-format", "stream-json", "--verbose",
96
+ "--max-turns", String(maxTurns),
97
+ "--restricted", "--safe-mode", "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence",
98
+ "--tools", "Read,Edit,Write,Glob,Grep,Bash",
99
+ "--allowedTools", ALLOWED.join(" "),
100
+ "--disallowedTools", `Edit(${SMOKE}) Write(${SMOKE})`,
101
+ "--permission-mode", "dontAsk", "--permission-prompts", "none",
102
+ "--settings", JSON.stringify(SANDBOX_SETTINGS),
103
+ ...(maxBudgetUsd !== undefined ? ["--max-budget-usd", maxBudgetUsd.toFixed(4)] : []),
104
+ ];
105
+ }
106
+ export function claudeCodePrompt(task) {
107
+ return `${taskPrompt(task)}\n\n${INSTRUCTIONS}`;
108
+ }
109
+ /** The Claude Code ab runs: CONTEXT_DOCTOR_CLAUDE_BIN, else `claude` on PATH. */
110
+ export function claudeBin() {
111
+ return process.env.CONTEXT_DOCTOR_CLAUDE_BIN?.trim() || "claude";
112
+ }
113
+ /** Claude Code's environment: the caller's (its sign-in lives there), without the marker of an enclosing session. */
114
+ function claudeEnv() {
115
+ const env = { ...process.env };
116
+ delete env.CLAUDECODE;
117
+ return env;
118
+ }
119
+ /** `claude --version`, `--help` and `auth status --json`: all local, nothing sent to a model. */
120
+ export function inspectClaudeCode(bin = claudeBin()) {
121
+ const run = (args) => spawnSync(bin, args, { cwd: toolCwd(), env: claudeEnv(), encoding: "utf8", timeout: 30_000, windowsHide: true });
122
+ const v = run(["--version"]);
123
+ if (v.error || v.status !== 0) {
124
+ const why = v.error?.code === "ENOENT" ? "not found" : (v.error?.message ?? `exit ${v.status}: ${(v.stderr ?? "").trim().slice(0, 200)}`);
125
+ return { bin, missing: [], loggedIn: false, problem: `Claude Code (${bin}) could not be run: ${why}` };
126
+ }
127
+ const version = /(\d+\.\d+\.\d+)/.exec(v.stdout ?? "")?.[1];
128
+ const help = run(["--help"]).stdout ?? "";
129
+ const missing = REQUIRED_FLAGS.filter((f) => !help.includes(f));
130
+ const a = run(["auth", "status", "--json"]);
131
+ let auth = {};
132
+ try {
133
+ auth = JSON.parse(a.stdout ?? "") ?? {};
134
+ }
135
+ catch { /* an older Claude Code, or none */ }
136
+ const str = (k) => (typeof auth[k] === "string" ? auth[k] : undefined);
137
+ return { bin, version, missing, loggedIn: auth.loggedIn === true, authMethod: str("authMethod"), subscriptionType: str("subscriptionType"), apiKeySource: str("apiKeySource") };
138
+ }
139
+ function whoPays(info) {
140
+ if (onPlan(info))
141
+ return `signed in to claude.ai${info.subscriptionType ? ` (${info.subscriptionType} plan)` : ""}: this draws on your plan's usage limits (the weekly window, and the 5-hour one on plans that have it), not dollars`;
142
+ if (info.authMethod === "api_key")
143
+ return `on an API key (${info.apiKeySource ?? "API key"}): this bills that key, in dollars`;
144
+ return `signed in as ${info.authMethod ?? "unknown"}: billed as your Claude Code is set up`;
145
+ }
146
+ function readEvent(line, s) {
147
+ let e;
148
+ try {
149
+ e = JSON.parse(line);
150
+ }
151
+ catch {
152
+ return;
153
+ }
154
+ if (!e || typeof e !== "object")
155
+ return;
156
+ if (e.type === "system" && e.subtype === "init")
157
+ s.init = e;
158
+ else if (e.type === "result")
159
+ s.result = e;
160
+ else if (e.type === "rate_limit_event" && e.rate_limit_info?.status === "rejected")
161
+ s.limit = e.rate_limit_info;
162
+ else if (e.type === "assistant" && typeof e.error === "string")
163
+ s.assistantError ??= e.error;
164
+ }
165
+ async function runOne(task, model, rep, ctx) {
166
+ const started = Date.now();
167
+ const run = { task: task.id, model, rep, pass: false, stop: "", turns: 0, inputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 0, costUsd: 0, wallMs: 0, denied: 0 };
168
+ // Under --budget: this run's share of what is left, split over the free slots, passed as --max-budget-usd.
169
+ let cap;
170
+ if (Number.isFinite(ctx.budgetUsd)) {
171
+ cap = (ctx.budgetUsd - ctx.spent - ctx.reserved) / Math.max(1, ctx.concurrency - ctx.inFlight);
172
+ if (cap < 0.01) {
173
+ run.stop = "budget";
174
+ return run;
175
+ }
176
+ ctx.reserved += cap;
177
+ }
178
+ ctx.inFlight++;
179
+ const paths = makeRun(task, ctx.live);
180
+ try {
181
+ const s = {};
182
+ let stderr = "";
183
+ let timedOut = false;
184
+ const code = await new Promise((resolveRun) => {
185
+ if (ctx.live.stopping)
186
+ return; // Ctrl-C: held until the exit
187
+ let child;
188
+ try {
189
+ child = spawn(ctx.bin, claudeArgs(model, ctx.maxTurns, cap), { cwd: paths.repo, env: claudeEnv(), stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
190
+ }
191
+ catch (e) {
192
+ stderr = e.message;
193
+ resolveRun(1);
194
+ return;
195
+ }
196
+ ctx.live.children.add(child);
197
+ let buf = "";
198
+ child.stdout.on("data", (d) => {
199
+ buf += d.toString("utf8");
200
+ let nl;
201
+ while ((nl = buf.indexOf("\n")) >= 0) {
202
+ readEvent(buf.slice(0, nl), s);
203
+ buf = buf.slice(nl + 1);
204
+ }
205
+ });
206
+ child.stderr.on("data", (d) => { stderr = (stderr + d.toString("utf8")).slice(-2000); });
207
+ child.stdin.on("error", () => { });
208
+ child.stdin.end(claudeCodePrompt(task));
209
+ const timer = setTimeout(() => { timedOut = true; killTree(child); }, ctx.timeoutMs);
210
+ let done = false;
211
+ const finish = (c) => {
212
+ if (done || ctx.live.stopping)
213
+ return;
214
+ done = true;
215
+ clearTimeout(timer);
216
+ if (buf.trim())
217
+ readEvent(buf, s);
218
+ killTree(child); // whatever it started and left in its group
219
+ ctx.live.children.delete(child);
220
+ resolveRun(c);
221
+ };
222
+ child.on("error", (e) => { stderr += `\n${e.message}`; finish(1); });
223
+ child.on("close", (c) => finish(c ?? 1));
224
+ });
225
+ const r = s.result;
226
+ if (r) {
227
+ const u = r.usage ?? {};
228
+ const n = (v) => (typeof v === "number" && v > 0 ? v : 0);
229
+ run.turns = n(r.num_turns);
230
+ run.inputTokens = n(u.input_tokens);
231
+ run.cacheReadTokens = n(u.cache_read_input_tokens);
232
+ run.cacheWriteTokens = n(u.cache_creation_input_tokens);
233
+ run.outputTokens = n(u.output_tokens);
234
+ run.costUsd = n(r.total_cost_usd);
235
+ run.denied = Array.isArray(r.permission_denials) ? r.permission_denials.length : 0;
236
+ ctx.spent += run.costUsd;
237
+ }
238
+ const said = (r && typeof r.result === "string" ? r.result : "").slice(0, 300);
239
+ if (timedOut) {
240
+ run.stop = "timeout";
241
+ run.error = `killed after ${Math.round(ctx.timeoutMs / 1000)} s`;
242
+ }
243
+ else if (s.limit || s.assistantError === "rate_limit" || r?.api_error_status === 429 || r?.api_error === "usage_limit_reached") {
244
+ run.stop = "limit";
245
+ run.error = said || `usage limit reached${s.limit?.resetsAt ? `, resets ${new Date(Number(s.limit.resetsAt) * 1000).toISOString()}` : ""}`;
246
+ ctx.fatal ??= `your plan's usage limit was reached (${run.error})`;
247
+ }
248
+ else if (!r) {
249
+ run.stop = "error";
250
+ run.error = `Claude Code ended (exit ${code}) without a result${stderr.trim() ? `: ${stderr.trim().slice(-300)}` : ""}`;
251
+ // It never started a session (an unknown flag, the sandbox unavailable): every run would end the same way.
252
+ if (!s.init)
253
+ ctx.fatal ??= run.error;
254
+ }
255
+ else if (r.subtype === "error_max_turns") {
256
+ run.stop = "turns";
257
+ }
258
+ else if (r.subtype === "error_max_budget_usd") {
259
+ run.stop = "budget";
260
+ }
261
+ else if (r.is_error) {
262
+ run.stop = "error";
263
+ run.error = said || String(r.subtype ?? "error");
264
+ if (s.assistantError === "authentication_failed" || r.api_error_status === 401 || r.api_error_status === 403)
265
+ ctx.fatal ??= `Claude Code's sign-in was refused (${run.error})`;
266
+ }
267
+ else {
268
+ run.stop = typeof r.stop_reason === "string" && r.stop_reason !== "stop_sequence" ? r.stop_reason : "end_turn";
269
+ }
270
+ run.pass = await verifyRun(task, paths, ctx.live);
271
+ }
272
+ finally {
273
+ ctx.inFlight--;
274
+ if (cap !== undefined)
275
+ ctx.reserved -= cap;
276
+ removeRoot(paths.root, ctx.live);
277
+ }
278
+ run.wallMs = Date.now() - started;
279
+ return run;
280
+ }
281
+ export async function runClaudeCodeAb(options, info = {}) {
282
+ const tasks = options.tasks ?? AB_TASKS;
283
+ const repeat = options.repeat ?? 1;
284
+ const models = [...new Set(options.models)];
285
+ const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CC_CONCURRENCY);
286
+ const ctx = {
287
+ bin: options.bin ?? claudeBin(),
288
+ maxTurns: options.maxTurns ?? DEFAULT_CC_MAX_TURNS,
289
+ timeoutMs: options.timeoutMs ?? DEFAULT_CC_TIMEOUT_S * 1000,
290
+ budgetUsd: options.budgetUsd ?? Infinity,
291
+ concurrency,
292
+ inFlight: 0,
293
+ spent: 0,
294
+ reserved: 0,
295
+ live: { children: new Set(), roots: new Set(), timeoutMs: CHECK_TIMEOUT_MS },
296
+ };
297
+ // Ctrl-C: every Claude Code and everything it started is killed (and gone before the exit), no run folder stays behind.
298
+ const unhook = stopOnSignal(ctx.live);
299
+ // Models alternate within each task, so a limit reached halfway leaves both arms with the same tasks.
300
+ const queue = [];
301
+ for (let rep = 1; rep <= repeat; rep++)
302
+ for (const task of tasks)
303
+ for (const model of models)
304
+ queue.push({ task, model, rep });
305
+ const runs = [];
306
+ let next = 0;
307
+ const worker = async () => {
308
+ while (next < queue.length && !ctx.fatal && !ctx.live.stopping) {
309
+ const { task, model, rep } = queue[next++];
310
+ const run = await runOne(task, model, rep, ctx);
311
+ runs.push(run);
312
+ options.onRun?.(run, runs.length, queue.length);
313
+ }
314
+ };
315
+ try {
316
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));
317
+ }
318
+ finally {
319
+ unhook();
320
+ }
321
+ const order = (r) => queue.findIndex((q) => q.task.id === r.task && q.model === r.model && q.rep === r.rep);
322
+ runs.sort((a, b) => order(a) - order(b));
323
+ return {
324
+ via: "claude-code",
325
+ at: new Date().toISOString(),
326
+ claudeCode: { version: info.version, authMethod: info.authMethod, subscriptionType: info.subscriptionType },
327
+ models,
328
+ tasks: tasks.map((t) => t.id),
329
+ repeat,
330
+ runs,
331
+ costUsd: ctx.spent,
332
+ ...(ctx.fatal ? { aborted: ctx.fatal } : {}),
333
+ };
334
+ }
335
+ export function modelTotals(result) {
336
+ return result.models.map((model) => result.runs.filter((r) => r.model === model).reduce((t, r) => {
337
+ const stopped = STOPPED_EARLY.has(r.stop);
338
+ return {
339
+ model,
340
+ runs: t.runs + 1,
341
+ completed: t.completed + (stopped ? 0 : 1),
342
+ passed: t.passed + (!stopped && r.pass ? 1 : 0),
343
+ stoppedEarly: t.stoppedEarly + (stopped ? 1 : 0),
344
+ tokens: t.tokens + r.inputTokens + r.cacheReadTokens + r.cacheWriteTokens + r.outputTokens,
345
+ costUsd: t.costUsd + r.costUsd,
346
+ };
347
+ }, { model, runs: 0, completed: 0, passed: 0, stoppedEarly: 0, tokens: 0, costUsd: 0 }));
348
+ }
349
+ export function renderClaudeCodeAb(result) {
350
+ const plan = onPlan(result.claudeCode);
351
+ const out = [];
352
+ out.push(`A/B quality through Claude Code${result.claudeCode.version ? ` ${result.claudeCode.version}` : ""}: ${result.tasks.length} tasks, ${result.models.map(modelName).join(" vs ")}, ${result.repeat} run${result.repeat === 1 ? "" : "s"} per task and model`);
353
+ out.push(plan ? `On your plan: ${formatUsd(result.costUsd)} at list prices, drawn from your usage limits, not billed.` : `Claude Code's cost: ${formatUsd(result.costUsd)}.`);
354
+ if (result.aborted)
355
+ out.push(`Stopped early: ${result.aborted}. Runs not started are not in the table.`);
356
+ const cell = (runs) => {
357
+ if (!runs.length)
358
+ return "–";
359
+ const t = modelTotals({ models: [runs[0].model], runs })[0];
360
+ const verdict = t.runs === 1 ? (STOPPED_EARLY.has(runs[0].stop) ? runs[0].stop.toUpperCase().slice(0, 7) : runs[0].pass ? "PASS" : "FAIL") : `${t.passed}/${t.completed}${t.stoppedEarly ? "*" : ""}`;
361
+ return `${verdict.padEnd(8)}${formatTokens(t.tokens / t.runs).padStart(6)} ${formatUsd(t.costUsd / t.runs).padStart(8)}`;
362
+ };
363
+ const W = 26;
364
+ out.push("", `${"task".padEnd(18)}${result.models.map((m) => modelName(m).padEnd(W)).join("")}`);
365
+ for (const id of result.tasks)
366
+ out.push(`${id.padEnd(18)}${result.models.map((m) => cell(result.runs.filter((r) => r.task === id && r.model === m)).padEnd(W)).join("")}`);
367
+ const totals = modelTotals(result);
368
+ out.push(`${"passed".padEnd(18)}${totals.map((t) => `${t.passed}/${t.completed} completed`.padEnd(W)).join("")}`);
369
+ if (totals.some((t) => t.stoppedEarly))
370
+ out.push(`${"stopped early".padEnd(18)}${totals.map((t) => String(t.stoppedEarly).padEnd(W)).join("")}(usage limit, time or turn limit, budget, an error: left out of the pass counts)`);
371
+ out.push(`${"tokens per run".padEnd(18)}${totals.map((t) => formatTokens(t.runs ? t.tokens / t.runs : 0).padEnd(W)).join("")}`);
372
+ out.push(`${(plan ? "list-price cost" : "cost").padEnd(18)}${totals.map((t) => formatUsd(t.costUsd).padEnd(W)).join("")}`);
373
+ const denied = result.runs.reduce((n, r) => n + r.denied, 0);
374
+ if (denied)
375
+ out.push(`${"refused calls".padEnd(18)}${denied} (outside the run folder, the smoke test, or another command: Claude Code's permissions said no)`);
376
+ const done = totals.filter((t) => t.completed > 0);
377
+ out.push("");
378
+ if (done.length < 2)
379
+ out.push("Fewer than two models completed a run: nothing to compare.");
380
+ else
381
+ out.push(`${passLine(totals)}.`);
382
+ out.push(result.repeat < 3 ? "One task's difference is noise at this size: --repeat 3 or more for a figure worth quoting." : `${result.repeat} runs per task and model.`);
383
+ return out.join("\n");
384
+ }
385
+ // -- The stored results, for fix --------------------------------------------------------------
386
+ /** Keep a finished comparison for fix (the newest 20). */
387
+ export function storeAbResult(result, path = abResultsPath()) {
388
+ const entry = {
389
+ at: result.at,
390
+ via: "claude-code",
391
+ claudeCodeVersion: result.claudeCode.version,
392
+ authMethod: result.claudeCode.authMethod,
393
+ subscriptionType: result.claudeCode.subscriptionType,
394
+ repeat: result.repeat,
395
+ tasks: result.tasks.length,
396
+ models: modelTotals(result).map((t) => ({ model: t.model, passed: t.passed, completed: t.completed, runs: t.runs, costUsd: Math.round(t.costUsd * 1e4) / 1e4 })),
397
+ };
398
+ appendAbResult(entry, path);
399
+ return entry;
400
+ }
401
+ /** The arms: --model (default Sonnet 5.5), then each --compare (default Opus 5.5; "none" for none). */
402
+ export function modelsFor(model, compare) {
403
+ const named = (compare ?? []).flatMap((c) => c.split(",")).map((c) => c.trim()).filter(Boolean);
404
+ const others = named.length ? named.filter((c) => c !== "none") : [DEFAULT_CC_COMPARE];
405
+ return [...new Set([model ?? DEFAULT_CC_MODEL, ...others])];
406
+ }
407
+ /** `context-doctor ab --via claude-code`: the exit code. */
408
+ export async function abClaudeCodeCommand(o) {
409
+ const say = (line) => (o.json ? console.error(line) : console.log(line));
410
+ if (process.platform === "win32") {
411
+ console.error("ab --via claude-code runs each task under Claude Code's sandbox, which Claude Code offers on macOS and Linux (WSL included), not on Windows. Nothing was run.");
412
+ return 1;
413
+ }
414
+ const models = modelsFor(o.model, o.compare);
415
+ const noPrice = models.find((m) => !exactClaudePricingFor(m));
416
+ if (noPrice) {
417
+ console.error(`No price is known for ${noPrice} itself, so ab cannot estimate the runs. Name a Claude model in the price table by its full id (e.g. ${DEFAULT_CC_MODEL}, ${DEFAULT_CC_COMPARE}), not an alias.`);
418
+ return 1;
419
+ }
420
+ if (o.out) {
421
+ const problem = outProblem(o.out);
422
+ if (problem) {
423
+ console.error(`${problem}. Nothing was run.`);
424
+ return 1;
425
+ }
426
+ }
427
+ const info = inspectClaudeCode();
428
+ if (info.problem) {
429
+ console.error(`${info.problem}. Install Claude Code, or point CONTEXT_DOCTOR_CLAUDE_BIN at it. Nothing was run.`);
430
+ return 1;
431
+ }
432
+ if (info.missing.length) {
433
+ console.error(`Claude Code ${info.version ?? ""} (${info.bin}) does not list ${info.missing.join(", ")} in --help: ab needs them to confine each run. Update Claude Code (2.1.311 or later). Nothing was run.`);
434
+ return 1;
435
+ }
436
+ if (!info.loggedIn) {
437
+ console.error(`Claude Code (${info.bin}) is not signed in: run \`claude\` and /login, then try again. Nothing was run.`);
438
+ return 1;
439
+ }
440
+ const repeat = o.repeat ?? 1;
441
+ const maxTurns = o.maxTurns ?? DEFAULT_CC_MAX_TURNS;
442
+ const timeoutS = o.timeoutS ?? DEFAULT_CC_TIMEOUT_S;
443
+ const ests = models.map((m) => estimateAb(o.tasks, ["arm"], repeat, exactClaudePricingFor(m), CC_SHAPE));
444
+ const expected = ests.reduce((s, e) => s + e.expectedUsd, 0);
445
+ const upper = ests.reduce((s, e) => s + e.upperUsd, 0);
446
+ const runs = o.tasks.length * models.length * repeat;
447
+ const plan = onPlan(info);
448
+ // On a plan the limits are the cap; on a key, as ab does on the Messages API: the upper estimate plus 25%.
449
+ const budget = o.budgetUsd ?? (plan ? undefined : Math.max(1, Math.ceil(upper * 1.25)));
450
+ say(`A/B quality suite through Claude Code: ${o.tasks.length} task${o.tasks.length === 1 ? "" : "s"} x ${models.length} model${models.length === 1 ? "" : "s"} (${models.join(", ")}) x ${repeat} = ${runs} runs`);
451
+ say(`Claude Code ${info.version ?? "(version unknown)"} (${info.bin}), ${whoPays(info)}.`);
452
+ if (plan) {
453
+ say(`At API list prices the runs come to ~${formatUsd(expected)} (up to ~${formatUsd(upper)} if nothing caches); Claude Code reports each run's own figure.`);
454
+ let share;
455
+ try {
456
+ const fit = claudeLimitFit(limitsReport(30, { claudeOnly: true }));
457
+ if (fit?.usable && fit.pctPerUsd !== undefined) {
458
+ const pct = fit.pctPerUsd * expected;
459
+ const round = (v) => (v >= 10 ? Math.round(v).toString() : v.toFixed(1));
460
+ share = fit.window === "seven_day" ? `≈ ${round(pct)}% of your weekly limit` : `≈ ${round(pct)}% of a 5-hour window`;
461
+ }
462
+ }
463
+ catch { /* no readings */ }
464
+ say(share ? `That is ${share}, from your limit readings (context-doctor limits).` : "What share of your limits that is cannot be said here yet: there are no fitted limit readings (context-doctor limits).");
465
+ }
466
+ else {
467
+ say(`Estimated cost: ~${formatUsd(expected)} with prompt caching, up to ~${formatUsd(upper)} if nothing caches.`);
468
+ }
469
+ if (budget !== undefined)
470
+ say(`No run starts once Claude Code's own costs reach ${formatUsd(budget)} (--budget); each gets its share as --max-budget-usd.`);
471
+ say(`Each run: a fresh temporary copy of the task's repository; Claude Code with its file tools confined to it, only \`node ${SMOKE}\` allowed in Bash, under Claude Code's sandbox (no writes outside the run folder and temp, no network); no MCP servers, plugins, hooks, settings files or CLAUDE.md; no session saved; up to ${maxTurns} turns and ${timeoutS} s.`);
472
+ if (!o.yes) {
473
+ say(`Nothing was run. Run again with --yes to start${plan ? " (it uses your plan's limits)" : budget !== undefined ? `, spending up to ${formatUsd(budget)}` : ""}.`);
474
+ return 0;
475
+ }
476
+ const result = await runClaudeCodeAb({
477
+ models,
478
+ tasks: o.tasks,
479
+ repeat,
480
+ maxTurns,
481
+ timeoutMs: timeoutS * 1000,
482
+ budgetUsd: budget,
483
+ concurrency: o.concurrency,
484
+ bin: info.bin,
485
+ onRun: (r, done, total) => console.error(`[${done}/${total}] ${r.task} · ${r.model} · ${STOPPED_EARLY.has(r.stop) ? `stopped (${r.stop})` : r.pass ? "PASS" : "FAIL"} · ${r.turns} turns · ${formatTokens(r.inputTokens + r.cacheReadTokens + r.cacheWriteTokens + r.outputTokens)} tokens · ${formatUsd(r.costUsd)}${r.error ? ` · ${r.error}` : ""}`),
486
+ }, info);
487
+ const json = JSON.stringify({ ...result, summary: modelTotals(result) }, null, 2);
488
+ if (o.out)
489
+ writeFileSync(o.out, json + "\n");
490
+ let stored;
491
+ if (!result.aborted && modelTotals(result).filter((t) => t.completed > 0).length >= 2) {
492
+ try {
493
+ storeAbResult(result);
494
+ stored = abResultsPath();
495
+ }
496
+ catch (e) {
497
+ console.error(`The result could not be kept for fix: ${e.message}`);
498
+ }
499
+ }
500
+ if (o.json)
501
+ console.log(json);
502
+ else
503
+ console.log("\n" + renderClaudeCodeAb(result) + (o.out ? `\n\nEvery run, as JSON: ${o.out}` : "") + (stored ? `\nKept for context-doctor fix (its subagent-model line quotes it): ${stored}` : ""));
504
+ if (result.aborted)
505
+ console.error(`Stopped: ${result.aborted}.`);
506
+ const dead = models.filter((m) => {
507
+ const rs = result.runs.filter((r) => r.model === m);
508
+ return rs.length > 0 && rs.every((r) => r.stop === "error");
509
+ });
510
+ return result.aborted || dead.length > 0 ? 1 : 0;
511
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The model comparisons `ab --via claude-code` finished, kept beside the
3
+ * other state files (~/.claude/.context-doctor-ab.json, or the fallback
4
+ * state folder), the newest 20. `fix` quotes the newest one that compared
5
+ * the subagent lever's model with another on its subagent-model line. Kept
6
+ * apart from abclaude.ts so `fix` reads it without loading the harness.
7
+ */
8
+ /** What is kept of a finished comparison: enough for `fix` to quote. */
9
+ export interface AbStoredResult {
10
+ at: string;
11
+ via: "claude-code";
12
+ claudeCodeVersion?: string;
13
+ authMethod?: string;
14
+ subscriptionType?: string;
15
+ repeat: number;
16
+ tasks: number;
17
+ models: Array<{
18
+ model: string;
19
+ passed: number;
20
+ completed: number;
21
+ runs: number;
22
+ costUsd: number;
23
+ }>;
24
+ }
25
+ export declare function abResultsPath(): string;
26
+ /** Whether Claude Code drew on a claude.ai plan's limits (true) or billed money (an API key, a console sign-in). */
27
+ export declare function onPlan(info: {
28
+ authMethod?: string;
29
+ }): boolean;
30
+ /** "Sonnet 5.5 passed 7/8, Opus 5.5 8/8": in the order given, over the completed runs. */
31
+ export declare function passLine(totals: Array<{
32
+ model: string;
33
+ passed: number;
34
+ completed: number;
35
+ }>): string;
36
+ /** The kept comparisons; an unreadable file reads as none. */
37
+ export declare function readAbResults(path?: string): AbStoredResult[];
38
+ /** Add one (the newest 20 are kept), written atomically. */
39
+ export declare function appendAbResult(entry: AbStoredResult, path?: string): void;
40
+ /**
41
+ * The newest kept comparison of `candidate` (the subagent lever's model)
42
+ * with another model, both with completed runs: what `fix` quotes.
43
+ */
44
+ export declare function latestModelComparison(candidate?: string, path?: string): AbStoredResult | undefined;
45
+ /** fix's words for a kept comparison: "on your plan: Sonnet 5.5 passed 7/8, Opus 5.5 8/8, 2026-11-14". */
46
+ export declare function comparisonLine(r: AbStoredResult, candidate?: string): string;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The model comparisons `ab --via claude-code` finished, kept beside the
3
+ * other state files (~/.claude/.context-doctor-ab.json, or the fallback
4
+ * state folder), the newest 20. `fix` quotes the newest one that compared
5
+ * the subagent lever's model with another on its subagent-model line. Kept
6
+ * apart from abclaude.ts so `fix` reads it without loading the harness.
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import { stateDir } from "./ledger.js";
11
+ import { SUBAGENT_CANDIDATE } from "./subagentpay.js";
12
+ import { modelName } from "./subagentmodel.js";
13
+ export function abResultsPath() {
14
+ return join(stateDir(), ".context-doctor-ab.json");
15
+ }
16
+ /** Whether Claude Code drew on a claude.ai plan's limits (true) or billed money (an API key, a console sign-in). */
17
+ export function onPlan(info) {
18
+ return info.authMethod === "claude.ai";
19
+ }
20
+ /** "Sonnet 5.5 passed 7/8, Opus 5.5 8/8": in the order given, over the completed runs. */
21
+ export function passLine(totals) {
22
+ return totals.map((t, i) => `${modelName(t.model)} ${i === 0 ? "passed " : ""}${t.passed}/${t.completed}`).join(", ");
23
+ }
24
+ /** The kept comparisons; an unreadable file reads as none. */
25
+ export function readAbResults(path = abResultsPath()) {
26
+ try {
27
+ const v = JSON.parse(readFileSync(path, "utf8"));
28
+ return Array.isArray(v?.results) ? v.results.filter((r) => r && typeof r.at === "string" && Array.isArray(r.models)) : [];
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ }
34
+ /** Add one (the newest 20 are kept), written atomically. */
35
+ export function appendAbResult(entry, path = abResultsPath()) {
36
+ const all = [...readAbResults(path), entry].slice(-20);
37
+ mkdirSync(dirname(path), { recursive: true });
38
+ const tmp = `${path}.${process.pid}.tmp`;
39
+ writeFileSync(tmp, JSON.stringify({ results: all }, null, 2) + "\n");
40
+ renameSync(tmp, path);
41
+ }
42
+ /**
43
+ * The newest kept comparison of `candidate` (the subagent lever's model)
44
+ * with another model, both with completed runs: what `fix` quotes.
45
+ */
46
+ export function latestModelComparison(candidate = SUBAGENT_CANDIDATE, path = abResultsPath()) {
47
+ if (!existsSync(path))
48
+ return undefined;
49
+ return readAbResults(path)
50
+ .filter((r) => r.models.some((m) => m.model === candidate && m.completed > 0) && r.models.some((m) => m.model !== candidate && m.completed > 0))
51
+ .sort((a, b) => Date.parse(a.at) - Date.parse(b.at))
52
+ .at(-1);
53
+ }
54
+ /** fix's words for a kept comparison: "on your plan: Sonnet 5.5 passed 7/8, Opus 5.5 8/8, 2026-11-14". */
55
+ export function comparisonLine(r, candidate = SUBAGENT_CANDIDATE) {
56
+ const ordered = [...r.models.filter((m) => m.model === candidate), ...r.models.filter((m) => m.model !== candidate && m.completed > 0)];
57
+ return `${onPlan(r) ? "on your plan" : "through your Claude Code"}: ${passLine(ordered)}, ${r.at.slice(0, 10)}`;
58
+ }
package/dist/budget.d.ts CHANGED
@@ -79,7 +79,10 @@ export declare function periodEnd(period: Period, now?: number): number;
79
79
  * under another table or other rates is read again. `c` is where reading a
80
80
  * Claude Code transcript's compactions stopped (compactcost.ts): each
81
81
  * compaction's own request is in `k`/`d` too, estimated, keyed by its
82
- * boundary's uuid.
82
+ * boundary's uuid. Each of `r` is a recent reply: its id, its index in
83
+ * k/d, the output counted, its output price, and what its iterations billed
84
+ * beyond its usage came to (billedCost's `extra`), so a later row that
85
+ * settles an advisor's call adds it once.
83
86
  */
84
87
  export interface FileEntry {
85
88
  t: Tool;
@@ -90,7 +93,7 @@ export interface FileEntry {
90
93
  d: number[];
91
94
  o?: number;
92
95
  a?: string;
93
- r?: Array<[string, number, number, number]>;
96
+ r?: Array<[string, number, number, number, number]>;
94
97
  x?: Array<[number, string]>;
95
98
  y?: Array<[number, string]>;
96
99
  z?: Array<[number, string, string]>;