context-doctor 0.35.0 → 0.36.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 +8 -5
- package/dist/ab.d.ts +188 -0
- package/dist/ab.js +857 -0
- package/dist/abtasks.d.ts +49 -0
- package/dist/abtasks.js +287 -0
- package/dist/cli.js +34 -8
- package/dist/copilot.d.ts +63 -0
- package/dist/copilot.js +96 -0
- package/dist/doctor.js +114 -1
- package/dist/hook.d.ts +1 -1
- package/dist/hook.js +25 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +16 -0
- package/dist/install.js +176 -3
- package/dist/ledger.d.ts +4 -1
- package/dist/ledger.js +1 -0
- package/dist/mcp.js +38 -38
- package/dist/pricing.d.ts +7 -0
- package/dist/pricing.js +29 -5
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/rules.d.ts +16 -0
- package/dist/rules.js +30 -0
- package/package.json +1 -1
package/dist/ab.js
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `context-doctor ab`: does a lever cost quality? Each task of a small suite
|
|
3
|
+
* (abtasks.ts) runs with and without the lever, through the Messages API,
|
|
4
|
+
* with a minimal agent loop (read_file, write_file, run_check), and is
|
|
5
|
+
* scored by a hidden check the harness runs after the agent stops. Pass
|
|
6
|
+
* counts, tokens and cost per arm, side by side: "no quality loss" as a
|
|
7
|
+
* number rather than a proxy (re-reads, tool errors, corrections).
|
|
8
|
+
*
|
|
9
|
+
* Arms:
|
|
10
|
+
* none the baseline: a plain system prompt and the three tools
|
|
11
|
+
* rules + the standing context rules (what MCP clients and the
|
|
12
|
+
* Copilot hook inject) in the system prompt
|
|
13
|
+
* autoclear the client wrapped with withContextDoctor (autopilot in
|
|
14
|
+
* process), every request treated as after an idle gap so
|
|
15
|
+
* clearing is allowed on each one: the worst case for
|
|
16
|
+
* quality, not autopilot's real cost
|
|
17
|
+
* pack + a pack_context tool and the rule to use it for big
|
|
18
|
+
* files instead of reading them whole
|
|
19
|
+
* compact-generic one compaction mid-task with generic instructions; the
|
|
20
|
+
* session then continues from the summary alone
|
|
21
|
+
* compact the same compaction with the PreCompact hook's
|
|
22
|
+
* instructions (files changed, failing checks, the user's
|
|
23
|
+
* own instructions) added, as Claude Code merges them
|
|
24
|
+
*
|
|
25
|
+
* The agent's code runs (in the smoke test and the hidden check) with a
|
|
26
|
+
* minimal environment (no API key, a throwaway HOME), in its own process
|
|
27
|
+
* group, under a time limit; whatever it leaves running is killed and every
|
|
28
|
+
* temporary folder is removed, on errors and Ctrl-C too. It is a quality
|
|
29
|
+
* test, not a sandbox: the code runs as the user.
|
|
30
|
+
*
|
|
31
|
+
* It spends the caller's API budget, so the CLI prints the estimate first,
|
|
32
|
+
* needs --yes to send anything, and sends no request whose worst case
|
|
33
|
+
* (prompt as cache writes, max_tokens of output) would pass --budget. The
|
|
34
|
+
* provider is an interface: anthropicProvider() speaks the Messages API over
|
|
35
|
+
* fetch (this package has no runtime dependencies), and tests plug in a
|
|
36
|
+
* local mock server through ANTHROPIC_BASE_URL.
|
|
37
|
+
*/
|
|
38
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
39
|
+
import { randomBytes } from "node:crypto";
|
|
40
|
+
import { accessSync, chmodSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
41
|
+
import { tmpdir } from "node:os";
|
|
42
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
43
|
+
import { AB_TASKS, abVerifyScript } from "./abtasks.js";
|
|
44
|
+
import { AutoClearer } from "./autoclear.js";
|
|
45
|
+
import { packContext, renderPack } from "./pack.js";
|
|
46
|
+
import { compactFacts, compactInstructions } from "./precompact.js";
|
|
47
|
+
import { exactClaudePricingFor, formatUsd, usageCost, CACHE_WRITE_5M } from "./pricing.js";
|
|
48
|
+
import { SERVER_INSTRUCTIONS } from "./rules.js";
|
|
49
|
+
import { estimateTokens, formatTokens } from "./tokens.js";
|
|
50
|
+
import { contextDoctorStats, withContextDoctor } from "./wrap.js";
|
|
51
|
+
export const AB_LEVERS = ["rules", "autoclear", "pack", "compact"];
|
|
52
|
+
export const DEFAULT_AB_MODEL = "claude-opus-5-5";
|
|
53
|
+
/** The Messages API version the harness sends (sampling parameters are not sent). */
|
|
54
|
+
export const AB_API_VERSION = "2026-10-21";
|
|
55
|
+
/** Output cap per request; also the output side of each request's worst case for the budget. */
|
|
56
|
+
const MAX_TOKENS = 16000;
|
|
57
|
+
/** A smoke test or hidden check that runs longer is killed (and fails). */
|
|
58
|
+
const CHECK_TIMEOUT_MS = 30_000;
|
|
59
|
+
/** What each lever is compared against, and what it is. */
|
|
60
|
+
const LEVER_INFO = {
|
|
61
|
+
rules: { base: "none", arm: "rules", what: "the standing context rules in the system prompt (what MCP clients and the Copilot hook add)" },
|
|
62
|
+
autoclear: { base: "none", arm: "autoclear", what: "autopilot in process (withContextDoctor), stale tool output cleared whenever the batch is big enough, as if every request came after an idle gap" },
|
|
63
|
+
pack: { base: "none", arm: "pack", what: "a pack_context tool and the rule to use it for big files instead of reading them whole" },
|
|
64
|
+
compact: { base: "compact-generic", arm: "compact", what: "one compaction mid-task, continued from the summary alone, with the PreCompact hook's instructions vs generic ones" },
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* The Messages API over fetch. Retries what the API asks to be retried
|
|
68
|
+
* (429, 5xx, 529 overloaded) and what the network breaks (a refused
|
|
69
|
+
* connection, a body cut short, a 200 whose body is not the message), with
|
|
70
|
+
* backoff, honouring retry-after. Anything else is the caller's error and
|
|
71
|
+
* is thrown with its status, so the SDK wrapper can recognise a refused
|
|
72
|
+
* history edit and the suite can stop on a refused key.
|
|
73
|
+
*/
|
|
74
|
+
export function anthropicProvider(options) {
|
|
75
|
+
const base = (options.baseUrl ?? process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com").replace(/\/+$/, "");
|
|
76
|
+
const retries = options.retries ?? 4;
|
|
77
|
+
return {
|
|
78
|
+
name: `Anthropic Messages API (${base})`,
|
|
79
|
+
async create(body) {
|
|
80
|
+
for (let attempt = 0;; attempt++) {
|
|
81
|
+
let status = 0;
|
|
82
|
+
let text = "";
|
|
83
|
+
let retryAfter = null;
|
|
84
|
+
let broken; // the network or the body failed, not the API
|
|
85
|
+
try {
|
|
86
|
+
const res = await fetch(`${base}/v1/messages`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "content-type": "application/json", "x-api-key": options.apiKey, "anthropic-version": AB_API_VERSION },
|
|
89
|
+
body: JSON.stringify(body),
|
|
90
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 600_000),
|
|
91
|
+
});
|
|
92
|
+
status = res.status;
|
|
93
|
+
retryAfter = res.headers.get("retry-after");
|
|
94
|
+
text = await res.text();
|
|
95
|
+
if (res.ok) {
|
|
96
|
+
const parsed = JSON.parse(text);
|
|
97
|
+
if (Array.isArray(parsed?.content))
|
|
98
|
+
return parsed;
|
|
99
|
+
broken = new Error("the response has no content array");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
broken = e;
|
|
104
|
+
}
|
|
105
|
+
const retryable = broken !== undefined || status === 429 || status === 529 || status >= 500;
|
|
106
|
+
if (!retryable || attempt >= retries) {
|
|
107
|
+
if (broken !== undefined && (status === 0 || status === 200)) {
|
|
108
|
+
throw Object.assign(new Error(`${status ? "HTTP 200 with an unusable body" : "no response"}: ${broken.message ?? broken}`), { status });
|
|
109
|
+
}
|
|
110
|
+
let message = text.slice(0, 500);
|
|
111
|
+
let error = text;
|
|
112
|
+
try {
|
|
113
|
+
error = JSON.parse(text);
|
|
114
|
+
message = error?.error?.message ?? message;
|
|
115
|
+
}
|
|
116
|
+
catch { /* not JSON */ }
|
|
117
|
+
throw Object.assign(new Error(`HTTP ${status}: ${message}`), { status, error });
|
|
118
|
+
}
|
|
119
|
+
const wait = retryAfter && Number(retryAfter) >= 0 ? Number(retryAfter) * 1000 : 1000 * 2 ** attempt;
|
|
120
|
+
await new Promise((r) => setTimeout(r, Math.min(wait, 60_000)));
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** PATH and a throwaway home: no API key or other secret reaches code the model wrote. */
|
|
126
|
+
function minimalEnv(home) {
|
|
127
|
+
const tmp = join(home, "tmp");
|
|
128
|
+
mkdirSync(tmp, { recursive: true });
|
|
129
|
+
const env = { PATH: process.env.PATH ?? process.env.Path ?? "", HOME: home, USERPROFILE: home, TMPDIR: tmp, TEMP: tmp, TMP: tmp };
|
|
130
|
+
// Windows cannot start processes without these.
|
|
131
|
+
for (const k of ["SystemRoot", "SYSTEMROOT", "windir", "ComSpec", "PATHEXT"])
|
|
132
|
+
if (process.env[k] !== undefined)
|
|
133
|
+
env[k] = process.env[k];
|
|
134
|
+
return env;
|
|
135
|
+
}
|
|
136
|
+
/** Kill a child and everything in its process group (the child leads one). */
|
|
137
|
+
function killTree(child) {
|
|
138
|
+
if (child.pid === undefined)
|
|
139
|
+
return;
|
|
140
|
+
if (process.platform === "win32") {
|
|
141
|
+
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
process.kill(-child.pid, "SIGKILL");
|
|
146
|
+
}
|
|
147
|
+
catch { /* the group is gone */ }
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Processes still working inside a run folder: a child that left its process
|
|
151
|
+
* group (detached) is still found by its working directory, through /proc
|
|
152
|
+
* on Linux and lsof elsewhere, and killed. Best effort: without either, the
|
|
153
|
+
* minimal environment is what limits it.
|
|
154
|
+
*/
|
|
155
|
+
function killLeftovers(root) {
|
|
156
|
+
if (process.platform === "win32")
|
|
157
|
+
return;
|
|
158
|
+
const pids = new Set();
|
|
159
|
+
try {
|
|
160
|
+
if (existsSync("/proc/self/cwd")) {
|
|
161
|
+
for (const name of readdirSync("/proc")) {
|
|
162
|
+
if (!/^\d+$/.test(name))
|
|
163
|
+
continue;
|
|
164
|
+
try {
|
|
165
|
+
const cwd = readlinkSync(`/proc/${name}/cwd`);
|
|
166
|
+
if (cwd === root || cwd.startsWith(root + sep))
|
|
167
|
+
pids.add(Number(name));
|
|
168
|
+
}
|
|
169
|
+
catch { /* gone, or not ours to read */ }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 5000 });
|
|
174
|
+
for (const line of (r.stdout ?? "").split("\n"))
|
|
175
|
+
if (/^\d+$/.test(line.trim()))
|
|
176
|
+
pids.add(Number(line.trim()));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch { /* best effort */ }
|
|
180
|
+
pids.delete(process.pid);
|
|
181
|
+
for (const pid of pids) {
|
|
182
|
+
try {
|
|
183
|
+
process.kill(pid, "SIGKILL");
|
|
184
|
+
}
|
|
185
|
+
catch { /* already gone */ }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Make a tree removable (the agent's code may have made it read-only), without following links. */
|
|
189
|
+
function makeWritable(path) {
|
|
190
|
+
let st;
|
|
191
|
+
try {
|
|
192
|
+
st = lstatSync(path);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (st.isSymbolicLink())
|
|
198
|
+
return;
|
|
199
|
+
try {
|
|
200
|
+
chmodSync(path, st.isDirectory() ? 0o700 : 0o600);
|
|
201
|
+
}
|
|
202
|
+
catch { /* best effort */ }
|
|
203
|
+
if (st.isDirectory())
|
|
204
|
+
for (const name of readdirSync(path))
|
|
205
|
+
makeWritable(join(path, name));
|
|
206
|
+
}
|
|
207
|
+
function removeRoot(root, live) {
|
|
208
|
+
killLeftovers(root);
|
|
209
|
+
makeWritable(root);
|
|
210
|
+
try {
|
|
211
|
+
rmSync(root, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
catch { /* reported by nothing: a temp folder the OS clears */ }
|
|
214
|
+
live.roots.delete(root);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Run `node <args>` in `cwd` with the minimal environment, in its own
|
|
218
|
+
* process group, killed with its group at `timeoutMs` and again when it
|
|
219
|
+
* exits (whatever it started and left behind). Output is kept to its last
|
|
220
|
+
* 3,000 characters however much is written.
|
|
221
|
+
*/
|
|
222
|
+
function runNode(args, cwd, home, live) {
|
|
223
|
+
const timeoutMs = live.timeoutMs;
|
|
224
|
+
return new Promise((resolveRun) => {
|
|
225
|
+
let tail = "";
|
|
226
|
+
let timedOut = false;
|
|
227
|
+
const child = spawn(process.execPath, args, { cwd, env: minimalEnv(home), stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
|
|
228
|
+
live.children.add(child);
|
|
229
|
+
const keep = (d) => {
|
|
230
|
+
tail = (tail + d.toString("utf8")).slice(-3000);
|
|
231
|
+
};
|
|
232
|
+
child.stdout.on("data", keep);
|
|
233
|
+
child.stderr.on("data", keep);
|
|
234
|
+
const timer = setTimeout(() => {
|
|
235
|
+
timedOut = true;
|
|
236
|
+
killTree(child);
|
|
237
|
+
}, timeoutMs);
|
|
238
|
+
let finished = false;
|
|
239
|
+
const finish = (code) => {
|
|
240
|
+
if (finished)
|
|
241
|
+
return;
|
|
242
|
+
finished = true;
|
|
243
|
+
clearTimeout(timer);
|
|
244
|
+
killTree(child);
|
|
245
|
+
live.children.delete(child);
|
|
246
|
+
resolveRun({ code: timedOut ? 1 : code, output: timedOut ? `${tail}\n[killed after ${timeoutMs / 1000} s]` : tail, timedOut });
|
|
247
|
+
};
|
|
248
|
+
child.on("error", (e) => {
|
|
249
|
+
tail += `\n${e.message}`;
|
|
250
|
+
finish(1);
|
|
251
|
+
});
|
|
252
|
+
child.on("close", (code) => finish(code ?? 1));
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
// -- The agent's tools ---------------------------------------------------------
|
|
256
|
+
const SMOKE_FILE = "test.mjs";
|
|
257
|
+
const BASE_TOOLS = [
|
|
258
|
+
{
|
|
259
|
+
name: "read_file",
|
|
260
|
+
description: "Read one file of the repository, whole. `path` is relative to the repository root.",
|
|
261
|
+
input_schema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] },
|
|
262
|
+
},
|
|
263
|
+
{
|
|
264
|
+
name: "write_file",
|
|
265
|
+
description: "Write one whole file of the repository, replacing what is there (folders are created). test.mjs cannot be changed.",
|
|
266
|
+
input_schema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } }, required: ["path", "content"] },
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
name: "run_check",
|
|
270
|
+
description: "Run the repository's smoke test, `node test.mjs`, and return its output and exit code. It shows the code loads and runs, not that the results are right.",
|
|
271
|
+
input_schema: { type: "object", properties: {} },
|
|
272
|
+
},
|
|
273
|
+
];
|
|
274
|
+
const PACK_TOOL = {
|
|
275
|
+
name: "pack_context",
|
|
276
|
+
description: "Only the parts of the repository's files that a question needs, ranked and cut to ~1,500 tokens, instead of reading them whole. `paths` limits it to some files.",
|
|
277
|
+
input_schema: { type: "object", properties: { question: { type: "string" }, paths: { type: "array", items: { type: "string" } } }, required: ["question"] },
|
|
278
|
+
};
|
|
279
|
+
const BASE_SYSTEM = "You are a careful software engineer working in a small JavaScript repository through tools. Make the smallest correct change; " +
|
|
280
|
+
"the work is judged by a hidden test of the behaviour the request and the repository's documents describe. " +
|
|
281
|
+
"When you think the task is done, call run_check; once it passes, reply with one sentence saying what you changed.";
|
|
282
|
+
const PACK_RULE = "To answer from a big file you won't edit, call pack_context with the question; don't read it whole.";
|
|
283
|
+
const GENERIC_COMPACTION = "Your context is being compacted: the session will continue from your summary alone. Write a summary that lets the work continue without it: " +
|
|
284
|
+
"the request in full, what you found (with the exact facts the work depends on), what you changed, what is still failing, and what remains to do. " +
|
|
285
|
+
"Reply with the summary only; do not call tools.";
|
|
286
|
+
/**
|
|
287
|
+
* The repository file a tool names, or why not: a path outside the
|
|
288
|
+
* repository, or one through a symbolic link (the agent's own code can
|
|
289
|
+
* make links when the smoke test runs it, and reads or writes through one
|
|
290
|
+
* would reach outside).
|
|
291
|
+
*/
|
|
292
|
+
function repoPath(repo, path) {
|
|
293
|
+
if (typeof path !== "string" || path.trim() === "" || isAbsolute(path))
|
|
294
|
+
return { error: `not a path inside the repository: ${String(path)}` };
|
|
295
|
+
const full = resolve(repo, path);
|
|
296
|
+
const rel = relative(repo, full);
|
|
297
|
+
if (rel === "" || rel.startsWith("..") || isAbsolute(rel))
|
|
298
|
+
return { error: `not a path inside the repository: ${path}` };
|
|
299
|
+
let at = repo;
|
|
300
|
+
for (const part of rel.split(sep)) {
|
|
301
|
+
at = join(at, part);
|
|
302
|
+
try {
|
|
303
|
+
if (lstatSync(at).isSymbolicLink())
|
|
304
|
+
return { error: `${path} goes through a symbolic link, which is not followed` };
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
break; // the rest does not exist yet
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return { full, rel: rel.split(sep).join("/") };
|
|
311
|
+
}
|
|
312
|
+
function filesUnder(dir, root = dir) {
|
|
313
|
+
return readdirSync(dir).flatMap((name) => {
|
|
314
|
+
const full = join(dir, name);
|
|
315
|
+
const st = lstatSync(full);
|
|
316
|
+
if (st.isSymbolicLink())
|
|
317
|
+
return [];
|
|
318
|
+
return st.isDirectory() ? filesUnder(full, root) : [relative(root, full).split(sep).join("/")];
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Put the shipped smoke test back: whatever stands at test.mjs (a changed
|
|
323
|
+
* file, a folder, a link to anywhere) is removed without following it, and
|
|
324
|
+
* the file is created anew, never written through.
|
|
325
|
+
*/
|
|
326
|
+
function restoreSmoke(repo, task) {
|
|
327
|
+
makeWritable(repo);
|
|
328
|
+
const path = join(repo, SMOKE_FILE);
|
|
329
|
+
try {
|
|
330
|
+
const st = lstatSync(path);
|
|
331
|
+
if (st.isDirectory() && !st.isSymbolicLink())
|
|
332
|
+
rmSync(path, { recursive: true, force: true });
|
|
333
|
+
else
|
|
334
|
+
unlinkSync(path);
|
|
335
|
+
}
|
|
336
|
+
catch { /* nothing there */ }
|
|
337
|
+
writeFileSync(path, task.files[SMOKE_FILE], { flag: "wx" });
|
|
338
|
+
}
|
|
339
|
+
async function execute(block, run, task, allowPack, counts, live) {
|
|
340
|
+
const id = String(block.id ?? "");
|
|
341
|
+
const fail = (content) => ({ type: "tool_result", tool_use_id: id, content, is_error: true });
|
|
342
|
+
const input = block.input ?? {};
|
|
343
|
+
try {
|
|
344
|
+
switch (block.name) {
|
|
345
|
+
case "read_file": {
|
|
346
|
+
const p = repoPath(run.repo, input.path);
|
|
347
|
+
if ("error" in p)
|
|
348
|
+
return fail(p.error);
|
|
349
|
+
return { type: "tool_result", tool_use_id: id, content: readFileSync(p.full, "utf8") };
|
|
350
|
+
}
|
|
351
|
+
case "write_file": {
|
|
352
|
+
const p = repoPath(run.repo, input.path);
|
|
353
|
+
if ("error" in p)
|
|
354
|
+
return fail(p.error);
|
|
355
|
+
// Windows drops trailing dots and spaces: "test.mjs " is test.mjs there.
|
|
356
|
+
if (p.rel.replace(/[. ]+$/, "").toLowerCase() === SMOKE_FILE)
|
|
357
|
+
return fail("test.mjs is the smoke test and cannot be changed");
|
|
358
|
+
if (typeof input.content !== "string")
|
|
359
|
+
return fail("content must be a string");
|
|
360
|
+
mkdirSync(dirname(p.full), { recursive: true });
|
|
361
|
+
if (existsSync(p.full) && !statSync(p.full).isFile())
|
|
362
|
+
return fail(`${String(input.path)} is not a file`);
|
|
363
|
+
writeFileSync(p.full, input.content);
|
|
364
|
+
return { type: "tool_result", tool_use_id: id, content: `wrote ${Buffer.byteLength(input.content)} bytes to ${String(input.path)}` };
|
|
365
|
+
}
|
|
366
|
+
case "run_check": {
|
|
367
|
+
restoreSmoke(run.repo, task);
|
|
368
|
+
const r = await runNode([SMOKE_FILE], run.repo, run.home, live);
|
|
369
|
+
return { type: "tool_result", tool_use_id: id, content: `${r.output}\nexit code ${r.code}`, ...(r.code !== 0 ? { is_error: true } : {}) };
|
|
370
|
+
}
|
|
371
|
+
case "pack_context": {
|
|
372
|
+
if (!allowPack)
|
|
373
|
+
return fail("no such tool");
|
|
374
|
+
counts.pack++;
|
|
375
|
+
const wanted = Array.isArray(input.paths) ? input.paths.map(String) : undefined;
|
|
376
|
+
const sources = filesUnder(run.repo)
|
|
377
|
+
.filter((p) => !wanted || wanted.includes(p))
|
|
378
|
+
.map((p) => ({ name: p, text: readFileSync(join(run.repo, p), "utf8") }));
|
|
379
|
+
return { type: "tool_result", tool_use_id: id, content: renderPack(packContext(sources, { query: String(input.question ?? ""), budget: 1500 })) };
|
|
380
|
+
}
|
|
381
|
+
default:
|
|
382
|
+
return fail(`no such tool: ${String(block.name)}`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
catch (e) {
|
|
386
|
+
return fail(e.message);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** Ends that say nothing about the lever: the API failed or declined, or the harness's own caps cut the run. */
|
|
390
|
+
export const STOPPED_EARLY = new Set(["error", "budget", "turns", "refusal", "max_tokens"]);
|
|
391
|
+
/** Autopilot with every request as if after an idle gap: clearing is allowed on each one. */
|
|
392
|
+
class ColdEveryRequest extends AutoClearer {
|
|
393
|
+
clock = 0;
|
|
394
|
+
apply(body, _now, modelHint, account) {
|
|
395
|
+
this.clock += 2 * 3_600_000;
|
|
396
|
+
return super.apply(body, this.clock, modelHint, account);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/** The harness's history as a Claude Code transcript, the shape the PreCompact hook reads. */
|
|
400
|
+
function asTranscript(messages) {
|
|
401
|
+
const rename = (b) => {
|
|
402
|
+
if (b.type !== "tool_use")
|
|
403
|
+
return b;
|
|
404
|
+
if (b.name === "write_file")
|
|
405
|
+
return { ...b, name: "Write", input: { file_path: b.input?.path } };
|
|
406
|
+
if (b.name === "run_check")
|
|
407
|
+
return { ...b, name: "Bash", input: { command: "npm test" } };
|
|
408
|
+
return b;
|
|
409
|
+
};
|
|
410
|
+
return messages
|
|
411
|
+
.map((m) => JSON.stringify(m.role === "assistant"
|
|
412
|
+
? { type: "assistant", message: { role: "assistant", content: m.content.map(rename) } }
|
|
413
|
+
: { type: "user", message: { role: "user", content: m.content } }))
|
|
414
|
+
.join("\n") + "\n";
|
|
415
|
+
}
|
|
416
|
+
function taskPrompt(task) {
|
|
417
|
+
const list = Object.keys(task.files)
|
|
418
|
+
.sort()
|
|
419
|
+
.map((p) => `- ${p} (${(Buffer.byteLength(task.files[p]) / 1024).toFixed(1)} KB)`)
|
|
420
|
+
.join("\n");
|
|
421
|
+
return `Repository files:\n${list}\n\nTask: ${task.prompt}`;
|
|
422
|
+
}
|
|
423
|
+
function systemFor(arm) {
|
|
424
|
+
if (arm === "rules")
|
|
425
|
+
return `${BASE_SYSTEM}\n\n${SERVER_INSTRUCTIONS}`;
|
|
426
|
+
if (arm === "pack")
|
|
427
|
+
return `${BASE_SYSTEM}\n\n${PACK_RULE}`;
|
|
428
|
+
return BASE_SYSTEM;
|
|
429
|
+
}
|
|
430
|
+
/** The most a request can cost: its prompt written to the cache, and max_tokens of output. */
|
|
431
|
+
function worstCaseUsd(body, pricing) {
|
|
432
|
+
const prompt = estimateTokens(JSON.stringify([body.system, body.tools, body.messages]), "claude") * 1.25; // the estimate's margin
|
|
433
|
+
return (prompt * pricing.inputPerM * CACHE_WRITE_5M + MAX_TOKENS * pricing.outputPerM) / 1e6;
|
|
434
|
+
}
|
|
435
|
+
/** The hidden check: written outside the repository, run with it as the working directory. */
|
|
436
|
+
async function verifyRun(task, run, live) {
|
|
437
|
+
try {
|
|
438
|
+
makeWritable(run.root); // the agent's code may have locked its folders
|
|
439
|
+
const script = join(run.root, "verify.mjs");
|
|
440
|
+
rmSync(script, { force: true, recursive: true });
|
|
441
|
+
writeFileSync(script, abVerifyScript(task), { flag: "wx" });
|
|
442
|
+
const nonce = randomBytes(12).toString("hex");
|
|
443
|
+
const r = await runNode([script, nonce], run.repo, run.home, live);
|
|
444
|
+
return r.code === 0 && r.output.includes(`ab-verify-ok ${nonce}`);
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
return false; // a repository the check cannot even run in has not passed it
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/** A fresh run folder: the repository, and a home for the code it runs. */
|
|
451
|
+
function makeRun(task, live) {
|
|
452
|
+
const root = mkdtempSync(join(tmpdir(), `ctxdoc-ab-${task.id}-`));
|
|
453
|
+
live.roots.add(root);
|
|
454
|
+
const repo = join(root, "repo");
|
|
455
|
+
const home = join(root, "home");
|
|
456
|
+
mkdirSync(home, { recursive: true });
|
|
457
|
+
for (const [p, text] of Object.entries(task.files)) {
|
|
458
|
+
mkdirSync(dirname(join(repo, p)), { recursive: true });
|
|
459
|
+
writeFileSync(join(repo, p), text);
|
|
460
|
+
}
|
|
461
|
+
return { root, repo, home };
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* The verdict on files as they stand, for the tests and the self-check:
|
|
465
|
+
* a fresh run folder with `files`, the hidden check, everything removed.
|
|
466
|
+
*/
|
|
467
|
+
export async function abVerify(task, files = task.files) {
|
|
468
|
+
const live = { children: new Set(), roots: new Set(), timeoutMs: CHECK_TIMEOUT_MS };
|
|
469
|
+
const run = makeRun({ ...task, files }, live);
|
|
470
|
+
try {
|
|
471
|
+
return await verifyRun(task, run, live);
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
removeRoot(run.root, live);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
async function runOne(task, arm, rep, ctx) {
|
|
478
|
+
const started = Date.now();
|
|
479
|
+
const run = { task: task.id, arm, rep, pass: false, stop: "", requests: 0, inputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, outputTokens: 0, costUsd: 0, wallMs: 0, leverUses: 0, leverTokens: 0 };
|
|
480
|
+
const paths = makeRun(task, ctx.live);
|
|
481
|
+
const raw = { messages: { create: (body) => ctx.provider.create(body) } };
|
|
482
|
+
const client = arm === "autoclear" ? withContextDoctor(raw, { clearer: new ColdEveryRequest({ keepRecent: 1, minClearTokens: 1000 }) }) : raw;
|
|
483
|
+
const system = systemFor(arm);
|
|
484
|
+
const tools = arm === "pack" ? [...BASE_TOOLS, PACK_TOOL] : BASE_TOOLS;
|
|
485
|
+
const counts = { pack: 0 };
|
|
486
|
+
/** One request, or undefined when the turn cap or the budget says not to send it. */
|
|
487
|
+
const send = async (messages, extra = {}) => {
|
|
488
|
+
if (run.requests >= ctx.maxTurns) {
|
|
489
|
+
run.stop = "turns";
|
|
490
|
+
return undefined;
|
|
491
|
+
}
|
|
492
|
+
const body = { model: ctx.model, max_tokens: MAX_TOKENS, system, tools, messages, cache_control: { type: "ephemeral" }, ...extra };
|
|
493
|
+
const worst = worstCaseUsd(body, ctx.pricing);
|
|
494
|
+
if (ctx.fatal || ctx.spent + ctx.reserved + worst > ctx.budgetUsd) {
|
|
495
|
+
run.stop = ctx.fatal ? "error" : "budget";
|
|
496
|
+
return undefined;
|
|
497
|
+
}
|
|
498
|
+
ctx.reserved += worst;
|
|
499
|
+
let res;
|
|
500
|
+
try {
|
|
501
|
+
res = await client.messages.create(body);
|
|
502
|
+
}
|
|
503
|
+
finally {
|
|
504
|
+
ctx.reserved -= worst;
|
|
505
|
+
}
|
|
506
|
+
run.requests++;
|
|
507
|
+
const u = res.usage ?? {};
|
|
508
|
+
const n = (v) => (typeof v === "number" && v > 0 ? v : 0);
|
|
509
|
+
run.inputTokens += n(u.input_tokens);
|
|
510
|
+
run.cacheReadTokens += n(u.cache_read_input_tokens);
|
|
511
|
+
run.cacheWriteTokens += n(u.cache_creation_input_tokens);
|
|
512
|
+
run.outputTokens += n(u.output_tokens);
|
|
513
|
+
const cost = usageCost(u, ctx.pricing).totalUsd;
|
|
514
|
+
run.costUsd += cost;
|
|
515
|
+
ctx.spent += cost;
|
|
516
|
+
if (!Array.isArray(res.content))
|
|
517
|
+
throw new Error("the response has no content array");
|
|
518
|
+
return res;
|
|
519
|
+
};
|
|
520
|
+
let messages = [{ role: "user", content: taskPrompt(task) }];
|
|
521
|
+
let compacted = false;
|
|
522
|
+
try {
|
|
523
|
+
try {
|
|
524
|
+
for (;;) {
|
|
525
|
+
const res = await send(messages);
|
|
526
|
+
if (!res)
|
|
527
|
+
break;
|
|
528
|
+
messages.push({ role: "assistant", content: res.content });
|
|
529
|
+
if (res.stop_reason !== "tool_use") {
|
|
530
|
+
run.stop = res.stop_reason ?? "end_turn";
|
|
531
|
+
break;
|
|
532
|
+
}
|
|
533
|
+
const results = [];
|
|
534
|
+
for (const b of res.content.filter((x) => x.type === "tool_use"))
|
|
535
|
+
results.push(await execute(b, paths, task, arm === "pack", counts, ctx.live));
|
|
536
|
+
messages.push({ role: "user", content: results });
|
|
537
|
+
if ((arm === "compact" || arm === "compact-generic") && !compacted && run.requests >= ctx.compactAfter) {
|
|
538
|
+
compacted = true;
|
|
539
|
+
let instructions = "";
|
|
540
|
+
if (arm === "compact") {
|
|
541
|
+
const transcript = join(paths.root, "session.jsonl");
|
|
542
|
+
writeFileSync(transcript, asTranscript(messages));
|
|
543
|
+
instructions = compactInstructions(compactFacts(transcript));
|
|
544
|
+
}
|
|
545
|
+
const ask = [...messages.slice(0, -1), { role: "user", content: [...results, { type: "text", text: instructions ? `${GENERIC_COMPACTION}\n\n${instructions}` : GENERIC_COMPACTION }] }];
|
|
546
|
+
const summary = await send(ask, { tool_choice: { type: "none" } });
|
|
547
|
+
if (!summary)
|
|
548
|
+
break;
|
|
549
|
+
run.leverUses++;
|
|
550
|
+
const text = summary.content.filter((b) => b.type === "text").map((b) => b.text ?? "").join("\n").trim();
|
|
551
|
+
// The session goes on from the summary alone, as after a real compaction.
|
|
552
|
+
messages = [{ role: "user", content: `This session was compacted to save context. Your summary of it:\n\n${text}\n\nContinue the work from here.` }];
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
catch (e) {
|
|
557
|
+
run.stop = "error";
|
|
558
|
+
run.error = e.message.slice(0, 300);
|
|
559
|
+
const status = e.status;
|
|
560
|
+
if (status === 401 || status === 403)
|
|
561
|
+
ctx.fatal ??= run.error;
|
|
562
|
+
}
|
|
563
|
+
run.pass = await verifyRun(task, paths, ctx.live);
|
|
564
|
+
}
|
|
565
|
+
finally {
|
|
566
|
+
removeRoot(paths.root, ctx.live);
|
|
567
|
+
}
|
|
568
|
+
if (arm === "autoclear") {
|
|
569
|
+
const stats = contextDoctorStats(client);
|
|
570
|
+
run.leverUses = stats?.changed ?? 0;
|
|
571
|
+
run.leverTokens = stats?.tokensRemoved ?? 0;
|
|
572
|
+
}
|
|
573
|
+
if (arm === "pack")
|
|
574
|
+
run.leverUses = counts.pack;
|
|
575
|
+
run.wallMs = Date.now() - started;
|
|
576
|
+
return run;
|
|
577
|
+
}
|
|
578
|
+
// -- The suite ---------------------------------------------------------------
|
|
579
|
+
/** The arms a set of levers needs: one shared baseline for rules, autoclear and pack; compact brings its own. */
|
|
580
|
+
export function armsFor(levers) {
|
|
581
|
+
const arms = [];
|
|
582
|
+
if (levers.some((l) => l !== "compact"))
|
|
583
|
+
arms.push("none");
|
|
584
|
+
for (const l of levers) {
|
|
585
|
+
if (l === "compact")
|
|
586
|
+
arms.push("compact-generic", "compact");
|
|
587
|
+
else
|
|
588
|
+
arms.push(l);
|
|
589
|
+
}
|
|
590
|
+
return [...new Set(arms)];
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* A planning figure, not a quote: six requests a run, the task's files in
|
|
594
|
+
* context from the second request on, ~800 output tokens a request (thinking,
|
|
595
|
+
* tool calls, the files the agent writes).
|
|
596
|
+
*/
|
|
597
|
+
export function estimateAb(tasks, arms, repeat, pricing) {
|
|
598
|
+
const R = 6;
|
|
599
|
+
const OUT = 800;
|
|
600
|
+
const base = estimateTokens(BASE_SYSTEM + SERVER_INSTRUCTIONS + JSON.stringify([...BASE_TOOLS, PACK_TOOL]), "claude");
|
|
601
|
+
let expected = 0;
|
|
602
|
+
let upper = 0;
|
|
603
|
+
for (const task of tasks) {
|
|
604
|
+
const files = Object.values(task.files).reduce((n, t) => n + estimateTokens(t, "claude"), 0) + estimateTokens(task.prompt, "claude");
|
|
605
|
+
let context = 0;
|
|
606
|
+
for (let i = 1; i <= R; i++) {
|
|
607
|
+
const next = base + (i >= 2 ? files : 0) + (i - 1) * OUT;
|
|
608
|
+
const fresh = next - context;
|
|
609
|
+
expected += (fresh * pricing.inputPerM * CACHE_WRITE_5M + context * pricing.cacheReadPerM + OUT * pricing.outputPerM) / 1e6;
|
|
610
|
+
upper += (next * pricing.inputPerM + OUT * pricing.outputPerM) / 1e6;
|
|
611
|
+
context = next;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const per = arms.length * repeat;
|
|
615
|
+
return { runs: tasks.length * per, expectedUsd: expected * per, upperUsd: upper * per };
|
|
616
|
+
}
|
|
617
|
+
export async function runAbSuite(options) {
|
|
618
|
+
const model = options.model ?? DEFAULT_AB_MODEL;
|
|
619
|
+
const pricing = exactClaudePricingFor(model);
|
|
620
|
+
if (!pricing)
|
|
621
|
+
throw new Error(`no price is known for ${model} itself: ab needs one to estimate and cap the spend`);
|
|
622
|
+
const tasks = options.tasks ?? AB_TASKS;
|
|
623
|
+
const levers = [...(options.levers ?? AB_LEVERS)];
|
|
624
|
+
const arms = armsFor(levers);
|
|
625
|
+
const repeat = options.repeat ?? 1;
|
|
626
|
+
const ctx = {
|
|
627
|
+
provider: options.provider,
|
|
628
|
+
model,
|
|
629
|
+
pricing,
|
|
630
|
+
maxTurns: options.maxTurns ?? 16,
|
|
631
|
+
budgetUsd: options.budgetUsd ?? Infinity,
|
|
632
|
+
compactAfter: options.compactAfter ?? 2,
|
|
633
|
+
spent: 0,
|
|
634
|
+
reserved: 0,
|
|
635
|
+
live: { children: new Set(), roots: new Set(), timeoutMs: options.checkTimeoutMs ?? CHECK_TIMEOUT_MS },
|
|
636
|
+
};
|
|
637
|
+
// Ctrl-C: nothing of the agent's keeps running, no run folder stays behind.
|
|
638
|
+
const interrupt = (signal) => {
|
|
639
|
+
for (const child of ctx.live.children)
|
|
640
|
+
killTree(child);
|
|
641
|
+
for (const root of [...ctx.live.roots])
|
|
642
|
+
removeRoot(root, ctx.live);
|
|
643
|
+
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
644
|
+
};
|
|
645
|
+
process.once("SIGINT", interrupt);
|
|
646
|
+
process.once("SIGTERM", interrupt);
|
|
647
|
+
const queue = [];
|
|
648
|
+
for (let rep = 1; rep <= repeat; rep++)
|
|
649
|
+
for (const task of tasks)
|
|
650
|
+
for (const arm of arms)
|
|
651
|
+
queue.push({ task, arm, rep });
|
|
652
|
+
const runs = [];
|
|
653
|
+
let next = 0;
|
|
654
|
+
const worker = async () => {
|
|
655
|
+
while (next < queue.length && !ctx.fatal) {
|
|
656
|
+
const { task, arm, rep } = queue[next++];
|
|
657
|
+
const run = await runOne(task, arm, rep, ctx);
|
|
658
|
+
runs.push(run);
|
|
659
|
+
options.onRun?.(run, runs.length, queue.length);
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
try {
|
|
663
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(options.concurrency ?? 4, queue.length)) }, worker));
|
|
664
|
+
}
|
|
665
|
+
finally {
|
|
666
|
+
process.off("SIGINT", interrupt);
|
|
667
|
+
process.off("SIGTERM", interrupt);
|
|
668
|
+
}
|
|
669
|
+
const order = (r) => queue.findIndex((q) => q.task.id === r.task && q.arm === r.arm && q.rep === r.rep);
|
|
670
|
+
runs.sort((a, b) => order(a) - order(b));
|
|
671
|
+
return { model, provider: options.provider.name, tasks: tasks.map((t) => t.id), levers, arms, repeat, runs, spentUsd: ctx.spent, ...(ctx.fatal ? { aborted: `the API refused the key (${ctx.fatal})` } : {}) };
|
|
672
|
+
}
|
|
673
|
+
function totals(runs) {
|
|
674
|
+
return runs.reduce((t, r) => {
|
|
675
|
+
const stopped = STOPPED_EARLY.has(r.stop);
|
|
676
|
+
return {
|
|
677
|
+
runs: t.runs + 1,
|
|
678
|
+
completed: t.completed + (stopped ? 0 : 1),
|
|
679
|
+
passed: t.passed + (!stopped && r.pass ? 1 : 0),
|
|
680
|
+
stoppedEarly: t.stoppedEarly + (stopped ? 1 : 0),
|
|
681
|
+
tokens: t.tokens + r.inputTokens + r.cacheReadTokens + r.cacheWriteTokens + r.outputTokens,
|
|
682
|
+
costUsd: t.costUsd + r.costUsd,
|
|
683
|
+
leverUses: t.leverUses + r.leverUses,
|
|
684
|
+
leverTokens: t.leverTokens + r.leverTokens,
|
|
685
|
+
};
|
|
686
|
+
}, { runs: 0, completed: 0, passed: 0, stoppedEarly: 0, tokens: 0, costUsd: 0, leverUses: 0, leverTokens: 0 });
|
|
687
|
+
}
|
|
688
|
+
/** Per arm: runs, completed runs and their passes, runs stopped early, billed tokens, cost. */
|
|
689
|
+
export function summarizeAb(result) {
|
|
690
|
+
return Object.fromEntries(result.arms.map((arm) => [arm, totals(result.runs.filter((r) => r.arm === arm))]));
|
|
691
|
+
}
|
|
692
|
+
/** Arms every one of whose runs ended on an API error: nothing was measured there. */
|
|
693
|
+
export function erroredArms(result) {
|
|
694
|
+
return result.arms.filter((arm) => {
|
|
695
|
+
const runs = result.runs.filter((r) => r.arm === arm);
|
|
696
|
+
return runs.length > 0 && runs.every((r) => r.stop === "error");
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
const pct = (a, b) => (b > 0 ? `${a >= b ? "+" : ""}${(((a - b) / b) * 100).toFixed(0)}%` : "");
|
|
700
|
+
export function renderAb(result) {
|
|
701
|
+
const out = [];
|
|
702
|
+
out.push(`A/B quality: ${result.tasks.length} tasks, ${result.model}, ${result.repeat} run${result.repeat === 1 ? "" : "s"} per task and arm; ${formatUsd(result.spentUsd)} spent`);
|
|
703
|
+
if (result.aborted)
|
|
704
|
+
out.push(`Stopped early: ${result.aborted}. Runs not started are not in the tables.`);
|
|
705
|
+
const cell = (runs) => {
|
|
706
|
+
const t = totals(runs);
|
|
707
|
+
if (t.runs === 0)
|
|
708
|
+
return "–";
|
|
709
|
+
const verdict = t.runs === 1 ? (STOPPED_EARLY.has(runs[0].stop) ? runs[0].stop.toUpperCase().slice(0, 6) : runs[0].pass ? "PASS" : "FAIL") : `${t.passed}/${t.completed}${t.stoppedEarly ? "*" : ""}`;
|
|
710
|
+
return `${verdict.padEnd(7)}${formatTokens(t.tokens / t.runs).padStart(6)} ${formatUsd(t.costUsd / t.runs).padStart(7)}`;
|
|
711
|
+
};
|
|
712
|
+
const rate = (t) => (t.completed ? t.passed / t.completed : 0);
|
|
713
|
+
for (const lever of result.levers) {
|
|
714
|
+
const { base, arm, what } = LEVER_INFO[lever];
|
|
715
|
+
out.push("", `${lever}: ${what}`);
|
|
716
|
+
out.push(`${"task".padEnd(18)}${base.padEnd(24)}${arm}`);
|
|
717
|
+
for (const id of result.tasks) {
|
|
718
|
+
const of = (a) => result.runs.filter((r) => r.task === id && r.arm === a);
|
|
719
|
+
out.push(`${id.padEnd(18)}${cell(of(base)).padEnd(24)}${cell(of(arm))}`);
|
|
720
|
+
}
|
|
721
|
+
const b = totals(result.runs.filter((r) => r.arm === base));
|
|
722
|
+
const l = totals(result.runs.filter((r) => r.arm === arm));
|
|
723
|
+
out.push(`${"passed".padEnd(18)}${`${b.passed}/${b.completed} completed`.padEnd(24)}${l.passed}/${l.completed} completed`);
|
|
724
|
+
if (b.stoppedEarly + l.stoppedEarly > 0)
|
|
725
|
+
out.push(`${"stopped early".padEnd(18)}${String(b.stoppedEarly).padEnd(24)}${l.stoppedEarly} (API error or refusal, budget, turn or token cap: left out of the pass counts)`);
|
|
726
|
+
out.push(`${"tokens per run".padEnd(18)}${formatTokens(b.runs ? b.tokens / b.runs : 0).padEnd(24)}${formatTokens(l.runs ? l.tokens / l.runs : 0)} (${pct(l.tokens / (l.runs || 1), b.tokens / (b.runs || 1))})`);
|
|
727
|
+
out.push(`${"cost".padEnd(18)}${formatUsd(b.costUsd).padEnd(24)}${formatUsd(l.costUsd)} (${pct(l.costUsd, b.costUsd)})`);
|
|
728
|
+
const used = lever === "autoclear" ? `requests autopilot changed: ${l.leverUses}, tokens it kept off the wire: ${formatTokens(l.leverTokens)}`
|
|
729
|
+
: lever === "pack" ? `pack_context calls: ${l.leverUses}`
|
|
730
|
+
: lever === "compact" ? `compactions: ${b.leverUses} generic, ${l.leverUses} with the hook's instructions`
|
|
731
|
+
: "rules in every request's system prompt";
|
|
732
|
+
out.push(`${"lever".padEnd(18)}${used}`);
|
|
733
|
+
if (b.completed === 0 || l.completed === 0) {
|
|
734
|
+
out.push(`No completed runs on ${b.completed === 0 ? base : arm}: nothing to compare.`);
|
|
735
|
+
}
|
|
736
|
+
else if (b.completed === l.completed) {
|
|
737
|
+
const diff = l.passed - b.passed;
|
|
738
|
+
out.push(diff === 0 ? `Same pass count with and without ${lever} (${l.passed}/${l.completed}).`
|
|
739
|
+
: diff > 0 ? `${diff} more pass${diff === 1 ? "" : "es"} with ${lever} (${l.passed}/${l.completed} vs ${b.passed}/${b.completed}).`
|
|
740
|
+
: `${-diff} fewer pass${diff === -1 ? "" : "es"} with ${lever} (${l.passed}/${l.completed} vs ${b.passed}/${b.completed}): read those runs before trusting the lever.`);
|
|
741
|
+
}
|
|
742
|
+
else {
|
|
743
|
+
const d = rate(l) - rate(b);
|
|
744
|
+
out.push(Math.abs(d) < 1e-9 ? `Same pass rate with and without ${lever} over the completed runs (${l.passed}/${l.completed} vs ${b.passed}/${b.completed}).`
|
|
745
|
+
: `${d > 0 ? "Higher" : "Lower"} pass rate with ${lever} over the completed runs (${l.passed}/${l.completed} vs ${b.passed}/${b.completed})${d < 0 ? ": read those runs before trusting the lever" : ""}.`);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
const dead = erroredArms(result);
|
|
749
|
+
if (dead.length)
|
|
750
|
+
out.push("", `Every run of ${dead.join(", ")} ended on an API error: nothing was measured there.`);
|
|
751
|
+
out.push("", result.repeat < 3 ? "One task's difference is noise at this size: --repeat 3 or more for a figure worth publishing." : `${result.repeat} runs per task and arm.`);
|
|
752
|
+
return out.join("\n");
|
|
753
|
+
}
|
|
754
|
+
/** Why `--out` cannot be written, checked before anything is spent; undefined when it can. */
|
|
755
|
+
function outProblem(out) {
|
|
756
|
+
const path = resolve(out);
|
|
757
|
+
try {
|
|
758
|
+
if (statSync(path).isDirectory())
|
|
759
|
+
return `--out ${out} is a folder`;
|
|
760
|
+
accessSync(path, fsConstants.W_OK);
|
|
761
|
+
return undefined;
|
|
762
|
+
}
|
|
763
|
+
catch (e) {
|
|
764
|
+
if (e.code !== "ENOENT")
|
|
765
|
+
return `--out ${out} cannot be written (${e.message})`;
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
if (!statSync(dirname(path)).isDirectory())
|
|
769
|
+
return `--out ${out}: ${dirname(path)} is not a folder`;
|
|
770
|
+
accessSync(dirname(path), fsConstants.W_OK);
|
|
771
|
+
return undefined;
|
|
772
|
+
}
|
|
773
|
+
catch (e) {
|
|
774
|
+
return `--out ${out} cannot be written (${e.message})`;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* `context-doctor ab`: the exit code. 1 for a refusal, a bad argument, a key
|
|
779
|
+
* the API refused, or an arm all of whose runs ended on an API error.
|
|
780
|
+
*/
|
|
781
|
+
export async function abCommand(o) {
|
|
782
|
+
const say = (line) => (o.json ? console.error(line) : console.log(line));
|
|
783
|
+
if (o.list) {
|
|
784
|
+
console.log("Tasks (each a tiny repository, a smoke test the agent can run, and a hidden check):");
|
|
785
|
+
for (const t of AB_TASKS)
|
|
786
|
+
console.log(` ${t.id.padEnd(16)} ${t.title}${t.bigFile ? ` (big file: ${t.bigFile})` : ""}`);
|
|
787
|
+
console.log("\nLevers (each run against its baseline arm):");
|
|
788
|
+
for (const l of AB_LEVERS)
|
|
789
|
+
console.log(` ${l.padEnd(10)} ${LEVER_INFO[l].what}`);
|
|
790
|
+
return 0;
|
|
791
|
+
}
|
|
792
|
+
const leverNames = (o.levers ?? []).flatMap((l) => l.split(",")).map((l) => l.trim()).filter(Boolean);
|
|
793
|
+
const unknownLever = leverNames.find((l) => l !== "all" && !AB_LEVERS.includes(l));
|
|
794
|
+
if (unknownLever) {
|
|
795
|
+
console.error(`Unknown lever "${unknownLever}". Levers: ${AB_LEVERS.join(", ")}, or all.`);
|
|
796
|
+
return 1;
|
|
797
|
+
}
|
|
798
|
+
const levers = leverNames.length === 0 || leverNames.includes("all") ? [...AB_LEVERS] : [...new Set(leverNames)];
|
|
799
|
+
const taskIds = (o.tasks ?? []).flatMap((t) => t.split(",")).map((t) => t.trim()).filter(Boolean);
|
|
800
|
+
const unknownTask = taskIds.find((id) => !AB_TASKS.some((t) => t.id === id));
|
|
801
|
+
if (unknownTask) {
|
|
802
|
+
console.error(`Unknown task "${unknownTask}". Tasks: ${AB_TASKS.map((t) => t.id).join(", ")} (context-doctor ab --list).`);
|
|
803
|
+
return 1;
|
|
804
|
+
}
|
|
805
|
+
const tasks = taskIds.length ? AB_TASKS.filter((t) => taskIds.includes(t.id)) : AB_TASKS;
|
|
806
|
+
const model = o.model ?? DEFAULT_AB_MODEL;
|
|
807
|
+
const pricing = exactClaudePricingFor(model);
|
|
808
|
+
if (!pricing) {
|
|
809
|
+
console.error(`No price is known for ${model} itself (only a guess from its family, or none), so ab cannot estimate or cap what it spends. Pick a Claude model in the price table (e.g. ${DEFAULT_AB_MODEL}, claude-sonnet-5-5).`);
|
|
810
|
+
return 1;
|
|
811
|
+
}
|
|
812
|
+
if (o.out) {
|
|
813
|
+
const problem = outProblem(o.out);
|
|
814
|
+
if (problem) {
|
|
815
|
+
console.error(`${problem}. Nothing was sent.`);
|
|
816
|
+
return 1;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
const repeat = o.repeat ?? 1;
|
|
820
|
+
const arms = armsFor(levers);
|
|
821
|
+
const est = estimateAb(tasks, arms, repeat, pricing);
|
|
822
|
+
const budget = o.budgetUsd ?? Math.max(1, Math.ceil(est.upperUsd * 1.25));
|
|
823
|
+
const base = (process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com").replace(/\/+$/, "");
|
|
824
|
+
say(`A/B quality suite: ${tasks.length} task${tasks.length === 1 ? "" : "s"} x ${arms.length} arms (${arms.join(", ")}) x ${repeat} = ${est.runs} runs on ${model}`);
|
|
825
|
+
say(`Through the Anthropic Messages API at ${base}${process.env.ANTHROPIC_BASE_URL ? " (ANTHROPIC_BASE_URL)" : ""}.`);
|
|
826
|
+
say(`Estimated cost: ~${formatUsd(est.expectedUsd)} with prompt caching, up to ~${formatUsd(est.upperUsd)} if nothing caches. No request is sent whose worst case would pass ${formatUsd(budget)} (--budget).`);
|
|
827
|
+
const key = process.env.ANTHROPIC_API_KEY;
|
|
828
|
+
if (!key) {
|
|
829
|
+
console.error("ab sends these runs to the Messages API and bills the key in ANTHROPIC_API_KEY, which is not set. Nothing was sent.");
|
|
830
|
+
return 1;
|
|
831
|
+
}
|
|
832
|
+
if (!o.yes) {
|
|
833
|
+
say(`Nothing was sent. Run again with --yes to spend up to ${formatUsd(budget)}.`);
|
|
834
|
+
return 0;
|
|
835
|
+
}
|
|
836
|
+
const result = await runAbSuite({
|
|
837
|
+
provider: anthropicProvider({ apiKey: key }),
|
|
838
|
+
model,
|
|
839
|
+
tasks,
|
|
840
|
+
levers,
|
|
841
|
+
repeat,
|
|
842
|
+
maxTurns: o.maxTurns,
|
|
843
|
+
budgetUsd: budget,
|
|
844
|
+
concurrency: o.concurrency,
|
|
845
|
+
onRun: (r, done, total) => console.error(`[${done}/${total}] ${r.task} · ${r.arm} · ${STOPPED_EARLY.has(r.stop) ? `stopped (${r.stop})` : r.pass ? "PASS" : "FAIL"} · ${r.requests} requests · ${formatTokens(r.inputTokens + r.cacheReadTokens + r.cacheWriteTokens + r.outputTokens)} tokens · ${formatUsd(r.costUsd)}${r.error ? ` · ${r.error}` : ""}`),
|
|
846
|
+
});
|
|
847
|
+
const json = JSON.stringify({ ...result, summary: summarizeAb(result) }, null, 2);
|
|
848
|
+
if (o.out)
|
|
849
|
+
writeFileSync(o.out, json + "\n");
|
|
850
|
+
if (o.json)
|
|
851
|
+
console.log(json);
|
|
852
|
+
else
|
|
853
|
+
console.log("\n" + renderAb(result) + (o.out ? `\n\nEvery run, as JSON: ${o.out}` : ""));
|
|
854
|
+
if (result.aborted)
|
|
855
|
+
console.error(`Stopped: ${result.aborted}.`);
|
|
856
|
+
return result.aborted || erroredArms(result).length > 0 ? 1 : 0;
|
|
857
|
+
}
|