context-doctor 0.47.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.
- package/README.md +3 -1
- package/dist/ab.d.ts +51 -3
- package/dist/ab.js +68 -26
- package/dist/abclaude.d.ts +167 -0
- package/dist/abclaude.js +511 -0
- package/dist/abstore.d.ts +46 -0
- package/dist/abstore.js +58 -0
- package/dist/cli.js +19 -0
- package/dist/fix.d.ts +7 -2
- package/dist/fix.js +6 -3
- package/dist/install.js +2 -0
- package/dist/mcp.d.ts +4 -0
- package/dist/mcp.js +142 -98
- package/dist/mcpclient.js +73 -42
- package/dist/modelids.d.ts +58 -0
- package/dist/modelids.js +133 -1
- package/dist/pricing.js +14 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ 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.
|
|
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)) |
|
|
34
34
|
|
|
35
35
|
## What it does
|
|
36
36
|
|
|
@@ -183,6 +183,7 @@ 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.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
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)).
|
|
187
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)).
|
|
188
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)).
|
|
@@ -211,6 +212,7 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
|
|
|
211
212
|
- [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
|
|
212
213
|
- [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
|
|
213
214
|
- [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
|
|
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
|
|
214
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)
|
|
215
217
|
- [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
|
|
216
218
|
- [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
|
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,
|
|
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:
|
|
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
|
-
|
|
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,
|
|
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
|
|
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
|
-
|
|
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>;
|