context-doctor 0.35.1 → 0.37.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";
@@ -54,15 +55,17 @@ import { planCache, renderCachePlan } from "./cacheplan.js";
54
55
  import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
55
56
  import { renderPayback, subagentPayback } from "./subagentpay.js";
56
57
  import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
58
+ import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
57
59
  const HELP = `context-doctor — profile and optimize LLM context windows
58
60
 
59
61
  Start here:
60
62
  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
63
+ Desktop, Claude Code, Cursor, Codex, Gemini CLI,
64
+ GitHub Copilot), the skill (Claude Code, Codex), the
65
+ every-prompt hook (Claude Code, Codex, Gemini CLI's
66
+ BeforeAgent, Cursor's postToolUse), Claude Code's
67
+ PreCompact hook, which tells each compaction what to
68
+ keep, and Copilot's sessionStart (the standing rules)
66
69
  context-doctor savings [--days n] [--share [--copy]]
67
70
  What your recent Claude Code sessions cost, and what
68
71
  /compact at cold resumes, autopilot and an earlier
@@ -107,6 +110,13 @@ Measure:
107
110
  context-doctor experiment --task "<t>" Run one task twice from the same commit, in a fresh
108
111
  session and forked from an --existing one; compare
109
112
  bill, cache, time, and whether --check passed
113
+ context-doctor ab [--lever rules|autoclear|pack|compact|all] [--tasks a,b] [--repeat n] [--yes]
114
+ Does a lever cost quality? 8 small coding tasks, each
115
+ run with and without it through the Messages API and
116
+ scored by a hidden check: passes, tokens, cost side by
117
+ side. Bills ANTHROPIC_API_KEY: prints the estimate,
118
+ sends nothing without --yes, never passes --budget usd.
119
+ --list shows the tasks; --model (default claude-opus-5-5)
110
120
 
111
121
  Fix automatically:
112
122
  context-doctor autopilot on|off|pause|resume|status
@@ -142,6 +152,10 @@ Fix on request:
142
152
  Where an Anthropic request should carry cache_control,
143
153
  what it saves over n calls; --out writes it applied
144
154
  (top-level automatic caching unless --explicit)
155
+ context-doctor handoff [list|show <id>|latest] [--copy]
156
+ Handoffs saved from chat apps (the \`handoff\` prompt or
157
+ save_handoff): list them, print one, or --copy it to
158
+ paste as the first message of a new chat
145
159
 
146
160
  Integrations:
147
161
  context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
@@ -153,7 +167,8 @@ Integrations:
153
167
  (chat, agent, batch; no argument lists them)
154
168
 
155
169
  Internal (Claude Code and MCP clients run these for you):
156
- context-doctor hook The every-prompt and PreCompact hook (installed by
170
+ context-doctor hook [copilot] The every-prompt and PreCompact hook; \`hook copilot\`
171
+ is GitHub Copilot's sessionStart (installed by
157
172
  \`install\`; reads hook JSON on stdin)
158
173
  context-doctor statusline Claude Code status bar line: live context size, cache
159
174
  share, cost (wired by \`install --statusline\`; reads
@@ -259,7 +274,7 @@ const COMMANDS = [
259
274
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
260
275
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
261
276
  "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "subagents", "tasks",
262
- "reads", "pack", "watch", "help", "version",
277
+ "reads", "pack", "watch", "ab", "handoff", "help", "version",
263
278
  ];
264
279
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
265
280
  function strategyArg(v) {
@@ -285,6 +300,12 @@ const FLAGS = [
285
300
  { names: ["--check"], value: "text", set: (a, v) => { a.check = v; } },
286
301
  { names: ["--existing"], value: "text", set: (a, v) => { a.existing = v; } },
287
302
  { names: ["--budget"], value: "number", num: { min: 0 }, set: (a, v) => { a.budgetUsd = v; } },
303
+ { names: ["--lever"], value: "text", set: (a, v) => { (a.levers ??= []).push(v); } },
304
+ { names: ["--tasks"], value: "text", set: (a, v) => { (a.abTasks ??= []).push(v); } },
305
+ { names: ["--repeat"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.repeat = v; } },
306
+ { names: ["--max-turns"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTurns = v; } },
307
+ { names: ["--concurrency"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.concurrency = v; } },
308
+ { names: ["--yes"], set: (a) => { a.yes = true; } },
288
309
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
289
310
  { names: ["--copy"], set: (a) => { a.copy = true; } },
290
311
  { names: ["--share"], set: (a) => { a.share = true; } },
@@ -318,6 +339,9 @@ const FLAGS = [
318
339
  { names: ["--upstream-google"], value: "text", set: (a, v) => { a.upstreamGoogle = v; } },
319
340
  // Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
320
341
  { names: ["--http"], set: () => { } },
342
+ { names: ["--store-handoffs"], set: () => { } },
343
+ { names: ["--allowed-hosts"], value: "text", set: () => { } },
344
+ { names: ["--allowed-origins"], value: "text", set: () => { } },
321
345
  ];
322
346
  const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
323
347
  const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
@@ -496,7 +520,10 @@ async function main() {
496
520
  return;
497
521
  }
498
522
  if (args.command === "hook") {
499
- void runHook();
523
+ // `hook copilot` is GitHub Copilot's sessionStart; a bare `hook` serves the rest.
524
+ if (args.file !== undefined && args.file !== "copilot")
525
+ usageError(`hook takes no argument, or \`copilot\` (GitHub Copilot's session-start hook); got "${args.file}".`);
526
+ void runHook(args.file === "copilot" ? "copilot" : undefined);
500
527
  return;
501
528
  }
502
529
  if (args.command === "dashboard") {
@@ -540,6 +567,13 @@ async function main() {
540
567
  void runStatusLine();
541
568
  return;
542
569
  }
570
+ if (args.command === "ab") {
571
+ process.exitCode = await abCommand({
572
+ levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
573
+ concurrency: args.concurrency, budgetUsd: args.budgetUsd, yes: args.yes === true, json: args.json, out: args.out, list: args.list,
574
+ });
575
+ return;
576
+ }
543
577
  if (args.command === "experiment") {
544
578
  if (!args.task) {
545
579
  console.error('Usage: context-doctor experiment --task "<what to do>" [--check "<cmd>"] [--existing <session-id>] [--model m] [--budget usd] [--dry-run]');
@@ -832,6 +866,47 @@ async function main() {
832
866
  }
833
867
  return;
834
868
  }
869
+ if (args.command === "handoff") {
870
+ // Read-only: handoffs are written by the MCP server's save_handoff.
871
+ const sub = args.file ?? "list";
872
+ if (sub === "list") {
873
+ const metas = listHandoffs();
874
+ console.log(args.json ? JSON.stringify(metas, null, 2) : renderHandoffList(metas));
875
+ return;
876
+ }
877
+ const id = sub === "show" ? args.positionals?.[1] : sub === "latest" || isHandoffId(sub) ? sub : undefined;
878
+ if (!id) {
879
+ console.error(sub === "show"
880
+ ? "Usage: context-doctor handoff show <id> (the ids are in `context-doctor handoff list`)."
881
+ : `Usage: context-doctor handoff [list | show <id> | latest] [--copy] [--json]; got "${sub}".`);
882
+ process.exitCode = 1;
883
+ return;
884
+ }
885
+ const h = readHandoff(id);
886
+ if (!h) {
887
+ console.error(id === "latest"
888
+ ? "No handoffs saved yet. In a long chat, pick the `handoff` prompt (Claude Desktop's + menu) or ask for a handoff."
889
+ : `No saved handoff "${id}". List them: ${selfCommand("handoff list")}`);
890
+ process.exitCode = 1;
891
+ return;
892
+ }
893
+ if (args.json) {
894
+ console.log(JSON.stringify({ ...h.meta, markdown: h.markdown }, null, 2));
895
+ return;
896
+ }
897
+ // Control characters out before anything reaches a terminal or the
898
+ // clipboard: a hand-edited or older file could carry escape sequences.
899
+ const markdown = stripControls(h.markdown);
900
+ if (args.copy) {
901
+ const copied = copyToClipboard(markdown);
902
+ console.log(copied
903
+ ? `Copied handoff ${h.meta.id} (~${formatTokens(h.meta.tokens)} tokens). Paste it as the first message of a new chat.`
904
+ : `No clipboard tool found; copy the handoff below by hand.\n\n${markdown}`);
905
+ return;
906
+ }
907
+ process.stdout.write(markdown);
908
+ return;
909
+ }
835
910
  if (args.command === "instructions") {
836
911
  console.log(renderPreferences(args.copy ? copyToClipboard(CHAT_PREFERENCES) : undefined));
837
912
  return;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Compact tool results: a short text, the detail as `structuredContent`, and
3
+ * presentation-only data in `_meta`.
4
+ *
5
+ * Why: every byte of a tool result is re-read on every later turn of the chat.
6
+ * profile_context's full report (bars, message previews) and pack_context's
7
+ * outline (one line per chunk, the heading path repeated on each) are mostly
8
+ * presentation. ChatGPT surfaces `content` and `structuredContent` to the
9
+ * model and keeps `_meta` for the widget only (developers.openai.com/plugins/reference,
10
+ * "Tool results"), so the compact form puts one line of text and
11
+ * the decision-relevant fields in front of the model, and the rest where only
12
+ * a widget would read it.
13
+ *
14
+ * Not the default: a client that ignores `structuredContent` would lose the
15
+ * detail. The server sends this form to ChatGPT (recognised by the
16
+ * `openai/session` or `openai/subject` request metadata, the anonymized
17
+ * conversation and user ids it attaches to tool calls) or when
18
+ * CONTEXT_DOCTOR_RESULTS=compact; everything else gets the full text, as
19
+ * before. Measured sizes are in ROADMAP.md ("Desktop chat apps").
20
+ */
21
+ import type { ContextProfile } from "./profile.js";
22
+ import type { SketchProfile } from "./sketch.js";
23
+ import type { PackResult } from "./pack.js";
24
+ export type ResultMode = "full" | "compact";
25
+ export interface CompactResult {
26
+ text: string;
27
+ structured: Record<string, unknown>;
28
+ meta: Record<string, unknown>;
29
+ }
30
+ export declare function resultMode(requestMeta: unknown, env?: NodeJS.ProcessEnv): ResultMode;
31
+ /** profile_context on a conversation. */
32
+ export declare function compactProfile(p: ContextProfile, fullText: string): CompactResult;
33
+ /** profile_context on a chat-app sketch. */
34
+ export declare function compactSketch(p: SketchProfile, fullText: string): CompactResult;
35
+ /** pack_context with no query: sections instead of one line per chunk. */
36
+ export declare function compactOutline(r: PackResult, fullText: string, maxSections?: number): CompactResult;