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
package/README.md CHANGED
@@ -9,7 +9,7 @@ AI agents re-send their whole context on every message: old tool output, pasted
9
9
  ```bash
10
10
  npx context-doctor savings # what your recent sessions cost, and what each fix would have saved
11
11
  npx context-doctor fix # the fixes ranked by dollars; applies only the ones you say yes to
12
- npx context-doctor spend # one bill across Claude Code, Codex, Gemini CLI and Cursor
12
+ npx context-doctor spend # one bill across Claude Code, Codex, Gemini CLI, Cursor, Copilot CLI, OpenCode and Cline
13
13
  ```
14
14
 
15
15
  <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
@@ -30,17 +30,17 @@ Pick where you work. Each takes about a minute and is fully reversible.
30
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)) |
31
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)) |
32
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) |
33
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.47.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.49.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
34
34
 
35
35
  ## What it does
36
36
 
37
37
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
38
- - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, as billed at list rates ([spend and budget](./docs/spend.md)).
38
+ - `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI, Cursor, Copilot CLI, OpenCode and Cline, by tool, project, model and day, as billed at list rates ([spend and budget](./docs/spend.md)).
39
39
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
40
40
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
41
41
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
42
- - `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one.
43
- - `limits`: your plan's 5-hour and weekly windows (Claude Pro/Max, recorded by the status line) and Codex's, the pace and when each runs out, and what 1M tokens of each kind cost in % of the limit, fitted on your own readings with the error shown.
42
+ - `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one. And the cold returns (back after the cache expired): each one as billed, compacted on return, and kept warm by a cache read every 55 minutes, by how long you were away; what keeping warm for up to 1-8 hours would have netted; and a compacted segment the Desktop app put back ([#107157](https://github.com/anthropics/claude-code/issues/107157)).
43
+ - `limits`: your plan's weekly and 5-hour windows (Claude Pro, Max and Ultra, which has no 5-hour window; recorded by the plugin's mod, the status line or the proxy) and Codex's, the pace and when each runs out, what 1M tokens of each kind cost in % of the limit, and for each weekly window the API-equivalent dollars and tokens per 1%, by entrypoint and model, with every move in that figure dated. `limits --report` prints it as a block to paste into a bug report, with no prompts, paths or ids.
44
44
  - `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
45
45
  - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
46
46
 
@@ -107,7 +107,7 @@ On a Claude subscription you do not pay list price; the same tokens come out of
107
107
  | Where you work | Automatic, every request | What you get on top |
108
108
  |---|---|---|
109
109
  | **Claude Code** in the terminal, VS Code or JetBrains | **Autopilot** clears stale tool output (cold cache only, never more expensive). **Hook** on every prompt: real context size, largest waste, and a `/compact` offer when you return to a large session after the cache expired. **Compaction hook** on every compaction. **`compact-window`**, if you set one | Install via npm or as a **plugin**. Status bar context meter, `/context-doctor:savings`, `session`, `watch`, `report`, dashboard, MCP tools |
110
- | **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above |
110
+ | **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above, and the plugin's mod: `/context-doctor-usage`, the usage view the app dropped (context ring, limit windows, tokens and dollars by model for today, 7 and 30 days, running subagents), and `/context-doctor-fix` ([Desktop](./docs/desktop.md)) |
111
111
  | **Cursor** (agent) | A native **after-tool-call hook** (`~/.cursor/hooks.json`): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model) | MCP tools, editor status bar extension, `cursor` profiler. With your own OpenAI key, autopilot too via a tokened tunnel ([how](./docs/proxy.md#putting-the-proxy-on-a-public-url-cursor-with-your-own-openai-key-remote-apps)) |
112
112
  | **Codex** (ChatGPT app's Codex tab, IDE extension, CLI) | Every-prompt hook with the API's own token counts | MCP tools, skill, `session` reads Codex rollouts. On an API key, autopilot too (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
113
113
  | **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL` set to the proxy on `127.0.0.1:8787`, plain HTTP (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
@@ -135,8 +135,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
135
135
  | Command | What it does |
136
136
  |---|---|
137
137
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
138
- | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
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
+ | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, MCP servers set to load up front, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
139
+ | `context-doctor spend [--days n] [--by repo\|branch] [--share] [--export]`, `spend merge <folder>` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI, Cursor (an estimate: no cache split), Copilot CLI (with the AI credits it counted), OpenCode and Cline, by tool, project (or repository or branch), model and day; `--export` writes a file of totals (no prompt or path) and `spend merge` adds up a team's files, with a month-end forecast, with what drives it, and Claude Code's own figure (its `cost-state`) beside ours with what the gap is made of ([docs](./docs/spend.md)) |
140
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)) |
141
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 |
142
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 |
@@ -148,23 +148,23 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
148
148
  | `context-doctor handoff [list\|show <id>\|latest] [--copy]` | Handoffs saved from chat apps (the `handoff` prompt or `save_handoff`): list them, print one, or copy it to paste as a new chat's first message ([handoff](./docs/handoff.md)) |
149
149
  | `context-doctor mcp [--http]` | The MCP server as a subcommand, for clients and registries that launch `npx -y context-doctor mcp` |
150
150
  | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H] [--allowed-hosts names] [--allowed-origins list] [--store-handoffs]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to `--allowed-hosts`) |
151
- | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, output's and reasoning's share of the cost, repeated identical (polling) tool calls priced, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
151
+ | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, output's and reasoning's share of the cost, repeated identical (polling) tool calls priced, **what its subagents cost** (their own windows, your bill; never in the parent's profile), and **Claude Code's own figure for it** (its `cost-state`) beside ours, with what the gap is made of. Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
152
152
  | `context-doctor watch [file]` | Live monitor of a growing session transcript or agent trace (Claude Code / Codex JSONL, or a plain OpenAI/Anthropic conversation JSON file): token/cost line per change, findings as they appear |
153
153
  | `context-doctor cursor [--list]` | Profile a chat from Cursor's local history (both storage formats) |
154
154
  | `context-doctor analyze <file>` | Profile a conversation: token breakdown, findings, cost + latency estimates. `--exact` adds a true count; `--fail-over-budget` exits 1 on a breach, for CI |
155
155
  | `context-doctor optimize <file>` | Apply the safe fixes; add `--strategy trim-tool-calls` for big inline file writes, `--strategy prune-history` for consented lossy compaction ([what each does](./docs/detectors.md)) |
156
156
  | `context-doctor diff <before> <after>` | Compare two profiles: what moved by category, which findings were resolved or introduced, and what it saves in money and latency |
157
- | `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; `--mcp` sizes each configured server's tool definitions and flags unused ones |
157
+ | `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; each session's and subagent's start per entrypoint (Desktop app, terminal, SDK) and subagent type, priced over the period, with the MCP tool definitions sent whole and whether any setting defers them; `--mcp` sizes each configured server's tool definitions and flags unused ones |
158
158
  | `context-doctor overhead prune [--days n] [--write] [--undo]` | Per project, the MCP servers and skills its sessions never used in n days; `--write` switches them off for this folder's project in its `.claude/settings.local.json` (backup kept, every entry recorded), `--undo` takes exactly those out. Never the app's connectors, plugins, or context-doctor itself |
159
159
  | `context-doctor overhead split <file> [--min-tokens n] [--write]` | Move a memory file's big or code-heavy sections word for word to `<name>.reference.md`, leaving pointers; indexes stay. A plan until `--write`, which backs up first |
160
160
  | `context-doctor pack <files\|dirs\|-> -q "…"` | Only the chunks of big documents, logs or code a question needs, ranked and fit to `--max-tokens` (default 4000). No query: an outline; `--ids a#2,b#5` picks chunks from it. `--semantic` also ranks by meaning with a local Ollama model. Offline, no key |
161
161
  | `context-doctor recall "<query>" [--session <id\|path>]` | Search this session's own transcript on disk (Claude Code or Codex; turns before a compaction and tool output cleared from the context included) and print the best excerpts with time and position, secrets masked. Never another project's session unless named with `--session`. Also the `recall` MCP tool |
162
162
  | `context-doctor tasks [--days n]` | Cost per commit, per project: each session priced from its recorded usage against the commits it made |
163
163
  | `context-doctor reads [--days n] [--limit n]` | Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or `pack` pays |
164
- | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
164
+ | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session (read through the transcript cache: 15 s to 0.3 s warm on the author's machine) |
165
165
  | `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
166
- | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate); `--json` per model and version |
167
- | `context-doctor limits [--days n]` | Your plan's limits in their own unit: each window's %, pace and run-out time (Claude's 5-hour and weekly windows from the status line's readings, Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted |
166
+ | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate). Then the cold returns, each replayed as billed, compacted on return and kept warm (a cache read every 55 min while away, 4.5 on a 5-minute cache), by time away (<1h to >8h); keeping warm for up to 1, 2, 4 and 8 hours priced with every ping a timer would send; and #107157's re-added compacted segment with its re-write; `--json` per model and version |
167
+ | `context-doctor limits [--days n] [--report [--copy]]` | Your plan's limits in their own unit: each window's %, pace and run-out time (Claude's weekly and 5-hour windows, from the readings the plugin's mod, the status line or the proxy record; Ultra has no 5-hour window; Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted. Each weekly window, reset to reset: API-equivalent $ and tokens per 1%, split by entrypoint (`cli`, `claude-desktop`, `sdk-cli`) and model, and where that moved, by how much and on what date. `--report`: the same as a block to paste into a GitHub issue (no prompts, paths, session or account ids) |
168
168
  | `context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]` | Where an Anthropic API request should carry `cache_control` (top-level automatic caching for the moving end, unless `--explicit`), and what it saves over n calls; `--out` writes it applied |
169
169
  | `context-doctor accuracy` | How much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses |
170
170
  | `context-doctor report` | Machine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume `/compact` offer was followed by a compaction, recoverable waste in recent sessions |
@@ -183,6 +183,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
183
183
 
184
184
  ## What's new
185
185
 
186
+ - **0.49 Count what Claude Code counts, cold returns, limits you can paste, a Desktop usage pane, and teams**: `spend` and `doctor` show Claude Code's own cost (its `cost-state`) beside ours, 2% apart on the author's 30 days, and count the advisor's calls and replies a server-side fallback replaced. `cache-misses` replays every return after the cache expired three ways (as billed, compacted, kept warm) by time away (the author's: $894 in 183 returns), and the mod's `/context-doctor-keep-warm` keeps it warm on request only, capped in hours and dollars. `overhead` prices every session's and subagent's start ($455 a month here) and `fix` gains `mcp-defer`. `limits` gives dollars per 1% per weekly reset with the moves dated, `limits --report` a block for a bug report, and handles Ultra (no 5-hour window). `/context-doctor-usage` is a usage pane in the Desktop app. `spend` reads Copilot CLI, OpenCode and Cline, splits `--by repo|branch`, and `--export` / `spend merge` add up a team's totals with no prompt or path ([details](./ROADMAP.md#shipped-in-0490-count-what-claude-code-counts-cold-returns-limits-you-can-paste-a-desktop-usage-pane-and-teams)).
187
+ - **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)).
186
188
  - **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)).
187
189
  - **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)).
188
190
  - **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)).
@@ -211,7 +213,8 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
211
213
  - [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
212
214
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
213
215
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
214
- - [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)
216
+ - [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
217
+ - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, `/context-doctor-fix`, `/context-doctor-usage` (the context ring, limit windows, tokens and dollars by model, running subagents) and `/context-doctor-keep-warm` (Desktop app, VS Code, terminal), and the cache band with Compact first (Desktop app and terminal only)
215
218
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
216
219
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
217
220
  - [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
@@ -56,7 +56,7 @@ export const AB_API_VERSION = "2026-10-21";
56
56
  /** Output cap per request; also the output side of each request's worst case for the budget. */
57
57
  const MAX_TOKENS = 16000;
58
58
  /** A smoke test or hidden check that runs longer is killed (and fails). */
59
- const CHECK_TIMEOUT_MS = 30_000;
59
+ export const CHECK_TIMEOUT_MS = 30_000;
60
60
  /** What each lever is compared against, and what it is. */
61
61
  const LEVER_INFO = {
62
62
  rules: { base: "none", arm: "rules", what: "the standing context rules in the system prompt (what MCP clients and the Copilot hook add)" },
@@ -135,7 +135,7 @@ function minimalEnv(home) {
135
135
  return env;
136
136
  }
137
137
  /** Kill a child and everything in its process group (the child leads one). */
138
- function killTree(child) {
138
+ export function killTree(child) {
139
139
  if (child.pid === undefined)
140
140
  return;
141
141
  if (process.platform === "win32") {
@@ -207,7 +207,37 @@ function makeWritable(path) {
207
207
  for (const name of readdirSync(path))
208
208
  makeWritable(join(path, name));
209
209
  }
210
- 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) {
211
241
  killLeftovers(root);
212
242
  makeWritable(root);
213
243
  try {
@@ -225,6 +255,8 @@ function removeRoot(root, live) {
225
255
  function runNode(args, cwd, home, live) {
226
256
  const timeoutMs = live.timeoutMs;
227
257
  return new Promise((resolveRun) => {
258
+ if (live.stopping)
259
+ return; // Ctrl-C: held until the exit
228
260
  let tail = "";
229
261
  let timedOut = false;
230
262
  const child = spawn(process.execPath, args, { cwd, env: minimalEnv(home), stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
@@ -240,7 +272,7 @@ function runNode(args, cwd, home, live) {
240
272
  }, timeoutMs);
241
273
  let finished = false;
242
274
  const finish = (code) => {
243
- if (finished)
275
+ if (finished || live.stopping)
244
276
  return;
245
277
  finished = true;
246
278
  clearTimeout(timer);
@@ -389,8 +421,8 @@ async function execute(block, run, task, allowPack, counts, live) {
389
421
  return fail(e.message);
390
422
  }
391
423
  }
392
- /** Ends that say nothing about the lever: the API failed or declined, or the harness's own caps cut the run. */
393
- 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"]);
394
426
  /** Autopilot with every request as if after an idle gap: clearing is allowed on each one. */
395
427
  class ColdEveryRequest extends AutoClearer {
396
428
  clock = 0;
@@ -416,7 +448,7 @@ function asTranscript(messages) {
416
448
  : { type: "user", message: { role: "user", content: m.content } }))
417
449
  .join("\n") + "\n";
418
450
  }
419
- function taskPrompt(task) {
451
+ export function taskPrompt(task) {
420
452
  const list = Object.keys(task.files)
421
453
  .sort()
422
454
  .map((p) => `- ${p} (${(Buffer.byteLength(task.files[p]) / 1024).toFixed(1)} KB)`)
@@ -436,7 +468,7 @@ function worstCaseUsd(body, pricing) {
436
468
  return (prompt * pricing.inputPerM * CACHE_WRITE_5M + MAX_TOKENS * pricing.outputPerM) / 1e6;
437
469
  }
438
470
  /** The hidden check: written outside the repository, run with it as the working directory. */
439
- async function verifyRun(task, run, live) {
471
+ export async function verifyRun(task, run, live) {
440
472
  try {
441
473
  makeWritable(run.root); // the agent's code may have locked its folders
442
474
  const script = join(run.root, "verify.mjs");
@@ -451,7 +483,7 @@ async function verifyRun(task, run, live) {
451
483
  }
452
484
  }
453
485
  /** A fresh run folder: the repository, and a home for the code it runs. */
454
- function makeRun(task, live) {
486
+ export function makeRun(task, live) {
455
487
  const root = mkdtempSync(join(tmpdir(), `ctxdoc-ab-${task.id}-`));
456
488
  live.roots.add(root);
457
489
  const repo = join(root, "repo");
@@ -595,12 +627,13 @@ export function armsFor(levers) {
595
627
  /**
596
628
  * A planning figure, not a quote: six requests a run, the task's files in
597
629
  * context from the second request on, ~800 output tokens a request (thinking,
598
- * 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).
599
632
  */
600
- export function estimateAb(tasks, arms, repeat, pricing) {
601
- const R = 6;
633
+ export function estimateAb(tasks, arms, repeat, pricing, shape = {}) {
634
+ const R = shape.requests ?? 6;
602
635
  const OUT = 800;
603
- 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");
604
637
  let expected = 0;
605
638
  let upper = 0;
606
639
  for (const task of tasks) {
@@ -638,15 +671,7 @@ export async function runAbSuite(options) {
638
671
  live: { children: new Set(), roots: new Set(), timeoutMs: options.checkTimeoutMs ?? CHECK_TIMEOUT_MS },
639
672
  };
640
673
  // Ctrl-C: nothing of the agent's keeps running, no run folder stays behind.
641
- const interrupt = (signal) => {
642
- for (const child of ctx.live.children)
643
- killTree(child);
644
- for (const root of [...ctx.live.roots])
645
- removeRoot(root, ctx.live);
646
- process.exit(signal === "SIGINT" ? 130 : 143);
647
- };
648
- process.once("SIGINT", interrupt);
649
- process.once("SIGTERM", interrupt);
674
+ const unhook = stopOnSignal(ctx.live);
650
675
  const queue = [];
651
676
  for (let rep = 1; rep <= repeat; rep++)
652
677
  for (const task of tasks)
@@ -655,7 +680,7 @@ export async function runAbSuite(options) {
655
680
  const runs = [];
656
681
  let next = 0;
657
682
  const worker = async () => {
658
- while (next < queue.length && !ctx.fatal) {
683
+ while (next < queue.length && !ctx.fatal && !ctx.live.stopping) {
659
684
  const { task, arm, rep } = queue[next++];
660
685
  const run = await runOne(task, arm, rep, ctx);
661
686
  runs.push(run);
@@ -666,8 +691,7 @@ export async function runAbSuite(options) {
666
691
  await Promise.all(Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, worker));
667
692
  }
668
693
  finally {
669
- process.off("SIGINT", interrupt);
670
- process.off("SIGTERM", interrupt);
694
+ unhook();
671
695
  }
672
696
  const order = (r) => queue.findIndex((q) => q.task.id === r.task && q.arm === r.arm && q.rep === r.rep);
673
697
  runs.sort((a, b) => order(a) - order(b));
@@ -755,7 +779,7 @@ export function renderAb(result) {
755
779
  return out.join("\n");
756
780
  }
757
781
  /** Why `--out` cannot be written, checked before anything is spent; undefined when it can. */
758
- function outProblem(out) {
782
+ export function outProblem(out) {
759
783
  const path = resolve(out);
760
784
  try {
761
785
  if (statSync(path).isDirectory())
@@ -792,7 +816,20 @@ export async function abCommand(o) {
792
816
  console.log(` ${l.padEnd(10)} ${LEVER_INFO[l].what}`);
793
817
  return 0;
794
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
+ }
795
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
+ }
796
833
  const unknownLever = leverNames.find((l) => l !== "all" && !AB_LEVERS.includes(l));
797
834
  if (unknownLever) {
798
835
  console.error(`Unknown lever "${unknownLever}". Levers: ${AB_LEVERS.join(", ")}, or all.`);
@@ -806,6 +843,11 @@ export async function abCommand(o) {
806
843
  return 1;
807
844
  }
808
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
+ }
809
851
  const model = o.model ?? DEFAULT_AB_MODEL;
810
852
  const pricing = exactClaudePricingFor(model);
811
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>;