context-doctor 0.46.0 → 0.48.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 (68) hide show
  1. package/README.md +9 -4
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +71 -28
  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/autopilot.js +9 -5
  9. package/dist/blob.js +66 -12
  10. package/dist/budget.d.ts +8 -2
  11. package/dist/budget.js +30 -7
  12. package/dist/ci.js +2 -1
  13. package/dist/claudeplugin.d.ts +97 -0
  14. package/dist/claudeplugin.js +142 -0
  15. package/dist/cli.js +128 -36
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/cursor.js +2 -0
  19. package/dist/doctor.js +90 -18
  20. package/dist/extract.js +4 -3
  21. package/dist/fanout.d.ts +15 -0
  22. package/dist/fanout.js +30 -9
  23. package/dist/firstfix.d.ts +43 -0
  24. package/dist/firstfix.js +80 -0
  25. package/dist/fix.d.ts +53 -4
  26. package/dist/fix.js +101 -13
  27. package/dist/httpguard.d.ts +13 -0
  28. package/dist/httpguard.js +22 -0
  29. package/dist/install.d.ts +21 -9
  30. package/dist/install.js +213 -40
  31. package/dist/limits.d.ts +5 -0
  32. package/dist/limits.js +26 -2
  33. package/dist/mcp.d.ts +4 -0
  34. package/dist/mcp.js +142 -97
  35. package/dist/mcpclient.js +73 -42
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +8 -2
  38. package/dist/mod/api.js +2 -2
  39. package/dist/mod/logic.d.ts +13 -1
  40. package/dist/mod/logic.js +24 -2
  41. package/dist/mod/register.d.ts +2 -0
  42. package/dist/mod/register.js +19 -5
  43. package/dist/modelids.d.ts +62 -3
  44. package/dist/modelids.js +156 -8
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.js +13 -1
  47. package/dist/orgrates.d.ts +18 -0
  48. package/dist/orgrates.js +51 -2
  49. package/dist/pack.d.ts +13 -0
  50. package/dist/pack.js +38 -2
  51. package/dist/preferences.js +2 -1
  52. package/dist/pricing.d.ts +8 -0
  53. package/dist/pricing.js +30 -2
  54. package/dist/progresssummaries.d.ts +148 -0
  55. package/dist/progresssummaries.js +248 -0
  56. package/dist/proxy.d.ts +1 -1
  57. package/dist/proxy.js +1 -1
  58. package/dist/prune.d.ts +8 -0
  59. package/dist/prune.js +11 -1
  60. package/dist/spend.d.ts +34 -0
  61. package/dist/spend.js +48 -4
  62. package/dist/subagentmodel.d.ts +12 -0
  63. package/dist/subagentmodel.js +17 -4
  64. package/dist/subagentpay.d.ts +8 -0
  65. package/dist/subagentpay.js +8 -1
  66. package/dist/toolcwd.d.ts +14 -0
  67. package/dist/toolcwd.js +17 -0
  68. package/package.json +6 -3
package/README.md CHANGED
@@ -18,6 +18,8 @@ npx context-doctor spend # one bill across Claude Code, Codex, Gemini CLI
18
18
 
19
19
  ## Quick start
20
20
 
21
+ **See it first, nothing installed:** in a terminal, `npx context-doctor` reads your last 30 days of Claude Code sessions on this machine and shows what the fixes with no quality cost would have saved, as one total, then asks once: `y` applies them all, `npx context-doctor fix undo` puts them back. The fixes that trade something (compacting earlier, the subagents' model) are listed with their dollars and the command for each.
22
+
21
23
  Pick where you work. Each takes about a minute and is fully reversible.
22
24
 
23
25
  | You use | Do this |
@@ -28,7 +30,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
28
30
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
29
31
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
30
32
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
31
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.46.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
33
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.48.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
34
 
33
35
  ## What it does
34
36
 
@@ -137,7 +139,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
137
139
  | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
138
140
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
139
141
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
140
- | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows the same |
142
+ | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows `fix`'s plan instead, with one question for the fixes that cost nothing in quality |
141
143
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse ([details](./docs/autopilot.md)) |
142
144
  | `context-doctor proxy --autopilot` | Local proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain `proxy` runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. `--token` for a public URL; `/stats` for cumulative savings ([details](./docs/proxy.md)) |
143
145
  | `context-doctor compact-window [status\|off\|<size>]` | Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. `400k` (or `250000`, `0.4m`) sets Claude Code's `autoCompactWindow`, with a backup; `off` removes it. Works in every Claude Code surface, the desktop app included |
@@ -181,7 +183,9 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
181
183
 
182
184
  ## What's new
183
185
 
184
- - **0.46 Fable 5.2, the Desktop app, and an audit**: Claude Fable 5.2 is priced (0.45 read it 1.5x too high); managed `modelPricing` is honoured; a check catches new models without a price. The plugin's new mod brings limit readings, Claude Code's own cost, a cache-expiry band with **Compact first**, and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app and VS Code ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
186
+ - **0.48 Directory-ready, quality on your own plan, and MCP SDK v2**: a build of the plugin for Anthropic's directory (strict-clean, with and without the mod); `ab --via claude-code` measures the subagent lever on your own sign-in, no API key; the price check covers OpenAI, Google, Codex and Gemini CLI and warns before a price ends; the MCP server speaks protocol 2026-07-28 to Claude Code and the old handshake to everyone else. Fixed: installing the plugin from the marketplace no longer pulls 80 MB of build tools into Claude Code's cache ([details](./ROADMAP.md#shipped-in-0480-a-directory-ready-plugin-quality-on-your-own-plan-prices-that-change-under-us-and-mcp-sdk-v2)).
187
+ - **0.47 One keystroke to a saving, the mod through `install`, a weekly live check, and an audit of 0.46**: a bare `context-doctor` in a terminal shows the fixes that cost no quality as one monthly total and asks once (the author's: $469 a month: long Bash output to a file, the 1-hour cache). On Claude Code 2.1.286+, `install` enables the plugin, so npm users get the mod too (limit readings and Claude Code's own cost after each turn, Compact first, `/context-doctor-fix`). A weekly canary runs the plugin and mod in the newest Claude Code against a local mock API. `spend` estimates compaction requests and, for terminal sessions, subagent progress summaries, and `fix` can switch the summaries off. An audit fixed, among others, the GitHub Action's YAML (it could not load), programs planted in a cloned repository running on Windows, `pack_context` opening network shares, a re-pricing gap after upgrades, and a test that would have failed from 2026-12-16 ([details](./ROADMAP.md#shipped-in-0470-one-keystroke-the-mod-through-install-a-weekly-live-check-and-an-audit-of-046)).
188
+ - **0.46 Fable 5.2, the Desktop app, and an audit**: Claude Fable 5.2 is priced (0.45 read it 1.5x too high); managed `modelPricing` is honoured; a check catches new models without a price. The plugin's new mod brings limit readings, Claude Code's own cost and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app, VS Code and the terminal, and a cache-expiry band with **Compact first** to the Desktop app and the terminal (Claude Code draws a mod's band on no other surface) ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
185
189
  - **0.45 Price what is billed, and a security pass**: fast mode, US-only inference, Haiku 5.5's long-prompt rates, web searches and OpenAI's and Gemini's long-prompt tiers are priced per request in every report, and prices that end on a known day say so. A security pass fixed a cloned repository approving its own MCP servers for `overhead --mcp`, a PDF's name running as a command through `pack` on macOS, the agents' API-key configs being packed, and the proxy answering a DNS-rebinding page ([details](./ROADMAP.md#shipped-in-0450-price-what-is-billed-and-a-security-pass-on-044)).
186
190
  - **0.44 Workflow agents on the bill, current prices, and an audit**: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542. `spend`, the budget, a session's price, `subagents` and `fix` now count them, and `spend` equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed `overhead --mcp` launching a cloned repository's unapproved MCP servers, `pack_context` returning the agents' sign-in files, and more ([details](./ROADMAP.md#shipped-in-0440-workflow-agents-on-the-bill-current-prices-and-an-audit-of-043)).
187
191
  - **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
@@ -208,7 +212,8 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
208
212
  - [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
209
213
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
210
214
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
211
- - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, the cache band with Compact first, and `/context-doctor-fix`
215
+ - [Privacy](./docs/privacy.md) and [the directory submission](./docs/directory-submission.md): what the plugin reads, writes and sends; the package for Anthropic's plugin directory
216
+ - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost and `/context-doctor-fix` (Desktop app, VS Code, terminal), and the cache band with Compact first (Desktop app and terminal only)
212
217
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
213
218
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
214
219
  - [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
package/dist/ab.d.ts CHANGED
@@ -35,6 +35,7 @@
35
35
  * fetch (this package has no runtime dependencies), and tests plug in a
36
36
  * local mock server through ANTHROPIC_BASE_URL.
37
37
  */
38
+ import { type ChildProcess } from "node:child_process";
38
39
  import { type AbTask } from "./abtasks.js";
39
40
  import { type ModelPricing, type RecordedUsage } from "./pricing.js";
40
41
  export declare const AB_LEVERS: readonly ["rules", "autoclear", "pack", "compact"];
@@ -43,6 +44,8 @@ export type AbArm = "none" | "rules" | "autoclear" | "pack" | "compact-generic"
43
44
  export declare const DEFAULT_AB_MODEL = "claude-opus-5-5";
44
45
  /** The Messages API version the harness sends (sampling parameters are not sent). */
45
46
  export declare const AB_API_VERSION = "2026-10-21";
47
+ /** A smoke test or hidden check that runs longer is killed (and fails). */
48
+ export declare const CHECK_TIMEOUT_MS = 30000;
46
49
  export interface AbContentBlock {
47
50
  type: string;
48
51
  id?: string;
@@ -76,6 +79,29 @@ export declare function anthropicProvider(options: {
76
79
  retries?: number;
77
80
  timeoutMs?: number;
78
81
  }): AbProvider;
82
+ /** Children in flight and run folders on disk, for Ctrl-C. */
83
+ export interface Live {
84
+ children: Set<ChildProcess>;
85
+ roots: Set<string>;
86
+ /** A smoke test or hidden check running longer is killed. */
87
+ timeoutMs: number;
88
+ /** Ctrl-C is being handled: nothing new starts and no run finishes (stopOnSignal). */
89
+ stopping?: boolean;
90
+ }
91
+ /** Kill a child and everything in its process group (the child leads one). */
92
+ export declare function killTree(child: ChildProcess): void;
93
+ /**
94
+ * Ctrl-C (or SIGTERM): kill every child with its process group, wait until
95
+ * each child has exited and this process has reaped it (at most 5 s), then
96
+ * remove every run folder and exit 130 (143). Waiting is what makes "killed"
97
+ * true at exit: a SIGKILL is only sent, and a process exiting right after it
98
+ * left a child still dying, or a zombie, behind it for a moment (Linux, Node
99
+ * 22 and 24). While it waits, live.stopping holds every run where it is: no
100
+ * process is started and no run finishes, so the suite never goes on to
101
+ * print or keep a result. Returns what removes the handlers.
102
+ */
103
+ export declare function stopOnSignal(live: Live): () => void;
104
+ export declare function removeRoot(root: string, live: Live): void;
79
105
  export interface AbRun {
80
106
  task: string;
81
107
  arm: AbArm;
@@ -97,7 +123,7 @@ export interface AbRun {
97
123
  /** autoclear: tokens it kept off the wire, over all requests. */
98
124
  leverTokens: number;
99
125
  }
100
- /** Ends that say nothing about the lever: the API failed or declined, or the harness's own caps cut the run. */
126
+ /** Ends that say nothing about the lever: the API failed or declined, the harness's own caps cut the run, or (through Claude Code) the plan's usage limit or the run's time limit stopped it. */
101
127
  export declare const STOPPED_EARLY: Set<string>;
102
128
  export interface AbOptions {
103
129
  provider: AbProvider;
@@ -118,6 +144,16 @@ export interface AbOptions {
118
144
  /** Called as each run finishes. */
119
145
  onRun?: (run: AbRun, done: number, total: number) => void;
120
146
  }
147
+ export interface RunPaths {
148
+ root: string;
149
+ repo: string;
150
+ home: string;
151
+ }
152
+ export declare function taskPrompt(task: AbTask): string;
153
+ /** The hidden check: written outside the repository, run with it as the working directory. */
154
+ export declare function verifyRun(task: AbTask, run: RunPaths, live: Live): Promise<boolean>;
155
+ /** A fresh run folder: the repository, and a home for the code it runs. */
156
+ export declare function makeRun(task: AbTask, live: Live): RunPaths;
121
157
  /**
122
158
  * The verdict on files as they stand, for the tests and the self-check:
123
159
  * a fresh run folder with `files`, the hidden check, everything removed.
@@ -135,9 +171,13 @@ export interface AbEstimate {
135
171
  /**
136
172
  * A planning figure, not a quote: six requests a run, the task's files in
137
173
  * context from the second request on, ~800 output tokens a request (thinking,
138
- * tool calls, the files the agent writes).
174
+ * tool calls, the files the agent writes). `shape` changes the request count
175
+ * and the fixed prompt (Claude Code's own system prompt and tools).
139
176
  */
140
- export declare function estimateAb(tasks: AbTask[], arms: AbArm[], repeat: number, pricing: ModelPricing): AbEstimate;
177
+ export declare function estimateAb(tasks: AbTask[], arms: readonly string[], repeat: number, pricing: ModelPricing, shape?: {
178
+ requests?: number;
179
+ baseTokens?: number;
180
+ }): AbEstimate;
141
181
  export interface AbResult {
142
182
  model: string;
143
183
  provider: string;
@@ -180,7 +220,15 @@ export interface AbCommandOptions {
180
220
  json: boolean;
181
221
  out?: string;
182
222
  list: boolean;
223
+ /** "api" (the Messages API, the default) or "claude-code" (`claude -p` on the person's own sign-in, one arm per model). */
224
+ via?: string;
225
+ /** --via claude-code: the models compared with --model. */
226
+ compare?: string[];
227
+ /** --via claude-code: seconds before a run is killed. */
228
+ timeoutS?: number;
183
229
  }
230
+ /** Why `--out` cannot be written, checked before anything is spent; undefined when it can. */
231
+ export declare function outProblem(out: string): string | undefined;
184
232
  /**
185
233
  * `context-doctor ab`: the exit code. 1 for a refusal, a bad argument, a key
186
234
  * the API refused, or an arm all of whose runs ended on an API error.
package/dist/ab.js CHANGED
@@ -36,6 +36,7 @@
36
36
  * local mock server through ANTHROPIC_BASE_URL.
37
37
  */
38
38
  import { spawn, spawnSync } from "node:child_process";
39
+ import { toolCwd } from "./toolcwd.js";
39
40
  import { randomBytes } from "node:crypto";
40
41
  import { accessSync, chmodSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
41
42
  import { tmpdir } from "node:os";
@@ -55,7 +56,7 @@ export const AB_API_VERSION = "2026-10-21";
55
56
  /** Output cap per request; also the output side of each request's worst case for the budget. */
56
57
  const MAX_TOKENS = 16000;
57
58
  /** A smoke test or hidden check that runs longer is killed (and fails). */
58
- const CHECK_TIMEOUT_MS = 30_000;
59
+ export const CHECK_TIMEOUT_MS = 30_000;
59
60
  /** What each lever is compared against, and what it is. */
60
61
  const LEVER_INFO = {
61
62
  rules: { base: "none", arm: "rules", what: "the standing context rules in the system prompt (what MCP clients and the Copilot hook add)" },
@@ -134,11 +135,11 @@ function minimalEnv(home) {
134
135
  return env;
135
136
  }
136
137
  /** Kill a child and everything in its process group (the child leads one). */
137
- function killTree(child) {
138
+ export function killTree(child) {
138
139
  if (child.pid === undefined)
139
140
  return;
140
141
  if (process.platform === "win32") {
141
- spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
142
+ spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { cwd: toolCwd(), stdio: "ignore", windowsHide: true });
142
143
  return;
143
144
  }
144
145
  try {
@@ -172,7 +173,7 @@ function killLeftovers(root) {
172
173
  else {
173
174
  // lsof walks every process's open files: ~0.5 s here, several on a loaded machine. Cut off
174
175
  // early, it found nothing and the leftover lived on, so it gets time.
175
- const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 30_000 });
176
+ const r = spawnSync("lsof", ["-t", "+D", root], { cwd: toolCwd(), encoding: "utf8", timeout: 30_000 });
176
177
  for (const line of (r.stdout ?? "").split("\n"))
177
178
  if (/^\d+$/.test(line.trim()))
178
179
  pids.add(Number(line.trim()));
@@ -206,7 +207,37 @@ function makeWritable(path) {
206
207
  for (const name of readdirSync(path))
207
208
  makeWritable(join(path, name));
208
209
  }
209
- function removeRoot(root, live) {
210
+ /**
211
+ * Ctrl-C (or SIGTERM): kill every child with its process group, wait until
212
+ * each child has exited and this process has reaped it (at most 5 s), then
213
+ * remove every run folder and exit 130 (143). Waiting is what makes "killed"
214
+ * true at exit: a SIGKILL is only sent, and a process exiting right after it
215
+ * left a child still dying, or a zombie, behind it for a moment (Linux, Node
216
+ * 22 and 24). While it waits, live.stopping holds every run where it is: no
217
+ * process is started and no run finishes, so the suite never goes on to
218
+ * print or keep a result. Returns what removes the handlers.
219
+ */
220
+ export function stopOnSignal(live) {
221
+ const stop = async (signal) => {
222
+ live.stopping = true;
223
+ const children = [...live.children];
224
+ const exited = children.map((c) => (c.exitCode === null && c.signalCode === null ? new Promise((res) => c.once("exit", () => res())) : undefined));
225
+ for (const c of children)
226
+ killTree(c);
227
+ await Promise.race([Promise.all(exited), new Promise((res) => setTimeout(res, 5000))]);
228
+ for (const root of [...live.roots])
229
+ removeRoot(root, live);
230
+ process.exit(signal === "SIGINT" ? 130 : 143);
231
+ };
232
+ const handler = (signal) => void stop(signal);
233
+ process.once("SIGINT", handler);
234
+ process.once("SIGTERM", handler);
235
+ return () => {
236
+ process.off("SIGINT", handler);
237
+ process.off("SIGTERM", handler);
238
+ };
239
+ }
240
+ export function removeRoot(root, live) {
210
241
  killLeftovers(root);
211
242
  makeWritable(root);
212
243
  try {
@@ -224,6 +255,8 @@ function removeRoot(root, live) {
224
255
  function runNode(args, cwd, home, live) {
225
256
  const timeoutMs = live.timeoutMs;
226
257
  return new Promise((resolveRun) => {
258
+ if (live.stopping)
259
+ return; // Ctrl-C: held until the exit
227
260
  let tail = "";
228
261
  let timedOut = false;
229
262
  const child = spawn(process.execPath, args, { cwd, env: minimalEnv(home), stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
@@ -239,7 +272,7 @@ function runNode(args, cwd, home, live) {
239
272
  }, timeoutMs);
240
273
  let finished = false;
241
274
  const finish = (code) => {
242
- if (finished)
275
+ if (finished || live.stopping)
243
276
  return;
244
277
  finished = true;
245
278
  clearTimeout(timer);
@@ -388,8 +421,8 @@ async function execute(block, run, task, allowPack, counts, live) {
388
421
  return fail(e.message);
389
422
  }
390
423
  }
391
- /** Ends that say nothing about the lever: the API failed or declined, or the harness's own caps cut the run. */
392
- export const STOPPED_EARLY = new Set(["error", "budget", "turns", "refusal", "max_tokens"]);
424
+ /** Ends that say nothing about the lever: the API failed or declined, the harness's own caps cut the run, or (through Claude Code) the plan's usage limit or the run's time limit stopped it. */
425
+ export const STOPPED_EARLY = new Set(["error", "budget", "turns", "refusal", "max_tokens", "limit", "timeout"]);
393
426
  /** Autopilot with every request as if after an idle gap: clearing is allowed on each one. */
394
427
  class ColdEveryRequest extends AutoClearer {
395
428
  clock = 0;
@@ -415,7 +448,7 @@ function asTranscript(messages) {
415
448
  : { type: "user", message: { role: "user", content: m.content } }))
416
449
  .join("\n") + "\n";
417
450
  }
418
- function taskPrompt(task) {
451
+ export function taskPrompt(task) {
419
452
  const list = Object.keys(task.files)
420
453
  .sort()
421
454
  .map((p) => `- ${p} (${(Buffer.byteLength(task.files[p]) / 1024).toFixed(1)} KB)`)
@@ -435,7 +468,7 @@ function worstCaseUsd(body, pricing) {
435
468
  return (prompt * pricing.inputPerM * CACHE_WRITE_5M + MAX_TOKENS * pricing.outputPerM) / 1e6;
436
469
  }
437
470
  /** The hidden check: written outside the repository, run with it as the working directory. */
438
- async function verifyRun(task, run, live) {
471
+ export async function verifyRun(task, run, live) {
439
472
  try {
440
473
  makeWritable(run.root); // the agent's code may have locked its folders
441
474
  const script = join(run.root, "verify.mjs");
@@ -450,7 +483,7 @@ async function verifyRun(task, run, live) {
450
483
  }
451
484
  }
452
485
  /** A fresh run folder: the repository, and a home for the code it runs. */
453
- function makeRun(task, live) {
486
+ export function makeRun(task, live) {
454
487
  const root = mkdtempSync(join(tmpdir(), `ctxdoc-ab-${task.id}-`));
455
488
  live.roots.add(root);
456
489
  const repo = join(root, "repo");
@@ -594,12 +627,13 @@ export function armsFor(levers) {
594
627
  /**
595
628
  * A planning figure, not a quote: six requests a run, the task's files in
596
629
  * context from the second request on, ~800 output tokens a request (thinking,
597
- * tool calls, the files the agent writes).
630
+ * tool calls, the files the agent writes). `shape` changes the request count
631
+ * and the fixed prompt (Claude Code's own system prompt and tools).
598
632
  */
599
- export function estimateAb(tasks, arms, repeat, pricing) {
600
- const R = 6;
633
+ export function estimateAb(tasks, arms, repeat, pricing, shape = {}) {
634
+ const R = shape.requests ?? 6;
601
635
  const OUT = 800;
602
- const base = estimateTokens(BASE_SYSTEM + SERVER_INSTRUCTIONS + JSON.stringify([...BASE_TOOLS, PACK_TOOL]), "claude");
636
+ const base = shape.baseTokens ?? estimateTokens(BASE_SYSTEM + SERVER_INSTRUCTIONS + JSON.stringify([...BASE_TOOLS, PACK_TOOL]), "claude");
603
637
  let expected = 0;
604
638
  let upper = 0;
605
639
  for (const task of tasks) {
@@ -637,15 +671,7 @@ export async function runAbSuite(options) {
637
671
  live: { children: new Set(), roots: new Set(), timeoutMs: options.checkTimeoutMs ?? CHECK_TIMEOUT_MS },
638
672
  };
639
673
  // Ctrl-C: nothing of the agent's keeps running, no run folder stays behind.
640
- const interrupt = (signal) => {
641
- for (const child of ctx.live.children)
642
- killTree(child);
643
- for (const root of [...ctx.live.roots])
644
- removeRoot(root, ctx.live);
645
- process.exit(signal === "SIGINT" ? 130 : 143);
646
- };
647
- process.once("SIGINT", interrupt);
648
- process.once("SIGTERM", interrupt);
674
+ const unhook = stopOnSignal(ctx.live);
649
675
  const queue = [];
650
676
  for (let rep = 1; rep <= repeat; rep++)
651
677
  for (const task of tasks)
@@ -654,7 +680,7 @@ export async function runAbSuite(options) {
654
680
  const runs = [];
655
681
  let next = 0;
656
682
  const worker = async () => {
657
- while (next < queue.length && !ctx.fatal) {
683
+ while (next < queue.length && !ctx.fatal && !ctx.live.stopping) {
658
684
  const { task, arm, rep } = queue[next++];
659
685
  const run = await runOne(task, arm, rep, ctx);
660
686
  runs.push(run);
@@ -665,8 +691,7 @@ export async function runAbSuite(options) {
665
691
  await Promise.all(Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, worker));
666
692
  }
667
693
  finally {
668
- process.off("SIGINT", interrupt);
669
- process.off("SIGTERM", interrupt);
694
+ unhook();
670
695
  }
671
696
  const order = (r) => queue.findIndex((q) => q.task.id === r.task && q.arm === r.arm && q.rep === r.rep);
672
697
  runs.sort((a, b) => order(a) - order(b));
@@ -754,7 +779,7 @@ export function renderAb(result) {
754
779
  return out.join("\n");
755
780
  }
756
781
  /** Why `--out` cannot be written, checked before anything is spent; undefined when it can. */
757
- function outProblem(out) {
782
+ export function outProblem(out) {
758
783
  const path = resolve(out);
759
784
  try {
760
785
  if (statSync(path).isDirectory())
@@ -791,7 +816,20 @@ export async function abCommand(o) {
791
816
  console.log(` ${l.padEnd(10)} ${LEVER_INFO[l].what}`);
792
817
  return 0;
793
818
  }
819
+ const via = (o.via ?? "api").trim().toLowerCase();
820
+ if (via !== "api" && via !== "claude-code") {
821
+ console.error(`Unknown --via "${o.via}": api (the Messages API, on ANTHROPIC_API_KEY) or claude-code (claude -p, on your own Claude Code sign-in).`);
822
+ return 1;
823
+ }
794
824
  const leverNames = (o.levers ?? []).flatMap((l) => l.split(",")).map((l) => l.trim()).filter(Boolean);
825
+ if (via === "claude-code" && leverNames.length) {
826
+ console.error("--lever arms run through the Messages API harness; --via claude-code compares models instead (--model, --compare). Nothing was run.");
827
+ return 1;
828
+ }
829
+ if (via === "api" && (o.compare?.length || o.timeoutS !== undefined)) {
830
+ console.error(`${o.compare?.length ? "--compare" : "--timeout"} is for --via claude-code (models compared through your own Claude Code). Nothing was sent.`);
831
+ return 1;
832
+ }
795
833
  const unknownLever = leverNames.find((l) => l !== "all" && !AB_LEVERS.includes(l));
796
834
  if (unknownLever) {
797
835
  console.error(`Unknown lever "${unknownLever}". Levers: ${AB_LEVERS.join(", ")}, or all.`);
@@ -805,6 +843,11 @@ export async function abCommand(o) {
805
843
  return 1;
806
844
  }
807
845
  const tasks = taskIds.length ? AB_TASKS.filter((t) => taskIds.includes(t.id)) : AB_TASKS;
846
+ if (via === "claude-code") {
847
+ // Loaded here: abclaude.ts builds on this module.
848
+ const { abClaudeCodeCommand } = await import("./abclaude.js");
849
+ return abClaudeCodeCommand({ model: o.model, compare: o.compare, tasks, repeat: o.repeat, maxTurns: o.maxTurns, timeoutS: o.timeoutS, concurrency: o.concurrency, budgetUsd: o.budgetUsd, yes: o.yes, json: o.json, out: o.out });
850
+ }
808
851
  const model = o.model ?? DEFAULT_AB_MODEL;
809
852
  const pricing = exactClaudePricingFor(model);
810
853
  if (!pricing) {
@@ -0,0 +1,167 @@
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 { type AbTask } from "./abtasks.js";
54
+ import { type AbStoredResult } from "./abstore.js";
55
+ /** The arms when none are named: the subagent lever's question. */
56
+ export declare const DEFAULT_CC_MODEL = "claude-sonnet-5-5";
57
+ export declare const DEFAULT_CC_COMPARE = "claude-opus-5-5";
58
+ /** Claude Code turns a run may take (it reads, edits and runs the check one tool at a time). */
59
+ export declare const DEFAULT_CC_MAX_TURNS = 30;
60
+ /** A run still going after this long is killed. */
61
+ export declare const DEFAULT_CC_TIMEOUT_S = 600;
62
+ /** The flags ab needs, as `claude --help` lists them (--max-turns is accepted but not listed). */
63
+ export declare const REQUIRED_FLAGS: string[];
64
+ /** The arguments of one run's `claude -p` (the prompt goes on stdin). */
65
+ export declare function claudeArgs(model: string, maxTurns: number, maxBudgetUsd?: number): string[];
66
+ export declare function claudeCodePrompt(task: AbTask): string;
67
+ /** The Claude Code ab runs: CONTEXT_DOCTOR_CLAUDE_BIN, else `claude` on PATH. */
68
+ export declare function claudeBin(): string;
69
+ export interface ClaudeCodeInfo {
70
+ bin: string;
71
+ version?: string;
72
+ /** Flags ab needs that this Claude Code does not list. */
73
+ missing: string[];
74
+ loggedIn: boolean;
75
+ /** `claude auth status`: claude.ai, api_key, oauth_token, ... */
76
+ authMethod?: string;
77
+ subscriptionType?: string;
78
+ apiKeySource?: string;
79
+ /** Why it cannot be used at all (not found, not runnable). */
80
+ problem?: string;
81
+ }
82
+ /** `claude --version`, `--help` and `auth status --json`: all local, nothing sent to a model. */
83
+ export declare function inspectClaudeCode(bin?: string): ClaudeCodeInfo;
84
+ export interface AbModelRun {
85
+ task: string;
86
+ model: string;
87
+ rep: number;
88
+ /** The hidden check, run by the harness after Claude Code stopped. */
89
+ pass: boolean;
90
+ /** end_turn, turns (--max-turns), budget, limit (the plan's usage limit), timeout, or error. */
91
+ stop: string;
92
+ error?: string;
93
+ /** Claude Code's num_turns. */
94
+ turns: number;
95
+ inputTokens: number;
96
+ cacheReadTokens: number;
97
+ cacheWriteTokens: number;
98
+ outputTokens: number;
99
+ /** Claude Code's total_cost_usd: on a plan, what the run would cost at list prices. */
100
+ costUsd: number;
101
+ wallMs: number;
102
+ /** Tool calls Claude Code's permissions refused (outside the folder, the smoke test, other commands). */
103
+ denied: number;
104
+ }
105
+ export interface AbModelOptions {
106
+ models: string[];
107
+ tasks?: AbTask[];
108
+ repeat?: number;
109
+ maxTurns?: number;
110
+ /** Per run, ms. */
111
+ timeoutMs?: number;
112
+ /** No run starts once Claude Code's own costs reach this (each run gets its share as --max-budget-usd). */
113
+ budgetUsd?: number;
114
+ concurrency?: number;
115
+ bin?: string;
116
+ onRun?: (run: AbModelRun, done: number, total: number) => void;
117
+ }
118
+ export interface AbModelResult {
119
+ via: "claude-code";
120
+ /** ISO time the suite finished. */
121
+ at: string;
122
+ claudeCode: {
123
+ version?: string;
124
+ authMethod?: string;
125
+ subscriptionType?: string;
126
+ };
127
+ models: string[];
128
+ tasks: string[];
129
+ repeat: number;
130
+ runs: AbModelRun[];
131
+ /** Claude Code's own total_cost_usd, summed: on a plan, list-price equivalent. */
132
+ costUsd: number;
133
+ /** Why the suite stopped before every run (a usage limit, a refused sign-in, Claude Code not starting). */
134
+ aborted?: string;
135
+ }
136
+ export declare function runClaudeCodeAb(options: AbModelOptions, info?: Pick<ClaudeCodeInfo, "version" | "authMethod" | "subscriptionType">): Promise<AbModelResult>;
137
+ export interface ModelTotals {
138
+ model: string;
139
+ runs: number;
140
+ /** Runs that ended on their own: the ones a pass rate is about. */
141
+ completed: number;
142
+ passed: number;
143
+ stoppedEarly: number;
144
+ tokens: number;
145
+ costUsd: number;
146
+ }
147
+ export declare function modelTotals(result: Pick<AbModelResult, "models" | "runs">): ModelTotals[];
148
+ export declare function renderClaudeCodeAb(result: AbModelResult): string;
149
+ /** Keep a finished comparison for fix (the newest 20). */
150
+ export declare function storeAbResult(result: AbModelResult, path?: string): AbStoredResult;
151
+ export interface AbClaudeCodeCommandOptions {
152
+ model?: string;
153
+ compare?: string[];
154
+ tasks: AbTask[];
155
+ repeat?: number;
156
+ maxTurns?: number;
157
+ timeoutS?: number;
158
+ concurrency?: number;
159
+ budgetUsd?: number;
160
+ yes: boolean;
161
+ json: boolean;
162
+ out?: string;
163
+ }
164
+ /** The arms: --model (default Sonnet 5.5), then each --compare (default Opus 5.5; "none" for none). */
165
+ export declare function modelsFor(model: string | undefined, compare: string[] | undefined): string[];
166
+ /** `context-doctor ab --via claude-code`: the exit code. */
167
+ export declare function abClaudeCodeCommand(o: AbClaudeCodeCommandOptions): Promise<number>;