context-doctor 0.35.1 → 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.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The A/B suite's tasks (`context-doctor ab`): small, self-contained coding
3
+ * tasks, each a tiny repository, a request, a visible smoke test and a
4
+ * hidden check. Every file is generated here: no network, no dependencies,
5
+ * nothing from anyone's real sessions.
6
+ *
7
+ * The agent can run the smoke test (`node test.mjs`), which shows that the
8
+ * code loads and runs and gives no expected values. The verdict is `verify`,
9
+ * which the harness runs from outside the repository after the agent stops:
10
+ * the agent can neither read nor run it, so the answers come from the
11
+ * request and the repository's own files, not from a failing assertion.
12
+ *
13
+ * Three tasks keep the facts their solution needs only in a big file: a long
14
+ * format spec (one section of which matters, with an older version's rules
15
+ * as a decoy), a production log with the retry policy in the middle, a
16
+ * design doc. That is where the levers act (pack_context, autopilot's
17
+ * clearing, compaction). The other five are small fixes whose facts are in
18
+ * the request: there a lever should change nothing.
19
+ *
20
+ * `solution` is the reference fix. The agent never sees it: the test suite
21
+ * checks that every fixture fails `verify` and passes it with the solution,
22
+ * and the local mock API writes it to play a model that solves the task.
23
+ */
24
+ export interface AbTask {
25
+ id: string;
26
+ title: string;
27
+ /** The repository: relative path -> content. `test.mjs` is the smoke test and is read-only to the agent. */
28
+ files: Record<string, string>;
29
+ /** What the agent is asked to do. */
30
+ prompt: string;
31
+ /**
32
+ * The hidden check, an ES module body run with the repository as its
33
+ * working directory after a prelude (abVerifyScript) that provides `A`
34
+ * (assert functions captured before any repository code loads) and
35
+ * `load(path)` (import a repository file). Passing = it ran to the end.
36
+ */
37
+ verify: string;
38
+ /** The reference fix: files to write over the fixture. */
39
+ solution: Record<string, string>;
40
+ /** A big file holding facts the solution needs. */
41
+ bigFile?: string;
42
+ }
43
+ /**
44
+ * The hidden check as a script: the prelude, the task's body, and a last
45
+ * line printing `ab-verify-ok <nonce>`, which the harness requires along
46
+ * with exit 0 (an exit code alone could be set by the code under test).
47
+ */
48
+ export declare function abVerifyScript(task: AbTask): string;
49
+ export declare const AB_TASKS: AbTask[];
@@ -0,0 +1,287 @@
1
+ /**
2
+ * The A/B suite's tasks (`context-doctor ab`): small, self-contained coding
3
+ * tasks, each a tiny repository, a request, a visible smoke test and a
4
+ * hidden check. Every file is generated here: no network, no dependencies,
5
+ * nothing from anyone's real sessions.
6
+ *
7
+ * The agent can run the smoke test (`node test.mjs`), which shows that the
8
+ * code loads and runs and gives no expected values. The verdict is `verify`,
9
+ * which the harness runs from outside the repository after the agent stops:
10
+ * the agent can neither read nor run it, so the answers come from the
11
+ * request and the repository's own files, not from a failing assertion.
12
+ *
13
+ * Three tasks keep the facts their solution needs only in a big file: a long
14
+ * format spec (one section of which matters, with an older version's rules
15
+ * as a decoy), a production log with the retry policy in the middle, a
16
+ * design doc. That is where the levers act (pack_context, autopilot's
17
+ * clearing, compaction). The other five are small fixes whose facts are in
18
+ * the request: there a lever should change nothing.
19
+ *
20
+ * `solution` is the reference fix. The agent never sees it: the test suite
21
+ * checks that every fixture fails `verify` and passes it with the solution,
22
+ * and the local mock API writes it to play a model that solves the task.
23
+ */
24
+ /**
25
+ * The hidden check as a script: the prelude, the task's body, and a last
26
+ * line printing `ab-verify-ok <nonce>`, which the harness requires along
27
+ * with exit 0 (an exit code alone could be set by the code under test).
28
+ */
29
+ export function abVerifyScript(task) {
30
+ return [
31
+ 'import assert from "node:assert/strict";',
32
+ 'import { readFileSync } from "node:fs";',
33
+ 'import { pathToFileURL } from "node:url";',
34
+ "// Captured before the code under test loads, so it cannot swap them.",
35
+ "const A = { equal: assert.equal, deepEqual: assert.deepEqual, ok: assert.ok, throws: assert.throws, rejects: assert.rejects, match: assert.match, doesNotMatch: assert.doesNotMatch };",
36
+ "const write = process.stdout.write.bind(process.stdout);",
37
+ "const read = (p) => readFileSync(p, \"utf8\");",
38
+ "const load = (p) => import(pathToFileURL(p).href);",
39
+ task.verify,
40
+ 'write("ab-verify-ok " + process.argv[2] + "\\n");',
41
+ ].join("\n") + "\n";
42
+ }
43
+ /** A smoke test: the module loads and the call runs; no expected values. */
44
+ function smoke(importLine, ...body) {
45
+ return lines(importLine, ...body, 'console.log("smoke ok: the code loads and runs. This test does not check results.");');
46
+ }
47
+ /** Deterministic filler prose: the same words on every machine and run. */
48
+ function filler(seed, sentences) {
49
+ const words = [
50
+ "configuration", "loader", "section", "value", "parser", "release", "operator", "team", "file", "format",
51
+ "history", "comment", "reader", "writer", "legacy", "service", "deployment", "default", "migration", "field",
52
+ "token", "cluster", "region", "backup", "schedule", "policy", "client", "server", "cache", "window",
53
+ "the", "a", "of", "to", "and", "in", "for", "with", "on", "by", "is", "was", "are", "were", "every", "some",
54
+ ];
55
+ let s = seed >>> 0;
56
+ const next = () => (s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32;
57
+ const out = [];
58
+ for (let i = 0; i < sentences; i++) {
59
+ const n = 9 + Math.floor(next() * 12);
60
+ const w = Array.from({ length: n }, () => words[Math.floor(next() * words.length)]);
61
+ out.push(w[0][0].toUpperCase() + w[0].slice(1) + " " + w.slice(1).join(" ") + ".");
62
+ }
63
+ return out.join(" ");
64
+ }
65
+ const lines = (...l) => l.join("\n") + "\n";
66
+ // -- 1. range: an off-by-one and two missing cases --------------------------
67
+ const range = {
68
+ id: "range-inclusive",
69
+ title: "Fix an off-by-one and two edge cases",
70
+ files: {
71
+ "src/range.js": lines("// range(start, end, step): the numbers from start to end.", "export function range(start, end, step = 1) {", " const out = [];", " for (let i = start; i < end; i += step) out.push(i);", " return out;", "}"),
72
+ "test.mjs": smoke('import { range } from "./src/range.js";', "range(0, 1);"),
73
+ },
74
+ prompt: "range(start, end, step) in src/range.js must include `end` when the steps land on it (range(1, 5) is [1, 2, 3, 4, 5]), " +
75
+ "count down when step is negative (range(5, 1, -2) is [5, 3, 1]), return [] when the steps never reach end, and throw a RangeError for step 0. Fix it.",
76
+ verify: lines('const { range } = await load("src/range.js");', "A.deepEqual(range(1, 5), [1, 2, 3, 4, 5]);", "A.deepEqual(range(0, 10, 5), [0, 5, 10]);", "A.deepEqual(range(0, 9, 4), [0, 4, 8]);", "A.deepEqual(range(5, 1, -2), [5, 3, 1]);", "A.deepEqual(range(3, 3), [3]);", "A.deepEqual(range(4, 1), []);", "A.throws(() => range(1, 2, 0), RangeError);"),
77
+ solution: {
78
+ "src/range.js": lines("// range(start, end, step): the numbers from start to end, end included when a step lands on it.", "export function range(start, end, step = 1) {", ' if (step === 0) throw new RangeError("step must not be 0");', " const out = [];", " if (step > 0) for (let i = start; i <= end; i += step) out.push(i);", " else for (let i = start; i >= end; i += step) out.push(i);", " return out;", "}"),
79
+ },
80
+ };
81
+ // -- 2. slugify: implement from rules in the README --------------------------
82
+ const slugify = {
83
+ id: "slugify",
84
+ title: "Implement a function from a short spec",
85
+ files: {
86
+ "README.md": lines("# slugs", "", "`slugify(title)` turns a title into a URL slug:", "", "1. Letters with accents lose them (`Crème` becomes `creme`); everything is lower case.", "2. Every run of characters that are not a-z or 0-9 becomes one `-`.", "3. No `-` at the start or the end.", "4. At most 32 characters. A longer slug is cut back to the last `-` at or before character 32, so no word is cut in half; a slug whose first word is longer than 32 characters is cut at 32.", "5. An empty result is `untitled`."),
87
+ "src/slug.js": lines("export function slugify(title) {", ' throw new Error("not implemented");', "}"),
88
+ "test.mjs": smoke('import { slugify } from "./src/slug.js";', 'if (typeof slugify("A b") !== "string") throw new Error("slugify must return a string");'),
89
+ },
90
+ prompt: "Implement slugify in src/slug.js following the rules in README.md.",
91
+ verify: lines('const { slugify } = await load("src/slug.js");', 'A.equal(slugify("Hello, World!"), "hello-world");', 'A.equal(slugify(" Crème Brûlée -- Recipe "), "creme-brulee-recipe");', 'A.equal(slugify("a___b...c"), "a-b-c");', 'A.equal(slugify("The quick brown fox jumps over the lazy dog"), "the-quick-brown-fox-jumps-over");', 'A.equal(slugify("x".repeat(40)), "x".repeat(32));', 'A.equal(slugify("!!!"), "untitled");', 'A.equal(slugify("Ünïcödé 2026"), "unicode-2026");'),
92
+ solution: {
93
+ "src/slug.js": lines("export function slugify(title) {", ' let s = title.normalize("NFKD").replace(/[\\u0300-\\u036f]/g, "").toLowerCase();', ' s = s.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");', " if (s.length > 32) {", " const cut = s.slice(0, 33).lastIndexOf(\"-\");", " s = cut > 0 ? s.slice(0, cut) : s.slice(0, 32);", " }", ' return s || "untitled";', "}"),
94
+ },
95
+ };
96
+ // -- 3. ini: implement from one section of a long format document ------------
97
+ const formatDoc = [
98
+ "# The KEYFILE format",
99
+ "",
100
+ "This document describes the KEYFILE configuration format used by the deployment tools. Most of it is background; implementers need section 7.",
101
+ "",
102
+ "## 1. History",
103
+ "",
104
+ filler(11, 30),
105
+ "",
106
+ "## 2. Design goals",
107
+ "",
108
+ filler(12, 25),
109
+ "",
110
+ "## 3. Encoding",
111
+ "",
112
+ "Files are UTF-8. " + filler(13, 15),
113
+ "",
114
+ "## 4. Tooling",
115
+ "",
116
+ filler(14, 28),
117
+ "",
118
+ "## 5. Versioning",
119
+ "",
120
+ "Version 1 of the format also allowed `:` in place of `=`, and a comment after a value (`port = 80 ; web port`). Version 2, which this document specifies, allows neither (see section 7). " + filler(15, 20),
121
+ "",
122
+ "## 6. Examples from the field",
123
+ "",
124
+ filler(16, 30),
125
+ "",
126
+ "## 7. Parsing rules",
127
+ "",
128
+ "A parser returns a plain object. Lines are processed in order:",
129
+ "",
130
+ "- Blank lines are ignored. Lines whose first non-space character is `;` or `#` are comments and are ignored. There are no comments after a value.",
131
+ "- `[name]` starts a section: later keys go into `result[name]`. A dotted name `[a.b]` means `result.a.b`, created as nested objects. Spaces inside the brackets around the name are trimmed.",
132
+ "- `key = value` sets a key in the current section; keys before the first section go on the result itself. Key and value are trimmed. Only the first `=` splits; the value may contain more.",
133
+ "- A value wrapped in double quotes keeps its inner spaces and loses the quotes: `name = \" a b \"` is `\" a b \"` without the outer quotes, i.e. ` a b `.",
134
+ "- `true` and `false` become booleans; a value that is an integer (optional `-`, digits only) becomes a number. Everything else stays a string. Quoted values always stay strings.",
135
+ "- A key set twice in one section keeps the last value. A section seen twice continues the first one.",
136
+ "- Any other non-blank line is an error: throw a SyntaxError whose message includes the 1-based line number as `line N`.",
137
+ "",
138
+ "## 8. Security notes",
139
+ "",
140
+ filler(17, 22),
141
+ "",
142
+ "## 9. Frequently asked questions",
143
+ "",
144
+ filler(18, 35),
145
+ "",
146
+ ].join("\n");
147
+ const ini = {
148
+ id: "ini-parser",
149
+ title: "Implement a parser from one section of a long spec",
150
+ bigFile: "docs/FORMAT.md",
151
+ files: {
152
+ "docs/FORMAT.md": formatDoc,
153
+ "src/ini.js": lines("// parseIni(text): parse a KEYFILE document (see docs/FORMAT.md).", "export function parseIni(text) {", ' throw new Error("not implemented");', "}"),
154
+ "test.mjs": smoke('import { parseIni } from "./src/ini.js";', 'const r = parseIni("a = 1");', 'if (!r || typeof r !== "object") throw new Error("parseIni must return an object");'),
155
+ },
156
+ prompt: "Implement parseIni in src/ini.js for the KEYFILE format specified in docs/FORMAT.md.",
157
+ verify: lines('const { parseIni } = await load("src/ini.js");', "const doc = [", ' "; deployment settings",', ' "name = web",', ' "",', ' "[server]",', ' "port = 8080",', ' "host = example.org ",', ' "debug = false",', ' " # an indented comment",', ' "url = http://x/?a=b",', ' "[ db.primary ]",', ' "user = \\" admin \\"",', ' "retries = -3",', ' "ratio = 1.5",', ' "[server]",', ' "port = 9090",', "].join(\"\\n\");", "A.deepEqual(parseIni(doc), {", ' name: "web",', ' server: { port: 9090, host: "example.org", debug: false, url: "http://x/?a=b" },', ' db: { primary: { user: " admin ", retries: -3, ratio: "1.5" } },', "});", 'A.deepEqual(parseIni("[a]\\nflag = true\\nq = \\"42\\""), { a: { flag: true, q: "42" } });', 'A.throws(() => parseIni("[a]\\nok = 1\\nnot a pair"), (e) => e instanceof SyntaxError && /line 3/.test(e.message));', "// Version 1 habits are not version 2: no comment after a value, no `:`.", 'A.deepEqual(parseIni("note = a ; b"), { note: "a ; b" });', 'A.throws(() => parseIni("k: v"), (e) => e instanceof SyntaxError && /line 1/.test(e.message));'),
158
+ solution: {
159
+ "src/ini.js": lines("// parseIni(text): parse a KEYFILE document (see docs/FORMAT.md, section 7).", "export function parseIni(text) {", " const result = {};", " let current = result;", ' text.split("\\n").forEach((raw, i) => {', " const line = raw.trim();", ' if (line === "" || line.startsWith(";") || line.startsWith("#")) return;', " const header = /^\\[(.*)\\]$/.exec(line);", " if (header) {", " current = result;", ' for (const part of header[1].trim().split(".")) current = current[part] ??= {};', " return;", " }", ' const eq = line.indexOf("=");', ' if (eq <= 0) throw new SyntaxError("line " + (i + 1) + ": expected key = value");', " const key = line.slice(0, eq).trim();", " const rawValue = raw.slice(raw.indexOf(\"=\") + 1).trim();", " let value;", ' if (rawValue.length >= 2 && rawValue.startsWith("\\"") && rawValue.endsWith("\\"")) value = rawValue.slice(1, -1);', ' else if (rawValue === "true" || rawValue === "false") value = rawValue === "true";', " else if (/^-?\\d+$/.test(rawValue)) value = Number(rawValue);", " else value = rawValue;", " current[key] = value;", " });", " return result;", "}"),
160
+ },
161
+ };
162
+ // -- 4. retry: a bug the production log points at ---------------------------
163
+ function appLog() {
164
+ const out = [];
165
+ let t = Date.UTC(2026, 9, 20, 8, 0, 0);
166
+ const at = () => new Date((t += 1370)).toISOString();
167
+ const routes = ["/api/orders", "/api/users", "/api/cart", "/health", "/api/search", "/api/invoices"];
168
+ for (let i = 0; i < 300; i++) {
169
+ const r = routes[(i * 7) % routes.length];
170
+ if (i === 150) {
171
+ out.push(`${at()} INFO config service restarted; retry policy: retries=3 means 3 retries after the first attempt (4 attempts in all); the first retry waits baseDelayMs (an option, default 100) and each later one twice as long: 100, 200, 400 ms`);
172
+ }
173
+ if (i % 37 === 11) {
174
+ const id = 4000 + i;
175
+ out.push(`${at()} WARN payments request ${id} to billing failed (503), retrying: attempt=1 delayMs=NaN`);
176
+ out.push(`${at()} WARN payments request ${id} to billing failed (503), retrying: attempt=2 delayMs=NaN`);
177
+ out.push(`${at()} ERROR payments request ${id} gave up after 3 attempts with retries=3; no retry waited (delayMs=NaN)`);
178
+ }
179
+ else {
180
+ out.push(`${at()} INFO http ${r} 200 ${12 + ((i * 13) % 180)}ms user=${1000 + ((i * 31) % 900)}`);
181
+ }
182
+ }
183
+ return out.join("\n") + "\n";
184
+ }
185
+ const retry = {
186
+ id: "retry-backoff",
187
+ title: "Find a bug from a production log",
188
+ bigFile: "logs/app.log",
189
+ files: {
190
+ "logs/app.log": appLog(),
191
+ "src/retry.js": lines("// withRetry(fn, options): call fn until it succeeds, backing off between attempts. options.sleep(ms) is for tests.", "export async function withRetry(fn, options = {}) {", " const retries = options.retries ?? 3;", " const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));", " for (let attempt = 1; ; attempt++) {", " try {", " return await fn(attempt);", " } catch (err) {", " if (attempt >= retries) throw err;", " await sleep(options.baseDelay * 2 ** (attempt - 1));", " }", " }", "}"),
192
+ "test.mjs": smoke('import { withRetry } from "./src/retry.js";', 'if ((await withRetry(async () => 7, { sleep: async () => {} })) !== 7) throw new Error("withRetry must return what fn returns");'),
193
+ },
194
+ prompt: "Billing retries misbehave in production; the service's log is logs/app.log. Fix src/retry.js (the helper every service uses) so it follows the retry policy the service logs.",
195
+ verify: lines('const { withRetry } = await load("src/retry.js");', "const waits = [];", "let calls = 0;", 'const failing = async () => { calls++; throw new Error("503"); };', "await A.rejects(withRetry(failing, { sleep: async (ms) => { waits.push(ms); } }));", "A.equal(calls, 4, \"retries: 3 means 3 retries after the first try\");", "A.deepEqual(waits, [100, 200, 400]);", "waits.length = 0; calls = 0;", 'const flaky = async (n) => { calls++; if (n < 3) throw new Error("503"); return "done"; };', 'A.equal(await withRetry(flaky, { baseDelayMs: 50, sleep: async (ms) => { waits.push(ms); } }), "done");', "A.deepEqual(waits, [50, 100]);", "waits.length = 0; calls = 0;", "await A.rejects(withRetry(failing, { retries: 1, baseDelayMs: 10, sleep: async (ms) => { waits.push(ms); } }));", "A.equal(calls, 2); A.deepEqual(waits, [10]);"),
196
+ solution: {
197
+ "src/retry.js": lines("// withRetry(fn, options): call fn until it succeeds, backing off between attempts. options.sleep(ms) is for tests.", "// Policy: `retries` retries after the first attempt (default 3); waits baseDelayMs (default 100), doubling.", "export async function withRetry(fn, options = {}) {", " const retries = options.retries ?? 3;", " const base = options.baseDelayMs ?? 100;", " const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));", " for (let attempt = 1; ; attempt++) {", " try {", " return await fn(attempt);", " } catch (err) {", " if (attempt > retries) throw err;", " await sleep(base * 2 ** (attempt - 1));", " }", " }", "}"),
198
+ },
199
+ };
200
+ // -- 5. csv: quoted fields --------------------------------------------------
201
+ const csv = {
202
+ id: "csv-quotes",
203
+ title: "Handle quoted fields in a parser",
204
+ files: {
205
+ "src/csv.js": lines("// parseCsvLine(line): the fields of one CSV line (RFC 4180 quoting).", "export function parseCsvLine(line) {", ' return line.split(",");', "}"),
206
+ "test.mjs": smoke('import { parseCsvLine } from "./src/csv.js";', 'if (!Array.isArray(parseCsvLine("a,b"))) throw new Error("parseCsvLine must return an array");'),
207
+ },
208
+ prompt: "parseCsvLine in src/csv.js splits on every comma, which breaks quoted fields. Make it follow RFC 4180 quoting: fields in double quotes may contain commas, and a doubled quote inside them is one quote.",
209
+ verify: lines('const { parseCsvLine } = await load("src/csv.js");', 'A.deepEqual(parseCsvLine("a,b,c"), ["a", "b", "c"]);', 'A.deepEqual(parseCsvLine("\\"x, y\\",z"), ["x, y", "z"]);', 'A.deepEqual(parseCsvLine("\\"say \\"\\"hi\\"\\"\\",2"), ["say \\"hi\\"", "2"]);', 'A.deepEqual(parseCsvLine("a,,c,"), ["a", "", "c", ""]);', 'A.deepEqual(parseCsvLine("\\"\\""), [""]);'),
210
+ solution: {
211
+ "src/csv.js": lines("// parseCsvLine(line): the fields of one CSV line (RFC 4180 quoting).", "export function parseCsvLine(line) {", " const fields = [];", ' let field = "";', " let quoted = false;", " for (let i = 0; i < line.length; i++) {", " const c = line[i];", " if (quoted) {", ' if (c === "\\"" && line[i + 1] === "\\"") { field += "\\""; i++; }', ' else if (c === "\\"") quoted = false;', " else field += c;", ' } else if (c === "\\"") quoted = true;', ' else if (c === ",") { fields.push(field); field = ""; }', " else field += c;", " }", " fields.push(field);", " return fields;", "}"),
212
+ },
213
+ };
214
+ // -- 6. rename across files, keeping a deprecated alias ----------------------
215
+ const rename = {
216
+ id: "rename-export",
217
+ title: "Rename a function across files",
218
+ files: {
219
+ "src/users.js": lines("const USERS = new Map([[1, { id: 1, name: \"Ada\" }], [2, { id: 2, name: \"Lin\" }]]);", "export function getUser(id) {", " return USERS.get(id) ?? null;", "}"),
220
+ "src/api.js": lines('import { getUser } from "./users.js";', "export function handle(id) {", " const user = getUser(id);", " return user ? { status: 200, body: user } : { status: 404 };", "}"),
221
+ "src/report.js": lines('import { getUser } from "./users.js";', "export function names(ids) {", " return ids.map((id) => getUser(id)?.name ?? \"?\").join(\", \");", "}"),
222
+ "test.mjs": smoke('import "./src/users.js";', 'await import("./src/api.js");', 'await import("./src/report.js");'),
223
+ },
224
+ prompt: "Rename getUser to fetchUser in src/users.js and update every caller in src/. Keep getUser exported as an alias that calls fetchUser, marked with a JSDoc @deprecated tag, so outside code keeps working.",
225
+ verify: lines('const users = await load("src/users.js");', 'const { handle } = await load("src/api.js");', 'const { names } = await load("src/report.js");', 'A.equal(typeof users.fetchUser, "function");', 'A.equal(users.fetchUser(1).name, "Ada");', 'A.equal(users.getUser(2).name, "Lin", "getUser stays, as a deprecated alias");', "A.deepEqual(handle(1), { status: 200, body: { id: 1, name: \"Ada\" } });", 'A.equal(names([1, 2, 3]), "Ada, Lin, ?");', 'for (const f of ["src/api.js", "src/report.js"]) A.ok(!/getUser/.test(read(f)), f + " still calls getUser");', 'A.match(read("src/users.js"), /@deprecated/);'),
226
+ solution: {
227
+ "src/users.js": lines("const USERS = new Map([[1, { id: 1, name: \"Ada\" }], [2, { id: 2, name: \"Lin\" }]]);", "export function fetchUser(id) {", " return USERS.get(id) ?? null;", "}", "/** @deprecated Use fetchUser. */", "export function getUser(id) {", " return fetchUser(id);", "}"),
228
+ "src/api.js": lines('import { fetchUser } from "./users.js";', "export function handle(id) {", " const user = fetchUser(id);", " return user ? { status: 200, body: user } : { status: 404 };", "}"),
229
+ "src/report.js": lines('import { fetchUser } from "./users.js";', "export function names(ids) {", " return ids.map((id) => fetchUser(id)?.name ?? \"?\").join(\", \");", "}"),
230
+ },
231
+ };
232
+ // -- 7. a TTL cache from a design doc ----------------------------------------
233
+ const designDoc = [
234
+ "# Cache design",
235
+ "",
236
+ "## Context",
237
+ "",
238
+ filler(21, 25),
239
+ "",
240
+ "## Alternatives considered",
241
+ "",
242
+ "A sliding expiry, where every read extends an entry's lifetime, was considered and rejected: entries that are read often would never expire. " + filler(22, 30),
243
+ "",
244
+ "## Decision: TtlCache",
245
+ "",
246
+ "`new TtlCache({ max, ttlMs, now })` where `now` is a function returning milliseconds (default `Date.now`). Entries expire `ttlMs` after they were last **set** (reading does not extend them).",
247
+ "",
248
+ "- `get(key)`: the value, or `undefined` when absent or expired (an expired entry is removed). A hit makes the entry the most recently used.",
249
+ "- `set(key, value)`: stores it as the most recently used, with a fresh expiry. When that makes more than `max` live entries, remove expired entries first, then the least recently used, until `max` remain.",
250
+ "- `delete(key)`: removes it; returns whether a live entry was removed.",
251
+ "- `size`: a getter, the number of entries that have not expired.",
252
+ "",
253
+ "## Rollout",
254
+ "",
255
+ filler(23, 28),
256
+ "",
257
+ ].join("\n");
258
+ const ttl = {
259
+ id: "ttl-cache",
260
+ title: "Build a small class from a design doc",
261
+ bigFile: "docs/DESIGN.md",
262
+ files: {
263
+ "docs/DESIGN.md": designDoc,
264
+ "src/cache.js": lines("// TtlCache: see docs/DESIGN.md.", "export class TtlCache {", " constructor(options) {", ' throw new Error("not implemented");', " }", "}"),
265
+ "test.mjs": smoke('import { TtlCache } from "./src/cache.js";', 'const c = new TtlCache({ max: 1, ttlMs: 10 });', 'c.set("k", 1);', "c.get(\"k\");"),
266
+ },
267
+ prompt: "Implement TtlCache in src/cache.js as decided in docs/DESIGN.md.",
268
+ verify: lines('const { TtlCache } = await load("src/cache.js");', "let t = 0;", "const c = new TtlCache({ max: 2, ttlMs: 100, now: () => t });", 'c.set("a", 1); c.set("b", 2);', 'A.equal(c.get("a"), 1);', 'c.set("c", 3);', 'A.equal(c.get("b"), undefined, "b was least recently used");', 'A.equal(c.get("a"), 1); A.equal(c.get("c"), 3);', "A.equal(c.size, 2);", "t = 99; A.equal(c.get(\"a\"), 1, \"reading does not extend\");", 't = 100; A.equal(c.get("a"), undefined, "expired at ttlMs");', "A.equal(c.size, 0);", 't = 200; c.set("x", 1); t = 250; c.set("y", 2); t = 301; c.set("z", 3);', 'A.equal(c.get("x"), undefined); A.equal(c.get("y"), 2); A.equal(c.get("z"), 3);', 'A.equal(c.delete("y"), true); A.equal(c.delete("y"), false); A.equal(c.size, 1);'),
269
+ solution: {
270
+ "src/cache.js": lines("// TtlCache: see docs/DESIGN.md.", "export class TtlCache {", " constructor({ max, ttlMs, now = Date.now }) {", " this.max = max; this.ttlMs = ttlMs; this.now = now; this.map = new Map();", " }", " #live(key) {", " const e = this.map.get(key);", " if (!e) return undefined;", " if (this.now() >= e.expires) { this.map.delete(key); return undefined; }", " return e;", " }", " get(key) {", " const e = this.#live(key);", " if (!e) return undefined;", " this.map.delete(key); this.map.set(key, e);", " return e.value;", " }", " set(key, value) {", " this.map.delete(key);", " this.map.set(key, { value, expires: this.now() + this.ttlMs });", " if (this.size <= this.max) return;", " for (const k of [...this.map.keys()]) this.#live(k); // expired entries go first", " while (this.map.size > this.max) this.map.delete(this.map.keys().next().value);", " }", " delete(key) {", " const live = this.#live(key) !== undefined;", " this.map.delete(key);", " return live;", " }", " get size() {", " let n = 0;", " for (const e of this.map.values()) if (this.now() < e.expires) n++;", " return n;", " }", "}"),
271
+ },
272
+ };
273
+ // -- 8. money formatting -----------------------------------------------------
274
+ const money = {
275
+ id: "money-format",
276
+ title: "Fix formatting edge cases",
277
+ files: {
278
+ "src/money.js": lines("// formatMoney(cents, currency): USD $1,234.56, EUR €1.234,56, JPY ¥1,235 (no minor unit).", "export function formatMoney(cents, currency) {", ' const symbol = { USD: "$", EUR: "€", JPY: "¥" }[currency];', " return symbol + (cents / 100).toFixed(2);", "}"),
279
+ "test.mjs": smoke('import { formatMoney } from "./src/money.js";', 'if (typeof formatMoney(100, "USD") !== "string") throw new Error("formatMoney must return a string");'),
280
+ },
281
+ prompt: "formatMoney in src/money.js gets thousands separators, negatives and the yen wrong. USD: $1,234.56 and -$1.00. EUR: €1.234,56 (dots group thousands, comma before cents). JPY has no minor unit, so the amount is whole yen: formatMoney(1235, \"JPY\") is ¥1,235. An unknown currency throws an error naming it. Fix it.",
282
+ verify: lines('const { formatMoney } = await load("src/money.js");', 'A.equal(formatMoney(123456, "USD"), "$1,234.56");', 'A.equal(formatMoney(5, "USD"), "$0.05");', 'A.equal(formatMoney(-100, "USD"), "-$1.00");', 'A.equal(formatMoney(123456789, "EUR"), "€1.234.567,89");', 'A.equal(formatMoney(1235, "JPY"), "¥1,235", "JPY amounts are whole yen: 1235 means ¥1,235");', 'A.equal(formatMoney(0, "EUR"), "€0,00");', 'A.throws(() => formatMoney(1, "XYZ"), /XYZ/);'),
283
+ solution: {
284
+ "src/money.js": lines("// formatMoney(cents, currency): USD $1,234.56, EUR €1.234,56, JPY ¥1,235 (no minor unit).", "const FORMATS = {", ' USD: { symbol: "$", group: ",", decimal: ".", minor: 2 },', ' EUR: { symbol: "€", group: ".", decimal: ",", minor: 2 },', ' JPY: { symbol: "¥", group: ",", decimal: "", minor: 0 },', "};", "export function formatMoney(amount, currency) {", " const f = FORMATS[currency];", ' if (!f) throw new Error("unknown currency " + currency);', " const abs = Math.abs(amount);", " const units = f.minor ? Math.floor(abs / 100) : abs;", ' const grouped = String(units).replace(/\\B(?=(\\d{3})+(?!\\d))/g, f.group);', ' const minor = f.minor ? f.decimal + String(abs % 100).padStart(2, "0") : "";', ' return (amount < 0 ? "-" : "") + f.symbol + grouped + minor;', "}"),
285
+ },
286
+ };
287
+ export const AB_TASKS = [range, slugify, ini, retry, csv, rename, ttl, money];
package/dist/cli.js CHANGED
@@ -22,6 +22,7 @@ import { startProxy } from "./proxy.js";
22
22
  import { runInstall, runUninstall } from "./install.js";
23
23
  import { listSessions, parseSessionFile, pickCurrentSession } from "./session.js";
24
24
  import { runHook } from "./hook.js";
25
+ import { abCommand } from "./ab.js";
25
26
  import { buildImpactReport } from "./impact.js";
26
27
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
27
28
  import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
@@ -58,11 +59,12 @@ const HELP = `context-doctor — profile and optimize LLM context windows
58
59
 
59
60
  Start here:
60
61
  context-doctor install [--statusline] Wire everything it finds: the MCP server (Claude
61
- Desktop, Claude Code, Cursor, Codex, Gemini CLI),
62
- the skill (Claude Code, Codex), the every-prompt
63
- hook (Claude Code, Codex, Gemini CLI's BeforeAgent,
64
- Cursor's postToolUse) and Claude Code's PreCompact
65
- hook, which tells each compaction what to keep
62
+ Desktop, Claude Code, Cursor, Codex, Gemini CLI,
63
+ GitHub Copilot), the skill (Claude Code, Codex), the
64
+ every-prompt hook (Claude Code, Codex, Gemini CLI's
65
+ BeforeAgent, Cursor's postToolUse), Claude Code's
66
+ PreCompact hook, which tells each compaction what to
67
+ keep, and Copilot's sessionStart (the standing rules)
66
68
  context-doctor savings [--days n] [--share [--copy]]
67
69
  What your recent Claude Code sessions cost, and what
68
70
  /compact at cold resumes, autopilot and an earlier
@@ -107,6 +109,13 @@ Measure:
107
109
  context-doctor experiment --task "<t>" Run one task twice from the same commit, in a fresh
108
110
  session and forked from an --existing one; compare
109
111
  bill, cache, time, and whether --check passed
112
+ context-doctor ab [--lever rules|autoclear|pack|compact|all] [--tasks a,b] [--repeat n] [--yes]
113
+ Does a lever cost quality? 8 small coding tasks, each
114
+ run with and without it through the Messages API and
115
+ scored by a hidden check: passes, tokens, cost side by
116
+ side. Bills ANTHROPIC_API_KEY: prints the estimate,
117
+ sends nothing without --yes, never passes --budget usd.
118
+ --list shows the tasks; --model (default claude-opus-5-5)
110
119
 
111
120
  Fix automatically:
112
121
  context-doctor autopilot on|off|pause|resume|status
@@ -153,7 +162,8 @@ Integrations:
153
162
  (chat, agent, batch; no argument lists them)
154
163
 
155
164
  Internal (Claude Code and MCP clients run these for you):
156
- context-doctor hook The every-prompt and PreCompact hook (installed by
165
+ context-doctor hook [copilot] The every-prompt and PreCompact hook; \`hook copilot\`
166
+ is GitHub Copilot's sessionStart (installed by
157
167
  \`install\`; reads hook JSON on stdin)
158
168
  context-doctor statusline Claude Code status bar line: live context size, cache
159
169
  share, cost (wired by \`install --statusline\`; reads
@@ -259,7 +269,7 @@ const COMMANDS = [
259
269
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
260
270
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
261
271
  "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
262
- "reads", "pack", "watch", "help", "version",
272
+ "reads", "pack", "watch", "ab", "help", "version",
263
273
  ];
264
274
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
265
275
  function strategyArg(v) {
@@ -285,6 +295,12 @@ const FLAGS = [
285
295
  { names: ["--check"], value: "text", set: (a, v) => { a.check = v; } },
286
296
  { names: ["--existing"], value: "text", set: (a, v) => { a.existing = v; } },
287
297
  { names: ["--budget"], value: "number", num: { min: 0 }, set: (a, v) => { a.budgetUsd = v; } },
298
+ { names: ["--lever"], value: "text", set: (a, v) => { (a.levers ??= []).push(v); } },
299
+ { names: ["--tasks"], value: "text", set: (a, v) => { (a.abTasks ??= []).push(v); } },
300
+ { names: ["--repeat"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.repeat = v; } },
301
+ { names: ["--max-turns"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTurns = v; } },
302
+ { names: ["--concurrency"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.concurrency = v; } },
303
+ { names: ["--yes"], set: (a) => { a.yes = true; } },
288
304
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
289
305
  { names: ["--copy"], set: (a) => { a.copy = true; } },
290
306
  { names: ["--share"], set: (a) => { a.share = true; } },
@@ -496,7 +512,10 @@ async function main() {
496
512
  return;
497
513
  }
498
514
  if (args.command === "hook") {
499
- void runHook();
515
+ // `hook copilot` is GitHub Copilot's sessionStart; a bare `hook` serves the rest.
516
+ if (args.file !== undefined && args.file !== "copilot")
517
+ usageError(`hook takes no argument, or \`copilot\` (GitHub Copilot's session-start hook); got "${args.file}".`);
518
+ void runHook(args.file === "copilot" ? "copilot" : undefined);
500
519
  return;
501
520
  }
502
521
  if (args.command === "dashboard") {
@@ -540,6 +559,13 @@ async function main() {
540
559
  void runStatusLine();
541
560
  return;
542
561
  }
562
+ if (args.command === "ab") {
563
+ process.exitCode = await abCommand({
564
+ levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
565
+ concurrency: args.concurrency, budgetUsd: args.budgetUsd, yes: args.yes === true, json: args.json, out: args.out, list: args.list,
566
+ });
567
+ return;
568
+ }
543
569
  if (args.command === "experiment") {
544
570
  if (!args.task) {
545
571
  console.error('Usage: context-doctor experiment --task "<what to do>" [--check "<cmd>"] [--existing <session-id>] [--model m] [--budget usd] [--dry-run]');
@@ -0,0 +1,63 @@
1
+ /**
2
+ * GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
3
+ * agent sessions, whose default harness ("Copilot") is the same runtime as
4
+ * the CLI. Checked 2026-10-25 against GitHub's hooks reference
5
+ * (docs.github.com/en/copilot/reference/hooks-reference), VS Code's hooks,
6
+ * harness and MCP pages (code.visualstudio.com, updated 2026-10-21) and the
7
+ * Copilot Chat 0.61.0 extension built into VS Code 1.133:
8
+ *
9
+ * - Hooks: `~/.copilot/hooks/*.json` (or `$COPILOT_HOME/hooks/`), each
10
+ * `{"version": 1, "hooks": {"<event>": [{type, command, timeoutSec}]}}`.
11
+ * VS Code's older "Local" harness reads the same user hook files and
12
+ * accepts the Copilot event names.
13
+ * - Of the events that can add context, none carries a transcript path:
14
+ * `sessionStart` (additionalContext), `postToolUse`, `postToolUseFailure`.
15
+ * A transcript path reaches only agentStop, subagentStart, subagentStop
16
+ * and preCompact, which add nothing to the main agent's context (preCompact
17
+ * is a notification). So the every-prompt size check has nothing to read
18
+ * here, and only the standing rules go in, once per new session.
19
+ * - The Copilot harness reads top-level `additionalContext`; VS Code's Local
20
+ * harness reads `hookSpecificOutput.additionalContext` for SessionStart
21
+ * (seen in the extension's code). The answer carries both, and each
22
+ * harness takes its own.
23
+ * - MCP: `~/.copilot/mcp-config.json` (`$COPILOT_HOME/mcp-config.json`),
24
+ * `{"mcpServers": {name: {type: "local", command, args, tools: ["*"]}}}`.
25
+ * Copilot harness sessions read it directly, in VS Code too, according to
26
+ * VS Code's MCP docs of 2026-10-21 (no file of the installed VS Code 1.133
27
+ * mentions it yet). VS Code's user-profile mcp.json is labelled deprecated
28
+ * there and is forwarded into the same sessions, so it is not written as
29
+ * well; `doctor` warns when it also starts context-doctor, since the tools
30
+ * could then load twice.
31
+ */
32
+ /** Copilot's home: $COPILOT_HOME when set, else ~/.copilot. */
33
+ export declare function copilotHome(): string;
34
+ export declare function copilotMcpConfigPath(): string;
35
+ /** Our own hook file: install creates it, uninstall deletes it. */
36
+ export declare function copilotHookFilePath(): string;
37
+ /** Inline settings Copilot also reads; `disableAllHooks` there turns every hook off. */
38
+ export declare function copilotSettingsPath(): string;
39
+ /** The older settings file; doctor still honours a disableAllHooks there. */
40
+ export declare function copilotLegacyConfigPath(): string;
41
+ /** VS Code's user folders (stable and Insiders): VS Code ships Copilot built in. */
42
+ export declare function vsCodeUserDirs(): string[];
43
+ export declare function vsCodePresent(): boolean;
44
+ /** The one event install registers. */
45
+ export declare const COPILOT_HOOK_EVENT = "sessionStart";
46
+ /** Is this hook-file entry ours? Install writes `<context-doctor> hook copilot`. */
47
+ export declare function isOurCopilotEntry(entry: unknown): boolean;
48
+ /** What a new Copilot session is given: the standing rules, tagged as ours. */
49
+ export declare function copilotSessionContext(): string;
50
+ /**
51
+ * The hook's answer to a session start, or undefined to stay silent for an
52
+ * event other than a session start. A resumed session is answered too: the
53
+ * Copilot runtime keeps sessionStart context in memory and sends it with
54
+ * each turn, and does not restore it on resume (seen in VS Code's bundled
55
+ * runtime, 1.0.73 and 1.0.79), so a resumed session has the rules only if
56
+ * the hook gives them again.
57
+ *
58
+ * Input shapes: the Copilot harness sends camelCase without an event name
59
+ * for camelCase keys ({sessionId, timestamp, cwd, source}); VS Code's Local
60
+ * harness and the Copilot harness's PascalCase aliases send
61
+ * {hook_event_name: "SessionStart", session_id, ...}.
62
+ */
63
+ export declare function copilotSessionStartOutput(input: unknown): string | undefined;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * GitHub Copilot: the Copilot CLI, the GitHub Copilot app, and VS Code's
3
+ * agent sessions, whose default harness ("Copilot") is the same runtime as
4
+ * the CLI. Checked 2026-10-25 against GitHub's hooks reference
5
+ * (docs.github.com/en/copilot/reference/hooks-reference), VS Code's hooks,
6
+ * harness and MCP pages (code.visualstudio.com, updated 2026-10-21) and the
7
+ * Copilot Chat 0.61.0 extension built into VS Code 1.133:
8
+ *
9
+ * - Hooks: `~/.copilot/hooks/*.json` (or `$COPILOT_HOME/hooks/`), each
10
+ * `{"version": 1, "hooks": {"<event>": [{type, command, timeoutSec}]}}`.
11
+ * VS Code's older "Local" harness reads the same user hook files and
12
+ * accepts the Copilot event names.
13
+ * - Of the events that can add context, none carries a transcript path:
14
+ * `sessionStart` (additionalContext), `postToolUse`, `postToolUseFailure`.
15
+ * A transcript path reaches only agentStop, subagentStart, subagentStop
16
+ * and preCompact, which add nothing to the main agent's context (preCompact
17
+ * is a notification). So the every-prompt size check has nothing to read
18
+ * here, and only the standing rules go in, once per new session.
19
+ * - The Copilot harness reads top-level `additionalContext`; VS Code's Local
20
+ * harness reads `hookSpecificOutput.additionalContext` for SessionStart
21
+ * (seen in the extension's code). The answer carries both, and each
22
+ * harness takes its own.
23
+ * - MCP: `~/.copilot/mcp-config.json` (`$COPILOT_HOME/mcp-config.json`),
24
+ * `{"mcpServers": {name: {type: "local", command, args, tools: ["*"]}}}`.
25
+ * Copilot harness sessions read it directly, in VS Code too, according to
26
+ * VS Code's MCP docs of 2026-10-21 (no file of the installed VS Code 1.133
27
+ * mentions it yet). VS Code's user-profile mcp.json is labelled deprecated
28
+ * there and is forwarded into the same sessions, so it is not written as
29
+ * well; `doctor` warns when it also starts context-doctor, since the tools
30
+ * could then load twice.
31
+ */
32
+ import { existsSync } from "node:fs";
33
+ import { homedir, platform } from "node:os";
34
+ import { join } from "node:path";
35
+ import { SERVER_INSTRUCTIONS } from "./rules.js";
36
+ /** Copilot's home: $COPILOT_HOME when set, else ~/.copilot. */
37
+ export function copilotHome() {
38
+ return process.env.COPILOT_HOME || join(homedir(), ".copilot");
39
+ }
40
+ export function copilotMcpConfigPath() {
41
+ return join(copilotHome(), "mcp-config.json");
42
+ }
43
+ /** Our own hook file: install creates it, uninstall deletes it. */
44
+ export function copilotHookFilePath() {
45
+ return join(copilotHome(), "hooks", "context-doctor.json");
46
+ }
47
+ /** Inline settings Copilot also reads; `disableAllHooks` there turns every hook off. */
48
+ export function copilotSettingsPath() {
49
+ return join(copilotHome(), "settings.json");
50
+ }
51
+ /** The older settings file; doctor still honours a disableAllHooks there. */
52
+ export function copilotLegacyConfigPath() {
53
+ return join(copilotHome(), "config.json");
54
+ }
55
+ /** VS Code's user folders (stable and Insiders): VS Code ships Copilot built in. */
56
+ export function vsCodeUserDirs() {
57
+ const base = platform() === "darwin" ? join(homedir(), "Library", "Application Support")
58
+ : platform() === "win32" ? (process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"))
59
+ : join(homedir(), ".config");
60
+ return ["Code", "Code - Insiders"].map((app) => join(base, app, "User"));
61
+ }
62
+ export function vsCodePresent() {
63
+ return vsCodeUserDirs().some((d) => existsSync(d));
64
+ }
65
+ /** The one event install registers. */
66
+ export const COPILOT_HOOK_EVENT = "sessionStart";
67
+ /** Is this hook-file entry ours? Install writes `<context-doctor> hook copilot`. */
68
+ export function isOurCopilotEntry(entry) {
69
+ const e = entry;
70
+ return /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s+copilot\s*$/.test(String(e?.command ?? e?.bash ?? ""));
71
+ }
72
+ /** What a new Copilot session is given: the standing rules, tagged as ours. */
73
+ export function copilotSessionContext() {
74
+ return `<context-doctor>\n${SERVER_INSTRUCTIONS}\n</context-doctor>`;
75
+ }
76
+ /**
77
+ * The hook's answer to a session start, or undefined to stay silent for an
78
+ * event other than a session start. A resumed session is answered too: the
79
+ * Copilot runtime keeps sessionStart context in memory and sends it with
80
+ * each turn, and does not restore it on resume (seen in VS Code's bundled
81
+ * runtime, 1.0.73 and 1.0.79), so a resumed session has the rules only if
82
+ * the hook gives them again.
83
+ *
84
+ * Input shapes: the Copilot harness sends camelCase without an event name
85
+ * for camelCase keys ({sessionId, timestamp, cwd, source}); VS Code's Local
86
+ * harness and the Copilot harness's PascalCase aliases send
87
+ * {hook_event_name: "SessionStart", session_id, ...}.
88
+ */
89
+ export function copilotSessionStartOutput(input) {
90
+ const obj = input && typeof input === "object" && !Array.isArray(input) ? input : {};
91
+ const event = obj.hook_event_name;
92
+ if (event !== undefined && event !== "SessionStart" && event !== "sessionStart")
93
+ return undefined;
94
+ const context = copilotSessionContext();
95
+ return JSON.stringify({ additionalContext: context, hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context } });
96
+ }