@handfly/sandbox 0.0.0-stage → 0.1.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/dist/items.js ADDED
@@ -0,0 +1,983 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { GraphView, fingerprint, seededShuffle } from "@handfly/itemgen";
5
+ import { SandboxUnavailable, detectRuntime, imageDigest, run } from "./driver.js";
6
+ import { prepareNode, preparePython, snapshot } from "./env.js";
7
+ import { mutantsFor, pythonMutants, syntacticallyValid } from "./mutate.js";
8
+ import { changedLines, patchBudget } from "./local.js";
9
+ import { pythonContract } from "./contract.js";
10
+ import { RACE_INITIAL, parseRaceOutput, pythonRaces, raceScript, simulateRace } from "./race.js";
11
+ import { VULN_CLASSES, pythonVulnMutants } from "./security.js";
12
+ import { runHarness, runPytest, runQueryCapture, runVitest } from "./pytest.js";
13
+ /** Header line of each context-code section in a query-count item's evidence: `⟦FILE path:start⟧`. */
14
+ export const QUERY_SECTION = (path, start) => `⟦FILE ${path}:${start}⟧`;
15
+ /** Marker for the blank in cloze items; the web renders an input in its place. */
16
+ export const CLOZE_BLANK = "⟦BLANK⟧";
17
+ /** One-tap cause categories for failure triage, by mutation operator. */
18
+ const CAUSE = {
19
+ negate_condition: "condition", swap_bool_op: "condition", off_by_one: "boundary", early_return: "early_return",
20
+ missing_await: "async", remove_transaction: "transaction",
21
+ };
22
+ const CAUSES = ["condition", "boundary", "early_return", "async", "transaction"];
23
+ const IO_TAGS = ["orm.read", "orm.write", "orm.write.untyped", "http.client", "io", "cache", "celery.enqueue", "sleep", "storage"];
24
+ function pyRootFor(root, path) {
25
+ let d = dirname(path);
26
+ while (d && d !== ".") {
27
+ if (["manage.py", "pyproject.toml", "setup.py", "pytest.ini", "setup.cfg"].some((m) => existsSync(join(root, d, m))))
28
+ return d;
29
+ d = dirname(d);
30
+ }
31
+ return "";
32
+ }
33
+ function pytestId(n, pyRoot) {
34
+ const parts = (n.local ?? n.name).split(".");
35
+ const path = pyRoot && n.path.startsWith(`${pyRoot}/`) ? n.path : n.path;
36
+ return `${path}::${parts.join("::")}`;
37
+ }
38
+ /** Tests that reach `key` through calls/tests within 3 hops (closest first). */
39
+ function testsReaching(g, key, max = 20) {
40
+ const out = [];
41
+ let frontier = [key];
42
+ const seen = new Set(frontier);
43
+ for (let d = 0; d < 3 && frontier.length && out.length < max; d++) {
44
+ const next = [];
45
+ for (const k of frontier) {
46
+ for (const e of g.inn.get(k) ?? []) {
47
+ if (seen.has(e.from) || !(e.kind === "calls" || e.kind === "tests"))
48
+ continue;
49
+ seen.add(e.from);
50
+ const n = g.node(e.from);
51
+ if (n.kind === "test")
52
+ out.push(n);
53
+ else
54
+ next.push(e.from);
55
+ }
56
+ }
57
+ frontier = next;
58
+ }
59
+ return out.slice(0, max);
60
+ }
61
+ function sliceLines(text, start, end) {
62
+ return text.split("\n").slice(start - 1, end).join("\n");
63
+ }
64
+ /** Parameter names of a Python def (shown so the learner knows what to pass; names only, no defaults or values). */
65
+ function paramsOf(source, n) {
66
+ const head = source.split("\n").slice(n.span[0] - 1, n.span[0] + 4).join(" ");
67
+ const m = /def\s+\w+\s*\(([^)]*)\)/.exec(head);
68
+ if (!m)
69
+ return [];
70
+ return m[1].split(",").map((p) => p.trim().split(/[:=]/)[0].trim().replace(/^\*+/, "")).filter((p) => p && p !== "self" && p !== "cls");
71
+ }
72
+ export function display(canon) {
73
+ if (canon.startsWith("RAISES:"))
74
+ return `raises ${canon.slice(7)}`;
75
+ const v = JSON.parse(canon.slice(3));
76
+ const r = (x) => x && typeof x === "object" && !Array.isArray(x)
77
+ ? "__decimal__" in x ? x.__decimal__ : "__float__" in x ? x.__float__ : "__repr__" in x ? x.__repr__
78
+ : `{${Object.entries(x).map(([k, y]) => `'${k}': ${r(y)}`).join(", ")}}`
79
+ : Array.isArray(x) ? `[${x.map(r).join(", ")}]` : typeof x === "string" ? `'${x}'` : x === null ? "None" : x === true ? "True" : x === false ? "False" : String(x);
80
+ return r(v);
81
+ }
82
+ /**
83
+ * Seeded bugs (F-301) and output prediction (F-302), both verified by execution in the sandbox.
84
+ * Python only in v1. Returns nothing (and says why) when Docker is unavailable.
85
+ */
86
+ export async function buildExecutionItems(index, root, workDir, opts = {}) {
87
+ const log = [];
88
+ const say = (s) => { log.push(s); opts.onLog?.(s); };
89
+ const res = { specs: [], local: {}, recipes: {}, regen: {}, log };
90
+ try {
91
+ await detectRuntime();
92
+ }
93
+ catch (e) {
94
+ if (e instanceof SandboxUnavailable) {
95
+ say(e.message);
96
+ return res;
97
+ }
98
+ throw e;
99
+ }
100
+ const g = new GraphView(index);
101
+ const snap = snapshot(root, workDir, index.snapshot);
102
+ const envs = new Map();
103
+ const envFor = async (pyRoot) => {
104
+ if (!envs.has(pyRoot))
105
+ envs.set(pyRoot, await preparePython(root, pyRoot));
106
+ return envs.get(pyRoot);
107
+ };
108
+ const baseline = new Map();
109
+ // ---- Seeded bugs ---------------------------------------------------------
110
+ const bugTargets = index.nodes
111
+ .filter((n) => n.language === "python" && (n.kind === "function" || n.kind === "method" || n.kind === "view") && (n.criticality ?? 0) >= 25 && n.loc >= 3 && n.loc <= 80)
112
+ .map((n) => ({ n, tests: testsReaching(g, n.key) }))
113
+ .filter((x) => x.tests.length > 0)
114
+ .sort((a, b) => (b.n.criticality ?? 0) - (a.n.criticality ?? 0));
115
+ for (const { n, tests } of bugTargets) {
116
+ if (res.specs.filter((s) => s.type === "seeded_bug").length >= (opts.maxBugs ?? 12))
117
+ break;
118
+ const pyRoot = pyRootFor(root, n.path);
119
+ const env = await envFor(pyRoot);
120
+ const ids = [...new Set(tests.map((t) => pytestId(t, pyRoot)))];
121
+ const bkey = ids.join("|");
122
+ if (!baseline.has(bkey)) {
123
+ const b = await runPytest(env, snap, ids);
124
+ baseline.set(bkey, b.passed);
125
+ if (!b.passed)
126
+ say(`baseline tests fail for ${n.name}; skipping planted bugs there`);
127
+ }
128
+ if (!baseline.get(bkey))
129
+ continue;
130
+ const source = readFileSync(join(root, n.path), "utf8");
131
+ res.regen[n.id] = {
132
+ kind: "regen", path: n.path, qual: n.local ?? n.name, pyRoot, snapshot: index.snapshot,
133
+ sourceSha: createHash("sha256").update(source).digest("hex"), span: [n.span[0], n.span[1]], tests: ids,
134
+ };
135
+ const mutants = (await pythonMutants(n.path, source, n.span[0], n.span[1])).slice(0, 8);
136
+ // Killed mutants become different questions, never the same bug twice. Formats rotate across functions (function
137
+ // i starts at format i mod 4) so every format appears even when each function has only a few killed mutants;
138
+ // a format that does not fit this mutant (no assertion text for triage, a long span for cloze) falls back to a bug.
139
+ const formats = ["bug", "triage", "cloze", "fix"];
140
+ const rot = bugTargets.findIndex((x) => x.n.key === n.key);
141
+ let kept = 0;
142
+ const killedHere = [];
143
+ for (const m of mutants) {
144
+ if (kept >= formats.length)
145
+ break;
146
+ if (!(await syntacticallyValid(source, m)))
147
+ continue;
148
+ const r = await runPytest(env, snap, ids, { path: n.path, text: m.text, workDir });
149
+ if (r.passed || r.result.timedOut || r.failed.length === 0)
150
+ continue; // survived: a test gap, not an item
151
+ killedHere.push(m);
152
+ const delta = m.text.split("\n").length - source.split("\n").length;
153
+ const mutated = {
154
+ path: n.path, start_line: n.span[0], end_line: n.span[1] + delta, text: sliceLines(m.text, n.span[0], n.span[1] + delta),
155
+ };
156
+ const format = formats[(rot + kept) % formats.length];
157
+ kept++;
158
+ if (format === "triage") {
159
+ const evidence = failureEvidence(r.result.stdout);
160
+ if (evidence) {
161
+ const spec = triageSpec(g, n, m, r.failed, evidence);
162
+ res.specs.push(spec);
163
+ res.local[spec.fingerprint] = { ...mutated, evidence };
164
+ continue;
165
+ }
166
+ }
167
+ if (format === "cloze") {
168
+ const cz = clozeSpec(g, n, source, m, mutants);
169
+ if (cz) {
170
+ res.specs.push(cz.spec);
171
+ res.local[cz.spec.fingerprint] = cz.fragment;
172
+ continue;
173
+ }
174
+ }
175
+ // Fix it only when the smallest fix (undoing the plant) fits the patch budget: a removed `with` block re-indents
176
+ // its whole body, and asking for that as a "small fix" would grade a correct answer as a rewrite.
177
+ if (format === "fix" && changedLines(mutated.text.split("\n"), sliceLines(source, n.span[0], n.span[1]).split("\n")) <= patchBudget(n.loc)) {
178
+ const spec = fixBugSpec(g, n, m, r.failed);
179
+ res.specs.push(spec);
180
+ res.local[spec.fingerprint] = mutated;
181
+ res.recipes[spec.fingerprint] = {
182
+ kind: "fix_bug", path: n.path, qual: n.local ?? n.name, pyRoot, snapshot: index.snapshot,
183
+ sourceSha: createHash("sha256").update(source).digest("hex"), mutant: { start: m.start, end: m.end, replacement: m.replacement },
184
+ span: [n.span[0], n.span[1] + delta], tests: ids,
185
+ };
186
+ continue;
187
+ }
188
+ const bug = await bugSpec(g, n, m, r.failed, env, importLine(n, pyRoot));
189
+ res.specs.push(bug);
190
+ res.local[bug.fingerprint] = mutated;
191
+ // M1: the "write a test that catches it" step runs on the learner's machine: it must pass on the original
192
+ // code and fail with the planted bug.
193
+ res.recipes[bug.fingerprint] = {
194
+ kind: "bug_test", path: n.path, qual: n.local ?? n.name, pyRoot, snapshot: index.snapshot,
195
+ sourceSha: createHash("sha256").update(source).digest("hex"), mutant: { start: m.start, end: m.end, replacement: m.replacement },
196
+ testDir: dirname(join(pyRoot, r.failed[0].split("::")[0])), // pytest reports ids relative to pyRoot
197
+ };
198
+ // F-305: the same verified defect as an agent diff to review, and its fix as a diff to approve.
199
+ for (const reviewSpec of diffReviewSpecs(g, n, source, m, r.failed)) {
200
+ res.specs.push(reviewSpec.spec);
201
+ res.local[reviewSpec.spec.fingerprint] = reviewSpec.fragment;
202
+ }
203
+ }
204
+ // Faded Parsons (N9): this function's lines shuffled, plus a mutated line the tests reject as a distractor.
205
+ // Any arrangement the tests accept is right, so the check runs on the learner's machine.
206
+ if (killedHere.length && res.specs.filter((s) => s.type === "parsons").length < (opts.maxParsons ?? 2)) {
207
+ const pz = parsonsBlocks(source, n, killedHere);
208
+ if (pz) {
209
+ const spec = parsonsSpec(g, n, pz);
210
+ res.specs.push(spec);
211
+ res.local[spec.fingerprint] = { path: n.path, start_line: n.span[0], end_line: n.span[0] + pz.lines.length - 1, text: pz.lines.join("\n") };
212
+ res.recipes[spec.fingerprint] = {
213
+ kind: "parsons", path: n.path, qual: n.local ?? n.name, pyRoot, snapshot: index.snapshot,
214
+ sourceSha: createHash("sha256").update(source).digest("hex"), span: [n.span[0], n.span[1]], tests: ids, blocks: pz.lines,
215
+ };
216
+ }
217
+ }
218
+ }
219
+ // ---- TypeScript planted bugs (vitest) ---------------------------------------
220
+ const nodeEnvs = new Map();
221
+ const jsRootFor = (p) => {
222
+ let d = dirname(p);
223
+ while (d && d !== ".") {
224
+ if (existsSync(join(root, d, "package.json")))
225
+ return d;
226
+ d = dirname(d);
227
+ }
228
+ return existsSync(join(root, "package.json")) ? "" : null;
229
+ };
230
+ const tsTargets = index.nodes
231
+ .filter((n) => n.language !== "python" && ["function", "method", "hook"].includes(n.kind) && (n.criticality ?? 0) >= 20 && n.loc >= 3 && n.loc <= 80)
232
+ .map((n) => ({ n, tests: testsReaching(g, n.key) }))
233
+ .filter((x) => x.tests.length > 0)
234
+ .sort((a, b) => (b.n.criticality ?? 0) - (a.n.criticality ?? 0));
235
+ for (const { n, tests } of tsTargets) {
236
+ if (res.specs.filter((s) => s.type === "seeded_bug" && !s.fragment.path.endsWith(".py")).length >= (opts.maxBugs ?? 12) / 2)
237
+ break;
238
+ const jsRoot = jsRootFor(n.path);
239
+ if (jsRoot === null)
240
+ continue;
241
+ if (!nodeEnvs.has(jsRoot)) {
242
+ try {
243
+ nodeEnvs.set(jsRoot, await prepareNode(root, jsRoot));
244
+ }
245
+ catch (e) {
246
+ say(`could not prepare node deps in ${jsRoot || "."}: ${e.message.slice(0, 120)}`);
247
+ continue;
248
+ }
249
+ }
250
+ const env = nodeEnvs.get(jsRoot);
251
+ const files = [...new Set(tests.map((t) => t.path))];
252
+ const bkey = `js|${files.join("|")}`;
253
+ if (!baseline.has(bkey)) {
254
+ const b = await runVitest(env, snap, files);
255
+ baseline.set(bkey, b.passed);
256
+ if (!b.passed)
257
+ say(`baseline vitest fails for ${n.name}; skipping`);
258
+ }
259
+ if (!baseline.get(bkey))
260
+ continue;
261
+ const source = readFileSync(join(root, n.path), "utf8");
262
+ let kept = 0;
263
+ for (const m of (await mutantsFor(n.path, source, n.span[0], n.span[1])).slice(0, 8)) {
264
+ if (kept >= 2)
265
+ break;
266
+ if (!(await syntacticallyValid(source, m)))
267
+ continue;
268
+ const r = await runVitest(env, snap, files, { path: n.path, text: m.text, workDir });
269
+ if (r.passed || r.result.timedOut || r.failed.length === 0)
270
+ continue;
271
+ kept++;
272
+ const bug = await bugSpec(g, n, m, r.failed, { image: env.image, pyRoot: "" });
273
+ res.specs.push(bug);
274
+ const delta = m.text.split("\n").length - source.split("\n").length;
275
+ res.local[bug.fingerprint] = {
276
+ path: n.path, start_line: n.span[0], end_line: n.span[1] + delta, text: sliceLines(m.text, n.span[0], n.span[1] + delta),
277
+ };
278
+ for (const rs of diffReviewSpecs(g, n, source, m, r.failed)) {
279
+ res.specs.push(rs.spec);
280
+ res.local[rs.spec.fingerprint] = rs.fragment;
281
+ }
282
+ }
283
+ }
284
+ // ---- Output prediction ---------------------------------------------------
285
+ const callsByTarget = new Map();
286
+ for (const f of index.files) {
287
+ if (f.language !== "python")
288
+ continue;
289
+ for (const c of f.calls) {
290
+ if (!c.args || !c.inDef)
291
+ continue;
292
+ const name = c.callee.split(".").pop();
293
+ const arr = callsByTarget.get(name) ?? [];
294
+ if (!arr.includes(c.args))
295
+ arr.push(c.args);
296
+ callsByTarget.set(name, arr);
297
+ }
298
+ }
299
+ const pure = index.nodes.filter((n) => n.language === "python" && n.kind === "function" && n.complexity >= 2 && n.loc <= 60 && !n.tags.some((t) => IO_TAGS.includes(t)) &&
300
+ !n.tags.includes("async") && (callsByTarget.get(n.name)?.length ?? 0) > 0);
301
+ for (const n of pure) {
302
+ if (res.specs.filter((s) => s.type === "output_prediction").length >= (opts.maxPredictions ?? 12))
303
+ break;
304
+ const pyRoot = pyRootFor(root, n.path);
305
+ const env = await envFor(pyRoot);
306
+ const source = readFileSync(join(root, n.path), "utf8");
307
+ const mutants = (await pythonMutants(n.path, source, n.span[0], n.span[1])).slice(0, 10);
308
+ for (const args of callsByTarget.get(n.name).slice(0, 3)) {
309
+ const a = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`);
310
+ const b = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`);
311
+ if (!a || a !== b)
312
+ continue; // nondeterministic or not runnable
313
+ const outs = new Set();
314
+ const killers = []; // mutants this input tells apart from the original: provably killable
315
+ for (const m of mutants) {
316
+ if (outs.size >= 3)
317
+ break;
318
+ if (!(await syntacticallyValid(source, m)))
319
+ continue;
320
+ const o = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`, { path: n.path, text: m.text, workDir });
321
+ if (o && o !== a && display(o) !== display(a)) {
322
+ outs.add(display(o));
323
+ killers.push(m);
324
+ }
325
+ }
326
+ res.specs.push(predictionSpec(g, n, args, display(a), [...outs], env));
327
+ const base = { path: n.path, qual: n.local ?? n.name, pyRoot, snapshot: index.snapshot, sourceSha: createHash("sha256").update(source).digest("hex") };
328
+ const params = paramsOf(source, n);
329
+ // Kill the mutant: the learner writes a call + expected value that passes on the original and fails on this change.
330
+ if (killers[0]) {
331
+ const m = killers[0];
332
+ const delta = m.text.split("\n").length - source.split("\n").length;
333
+ const diff = unifiedDiff(n.path, source, m.text, n.span[0], n.span[1], n.span[1] + delta);
334
+ const spec = killMutantSpec(g, n, m, params, args);
335
+ res.specs.push(spec);
336
+ res.local[spec.fingerprint] = { path: n.path, start_line: n.span[0], end_line: n.span[0] + diff.split("\n").length - 1, text: diff };
337
+ res.recipes[spec.fingerprint] = { kind: "kill_mutant", ...base, mutant: { start: m.start, end: m.end, replacement: m.replacement } };
338
+ }
339
+ // Make it happen: an input that makes the function return a value seen for ANOTHER real call (not the one the
340
+ // prediction item shows), so the answer cannot be copied from a sibling question.
341
+ for (const other of callsByTarget.get(n.name).filter((x) => x !== args).slice(0, 2)) {
342
+ const o1 = await runHarness(env, snap, n.path, n.local ?? n.name, `(${other},)`);
343
+ const o2 = await runHarness(env, snap, n.path, n.local ?? n.name, `(${other},)`);
344
+ if (!o1 || o1 !== o2 || display(o1) === display(a))
345
+ continue;
346
+ const spec = reverseTraceSpec(g, n, params, display(o1), other);
347
+ res.specs.push(spec);
348
+ res.local[spec.fingerprint] = { path: n.path, start_line: n.span[0], end_line: n.span[1], text: sliceLines(source, n.span[0], n.span[1]) };
349
+ res.recipes[spec.fingerprint] = { kind: "reverse_trace", ...base };
350
+ break;
351
+ }
352
+ // State at a checkpoint (F3): same input, a tracer snapshot inside the call, run twice for determinism.
353
+ const t1 = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`, undefined, { trace: true });
354
+ const t2 = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`, undefined, { trace: true });
355
+ if (t1 && t1 === t2 && t1 !== "TRACE:null") {
356
+ const cp = JSON.parse(t1.slice(6));
357
+ if (cp.line >= n.span[0] && cp.line <= n.span[1])
358
+ res.specs.push(stateTraceSpec(g, n, args, cp));
359
+ }
360
+ // Which one behaves differently (N7): a refactor the tests and every known input agree is safe, next to a
361
+ // near-identical change this input proves wrong. The learner picks the broken one and gives an input that shows it.
362
+ if (killers[0] && res.specs.filter((s) => s.type === "spot_difference").length < (opts.maxSpot ?? 3)) {
363
+ const broken = killers[0];
364
+ for (const safe of safeRefactors(source, n, broken)) {
365
+ let same = true;
366
+ for (const x of callsByTarget.get(n.name).slice(0, 4)) {
367
+ const o = await runHarness(env, snap, n.path, n.local ?? n.name, `(${x},)`);
368
+ const r = await runHarness(env, snap, n.path, n.local ?? n.name, `(${x},)`, { path: n.path, text: safe.text, workDir });
369
+ if (!o || o !== r) {
370
+ same = false;
371
+ break;
372
+ }
373
+ }
374
+ const reach = testsReaching(g, n.key).map((t) => pytestId(t, pyRoot));
375
+ if (same && reach.length)
376
+ same = (await runPytest(env, snap, [...new Set(reach)], { path: n.path, text: safe.text, workDir })).passed;
377
+ if (!same)
378
+ continue;
379
+ const dSafe = unifiedDiff(n.path, source, safe.text, n.span[0], n.span[1], n.span[1] + safe.text.split("\n").length - source.split("\n").length);
380
+ const dBroken = unifiedDiff(n.path, source, broken.text, n.span[0], n.span[1], n.span[1] + broken.text.split("\n").length - source.split("\n").length);
381
+ const spec = spotSpec(g, n, broken, safe.kind, params);
382
+ const brokenFirst = spec.expected.broken === "A";
383
+ const [a1, b1] = brokenFirst ? [dBroken, dSafe] : [dSafe, dBroken];
384
+ res.specs.push(spec);
385
+ res.local[spec.fingerprint] = {
386
+ path: n.path, start_line: n.span[0], end_line: n.span[1], text: sliceLines(source, n.span[0], n.span[1]),
387
+ evidence: `⟦VERSION A⟧\n${a1}\n⟦VERSION B⟧\n${b1}`,
388
+ };
389
+ res.recipes[spec.fingerprint] = { kind: "kill_mutant", ...base, mutant: { start: broken.start, end: broken.end, replacement: broken.replacement } };
390
+ break;
391
+ }
392
+ }
393
+ break;
394
+ }
395
+ }
396
+ // ---- Cost scale (N10) ----------------------------------------------------
397
+ // Every list argument of a real call stretched to 10, 100 and 1000 items; the hottest line's count fits a class.
398
+ for (const n of pure) {
399
+ if (res.specs.filter((s) => s.type === "cost_scale").length >= (opts.maxCost ?? 3))
400
+ break;
401
+ const env = await envFor(pyRootFor(root, n.path));
402
+ for (const args of callsByTarget.get(n.name).filter((x) => x.includes("[")).slice(0, 2)) {
403
+ const cnt = async (k) => {
404
+ const r = await runHarness(env, snap, n.path, n.local ?? n.name, `(${args},)`, undefined, { count: true, scale: k });
405
+ return r?.startsWith("COUNT:") ? JSON.parse(r.slice(6)) : null;
406
+ };
407
+ const c10 = await cnt(10), c100 = await cnt(100), again = await cnt(100), c1000 = await cnt(1000);
408
+ if (!c10 || !c100 || !c1000 || JSON.stringify(c100) !== JSON.stringify(again))
409
+ continue;
410
+ const fit = costClass(c10, c100, c1000, n.span[0]);
411
+ if (fit) {
412
+ res.specs.push(costScaleSpec(g, n, args, fit));
413
+ break;
414
+ }
415
+ }
416
+ }
417
+ // ---- Find the vulnerability (N8) ------------------------------------------
418
+ // One protection removed (an object-level permission, an owner filter, query parameters, HTML escaping, a
419
+ // basename): structurally a known vulnerability class that the original code is not. Shown in the smallest
420
+ // function or class that contains it; graded on the line and the class.
421
+ const vulnFiles = [...new Set(index.nodes.filter((n) => n.language === "python" && n.kind !== "test" && !/(^|\/)tests?\//.test(n.path)).map((n) => n.path))].sort();
422
+ for (const path of vulnFiles) {
423
+ if (res.specs.filter((s) => s.type === "find_vuln").length >= (opts.maxVulns ?? 4))
424
+ break;
425
+ const source = readFileSync(join(root, path), "utf8");
426
+ const lines = source.split("\n").length;
427
+ for (const m of await pythonVulnMutants(path, source, 1, lines)) {
428
+ if (res.specs.filter((s) => s.type === "find_vuln").length >= (opts.maxVulns ?? 4))
429
+ break;
430
+ if (!(await syntacticallyValid(source, m)))
431
+ continue;
432
+ const host = index.nodes
433
+ .filter((n) => n.path === path && ["class", "function", "method", "view"].includes(n.kind) && n.span[0] <= m.line && n.span[1] >= m.line && n.loc <= 80)
434
+ .sort((a, b) => a.loc - b.loc)[0];
435
+ if (!host)
436
+ continue;
437
+ const delta = m.text.split("\n").length - lines;
438
+ const spec = vulnSpec(g, host, m);
439
+ if (res.specs.some((s) => s.fingerprint === spec.fingerprint))
440
+ continue;
441
+ res.specs.push(spec);
442
+ res.local[spec.fingerprint] = {
443
+ path, start_line: host.span[0], end_line: host.span[1] + delta, text: sliceLines(m.text, host.span[0], host.span[1] + delta),
444
+ };
445
+ }
446
+ }
447
+ // ---- Can it be None? (N11) ------------------------------------------------
448
+ // Read from the code (no execution): which path returns None, if any. "Yes" needs the proving line; "no" items are
449
+ // kept to about one in four so that answering "no" is not a strategy.
450
+ const contractNodes = index.nodes
451
+ .filter((n) => n.language === "python" && (n.kind === "function" || n.kind === "method") && n.loc >= 3 && n.loc <= 40 && !/(^|\/)tests?\//.test(n.path))
452
+ .sort((a, b) => (b.criticality ?? 0) - (a.criticality ?? 0) || a.key.localeCompare(b.key));
453
+ let yes = 0, no = 0;
454
+ for (const n of contractNodes) {
455
+ if (yes + no >= (opts.maxContracts ?? 4))
456
+ break;
457
+ const source = readFileSync(join(root, n.path), "utf8");
458
+ const c = await pythonContract(source, n.span[0], n.span[1]);
459
+ if (!c || (!c.canBeNone && no >= Math.max(1, Math.floor(yes / 3))))
460
+ continue;
461
+ const spec = contractSpec(g, n, c);
462
+ res.specs.push(spec);
463
+ res.local[spec.fingerprint] = { path: n.path, start_line: n.span[0], end_line: n.span[1], text: sliceLines(source, n.span[0], n.span[1]) };
464
+ if (c.canBeNone)
465
+ yes++;
466
+ else
467
+ no++;
468
+ }
469
+ // ---- Schedule the race (N12) --------------------------------------------
470
+ // Only where the detector finds a read-modify-write across an await, or an ORM update without select_for_update.
471
+ // The two-task model is reproduced with real asyncio tasks in the sandbox: a serial schedule must keep the
472
+ // invariant and an interleaved one must lose an update, or the item is not asked.
473
+ const raceNodes = index.nodes
474
+ .filter((n) => n.language === "python" && (n.kind === "function" || n.kind === "method" || n.kind === "view") && n.loc >= 3 && n.loc <= 80 && !/(^|\/)tests?\//.test(n.path))
475
+ .sort((a, b) => (b.criticality ?? 0) - (a.criticality ?? 0) || a.key.localeCompare(b.key));
476
+ let races = 0;
477
+ for (const n of raceNodes) {
478
+ if (races >= (opts.maxRaces ?? 2))
479
+ break;
480
+ const source = readFileSync(join(root, n.path), "utf8");
481
+ const model = pythonRaces(source, n.span[0], n.span[1])[0];
482
+ if (!model)
483
+ continue;
484
+ const env = await envFor(pyRootFor(root, n.path));
485
+ const exec = async (schedule) => parseRaceOutput((await run({ image: env.image, cmd: ["python", "-c", raceScript(model.delta, schedule)], timeoutSeconds: 10 })).stdout);
486
+ const serial = await exec(["A", "A", "B", "B"]);
487
+ const lost = await exec(["A", "B", "A", "B"]);
488
+ const expected = RACE_INITIAL + 2 * model.delta;
489
+ if (serial !== expected || lost === null || lost === expected || lost !== simulateRace(model.delta, ["A", "B", "A", "B"]).final)
490
+ continue;
491
+ const spec = raceSpec(g, n, model, lost);
492
+ res.specs.push(spec);
493
+ res.local[spec.fingerprint] = { path: n.path, start_line: n.span[0], end_line: n.span[1], text: sliceLines(source, n.span[0], n.span[1]) };
494
+ races++;
495
+ }
496
+ // ---- How many queries? (N6) ---------------------------------------------
497
+ // Django tests that drive the test client run with the query-capture plugin, twice; a request whose count
498
+ // differs between runs is discarded. One question per view and method, the request with the most queries first.
499
+ const clientTests = index.nodes.filter((n) => n.language === "python" && n.kind === "test");
500
+ const byRoot = new Map();
501
+ for (const t of clientTests) {
502
+ const text = readFileSync(join(root, t.path), "utf8");
503
+ if (!/\b(?:self\.)?client\.(?:get|post|put|patch|delete)\(/.test(text))
504
+ continue;
505
+ const pyRoot = pyRootFor(root, t.path);
506
+ if (!byRoot.has(pyRoot))
507
+ byRoot.set(pyRoot, new Set());
508
+ byRoot.get(pyRoot).add(t.path);
509
+ }
510
+ const seenViews = new Set();
511
+ for (const [pyRoot, files] of byRoot) {
512
+ if (res.specs.filter((s) => s.type === "query_count").length >= (opts.maxQueries ?? 4))
513
+ break;
514
+ const env = await envFor(pyRoot);
515
+ const ids = [...files].sort();
516
+ const a = await runQueryCapture(env, snap, ids);
517
+ const b = a && (await runQueryCapture(env, snap, ids));
518
+ if (!a || !b) {
519
+ say(`query capture produced nothing in ${pyRoot || "."}`);
520
+ continue;
521
+ }
522
+ const repoPath = (p) => (pyRoot ? `${pyRoot}/${p}` : p);
523
+ for (const nid of Object.keys(a).sort()) {
524
+ if (res.specs.filter((s) => s.type === "query_count").length >= (opts.maxQueries ?? 4))
525
+ break;
526
+ const ta = a[nid], tb = b[nid];
527
+ if (!tb || !ta.test?.span || tb.requests.length !== ta.requests.length)
528
+ continue;
529
+ const stable = ta.requests.filter((r, i) => r.count === tb.requests[i].count && r.line && r.view?.span && (r.status ?? 500) < 500);
530
+ const pick = stable.sort((x, y) => y.count - x.count)[0];
531
+ if (!pick || pick.count < 1)
532
+ continue;
533
+ const vkey = `${pick.view.name}|${pick.view.action}|${pick.method}`;
534
+ if (seenViews.has(vkey))
535
+ continue;
536
+ const vspan = pick.view.span;
537
+ const vpath = repoPath(vspan.path);
538
+ const viewNode = index.nodes.find((n) => n.path === vpath && n.span[0] <= vspan.start && n.span[1] >= vspan.end && n.kind !== "module")
539
+ ?? index.nodes.find((n) => n.path === vpath && n.kind !== "module");
540
+ if (!viewNode)
541
+ continue;
542
+ const tspan = ta.test.span;
543
+ const testText = sliceLines(readFileSync(join(root, repoPath(tspan.path)), "utf8"), tspan.start, tspan.end);
544
+ // Context code the count depends on, besides the view: the test that sets up the data, and (DRF) the
545
+ // serializer with its nested serializers. Sections are marked so the player can show each with its own path.
546
+ const sections = [{ path: repoPath(tspan.path), start: tspan.start, text: testText }];
547
+ const ser = pick.view.serializer;
548
+ if (ser && !(repoPath(ser.path) === repoPath(pick.view.span.path) && ser.start >= pick.view.span.start && ser.end <= pick.view.span.end)) {
549
+ sections.push({ path: repoPath(ser.path), start: ser.start, text: sliceLines(readFileSync(join(root, repoPath(ser.path)), "utf8"), ser.start, ser.end) });
550
+ }
551
+ const evidence = sections.map((x) => `${QUERY_SECTION(x.path, x.start)}\n${x.text}`).join("\n");
552
+ if (evidence.length > 4000)
553
+ continue;
554
+ const viewSource = readFileSync(join(root, vpath), "utf8");
555
+ const viewText = sliceLines(viewSource, vspan.start, vspan.end);
556
+ seenViews.add(vkey);
557
+ const spec = queryCountSpec(g, viewNode, ta.test.name, repoPath(tspan.path), tspan.start, pick, viewText);
558
+ res.specs.push(spec);
559
+ res.local[spec.fingerprint] = { path: vpath, start_line: vspan.start, end_line: vspan.end, text: viewText, evidence };
560
+ }
561
+ }
562
+ const count = (t, ts = false) => res.specs.filter((s) => s.type === t && (!ts || !s.fragment.path.endsWith(".py"))).length;
563
+ say(`sandbox: ${count("kill_mutant")} kill-the-mutant, ${count("reverse_trace")} make-it-happen, ${count("seeded_bug")} planted bugs (${count("seeded_bug", true)} TypeScript), ${count("agent_diff_review")} diff reviews, ${count("output_prediction")} predictions, ${count("state_trace")} checkpoints, ${count("failure_triage")} triage, ${count("cloze")} cloze, ${count("fix_bug")} fix-it, ${count("query_count")} query counts, ${count("find_vuln")} vulnerabilities, ${count("cost_scale")} cost scales, ${count("spot_difference")} spot-the-difference, ${count("parsons")} Parsons, ${count("null_contract")} contracts`);
564
+ return res;
565
+ }
566
+ /** A minimal unified diff of one function, original vs changed, with real line numbers. */
567
+ export function unifiedDiff(path, before, after, start, end, endAfter) {
568
+ const a = before.split("\n").slice(start - 1, end);
569
+ const b = after.split("\n").slice(start - 1, endAfter);
570
+ const out = [`--- a/${path}`, `+++ b/${path}`, `@@ -${start},${a.length} +${start},${b.length} @@`];
571
+ let i = 0;
572
+ let j = 0;
573
+ while (i < a.length || j < b.length) {
574
+ if (i < a.length && j < b.length && a[i] === b[j]) {
575
+ out.push(` ${a[i]}`);
576
+ i++;
577
+ j++;
578
+ }
579
+ else {
580
+ // find the next resync point (small functions: a simple greedy scan is enough)
581
+ let k = j;
582
+ while (k < b.length && b[k] !== a[i])
583
+ k++;
584
+ if (i < a.length && k < b.length && k - j <= 3) {
585
+ while (j < k)
586
+ out.push(`+${b[j++]}`);
587
+ }
588
+ else {
589
+ if (i < a.length)
590
+ out.push(`-${a[i++]}`);
591
+ if (j < b.length && (i >= a.length || b[j] !== a[i]))
592
+ out.push(`+${b[j++]}`);
593
+ }
594
+ }
595
+ }
596
+ return out.join("\n");
597
+ }
598
+ /** 0-based indexes of the added or removed rows of a unified diff (headers excluded). */
599
+ export function changedRows(diff) {
600
+ return diff.split("\n").flatMap((l, i) => (/^[+-]/.test(l) && !/^(\+\+\+|---) /.test(l) ? [i] : []));
601
+ }
602
+ function diffReviewSpecs(g, n, source, m, failing) {
603
+ const delta = m.text.split("\n").length - source.split("\n").length;
604
+ const breaking = unifiedDiff(n.path, source, m.text, n.span[0], n.span[1], n.span[1] + delta);
605
+ const fixing = unifiedDiff(n.path, m.text, source, n.span[0], n.span[1] + delta, n.span[1]);
606
+ const ref = `${n.language === "python" ? "pytest" : "vitest"}:${createHash("sha256").update(failing.join("\n")).digest("hex").slice(0, 16)}`;
607
+ const concepts = g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "testing.regression-tests", weight: 0.5 }];
608
+ const make = (kind, diff) => {
609
+ const fp = fingerprint({ type: "agent_diff_review", site: n.key, mutant: m.id, kind });
610
+ const spec = {
611
+ fingerprint: fp, template_key: "agent_diff_review.comment", type: "agent_diff_review", concepts,
612
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: kind === "breaking" ? 0.55 : 0.5,
613
+ grading_method: "decision",
614
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref, failing_tests: failing.slice(0, 5) } },
615
+ voice_compatible: false, est_seconds: 120,
616
+ // M2: besides the decision, the reviewer marks diff rows (GitHub-style line comments). Rows are 0-based indexes
617
+ // into the diff text; the changed rows are the defect (breaking) or the fix (fixing).
618
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, choices: ["approve", "request_changes", "reject"], comment_rows: true, diff_rows: diff.split("\n").length },
619
+ expected: kind === "breaking"
620
+ ? { acceptable: ["request_changes", "reject"], defect_line: m.line, defect_rows: changedRows(diff), review_mode: "comments", failing_tests: failing.slice(0, 5) }
621
+ : { acceptable: ["approve"], fixes_line: m.line, fix_rows: changedRows(diff), review_mode: "comments" },
622
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
623
+ };
624
+ return { spec, fragment: { path: n.path, start_line: n.span[0], end_line: n.span[0] + diff.split("\n").length - 1, text: diff } };
625
+ };
626
+ return [make("breaking", breaking), make("fixing", fixing)];
627
+ }
628
+ /** The import a learner's test needs: `from orders.pricing import line_total` (the class, for a method). */
629
+ function importLine(n, pyRoot) {
630
+ if (!n.path.endsWith(".py"))
631
+ return null;
632
+ let rel = pyRoot && n.path.startsWith(`${pyRoot}/`) ? n.path.slice(pyRoot.length + 1) : n.path;
633
+ if (rel.startsWith("src/"))
634
+ rel = rel.slice(4);
635
+ const mod = rel.replace(/\.py$/, "").replace(/\/__init__$/, "").split("/").join(".");
636
+ const top = (n.local ?? n.name).split(".")[0];
637
+ return /^[\w.]+$/.test(mod) && /^\w+$/.test(top) ? `from ${mod} import ${top}` : null;
638
+ }
639
+ async function bugSpec(g, n, m, failing, env, testImport = null) {
640
+ const fp = fingerprint({ type: "seeded_bug", site: n.key, mutant: m.id });
641
+ const ref = `${n.language === "python" ? "pytest" : "vitest"}:${createHash("sha256").update(failing.join("\n")).digest("hex").slice(0, 16)}`;
642
+ return {
643
+ fingerprint: fp,
644
+ template_key: "seeded_bug.locate",
645
+ type: "seeded_bug",
646
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "testing.regression-tests", weight: 0.5 }],
647
+ component_node_id: n.id,
648
+ criticality: n.criticality ?? 0,
649
+ difficulty: 0.6,
650
+ grading_method: "line_locate",
651
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref, failing_tests: failing.slice(0, 5), image: (await imageDigest(env.image)).slice(0, 19) } },
652
+ voice_compatible: false,
653
+ est_seconds: 180,
654
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line_count: n.loc, ...(testImport ? { test_check: true, test_import: testImport } : {}) },
655
+ expected: { line: m.line, operator: m.operator, failing_tests: failing.slice(0, 5) },
656
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
657
+ };
658
+ }
659
+ function predictionSpec(g, n, args, correct, distractors, env) {
660
+ const fp = fingerprint({ type: "output_prediction", site: n.key, input: args });
661
+ const ref = `harness:${createHash("sha256").update(`${n.key}|${args}|${correct}|${env.image}`).digest("hex").slice(0, 16)}`;
662
+ const choiceMode = distractors.length >= 2;
663
+ const choices = choiceMode ? seededShuffle([correct, ...distractors.slice(0, 3)], fp) : undefined;
664
+ return {
665
+ fingerprint: fp,
666
+ template_key: "output_prediction.call",
667
+ type: "output_prediction",
668
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "python.control-flow", weight: 0.6 }],
669
+ component_node_id: n.id,
670
+ criticality: n.criticality ?? 0,
671
+ difficulty: choiceMode ? 0.45 : 0.6,
672
+ grading_method: "exact_output",
673
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref } },
674
+ voice_compatible: choiceMode,
675
+ est_seconds: choiceMode ? 60 : 90,
676
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, call: `${n.name}(${args})`, ...(choices ? { choices } : {}) },
677
+ expected: { output: correct, ...(choices ? { choices, correct_choice: choices.indexOf(correct) } : {}) },
678
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
679
+ };
680
+ }
681
+ /** The first failure's section of `pytest --tb=short` output: frames and the assertion, capped at 3.5 KB. */
682
+ export function failureEvidence(stdout) {
683
+ const lines = stdout.replace(/\x1b\[[0-9;]*m/g, "").split("\n");
684
+ const start = lines.findIndex((l) => /^_{3,} .+ _{3,}$/.test(l));
685
+ if (start < 0)
686
+ return null;
687
+ let end = lines.findIndex((l, i) => i > start && (/^={3,}/.test(l) || /^_{3,} .+ _{3,}$/.test(l)));
688
+ if (end < 0)
689
+ end = lines.length;
690
+ let text = lines.slice(start, end).join("\n").trim();
691
+ if (!/^E\s/m.test(text))
692
+ return null; // no assertion or exception text: nothing to reason from
693
+ while (new TextEncoder().encode(text).length > 3500)
694
+ text = text.split("\n").slice(0, -1).join("\n");
695
+ return text;
696
+ }
697
+ function triageSpec(g, n, m, failing, _evidence) {
698
+ const fp = fingerprint({ type: "failure_triage", site: n.key, mutant: m.id });
699
+ const ref = `pytest:${createHash("sha256").update(failing.join("\n")).digest("hex").slice(0, 16)}`;
700
+ return {
701
+ fingerprint: fp, template_key: "failure_triage.locate", type: "failure_triage",
702
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "errors.handling", weight: 0.5 }],
703
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.55, grading_method: "triage",
704
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref, failing_tests: failing.slice(0, 5) } },
705
+ voice_compatible: false, est_seconds: 150,
706
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line_count: n.loc, causes: CAUSES },
707
+ expected: { line: m.line, cause: CAUSE[m.operator] ?? "condition", failing_tests: failing.slice(0, 5) },
708
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
709
+ };
710
+ }
711
+ /**
712
+ * Cloze over the ORIGINAL code: the span a killed mutant changes is blanked. Known-wrong answers are the
713
+ * replacements of killed mutants at that same span (verified wrong by the tests); a menu of them serves voice.
714
+ */
715
+ function clozeSpec(g, n, source, m, all) {
716
+ const answer = source.slice(m.start, m.end);
717
+ if (!answer.trim() || answer.includes("\n") || answer.length > 60)
718
+ return null;
719
+ const blanked = source.slice(0, m.start) + CLOZE_BLANK + source.slice(m.end);
720
+ const wrong = [...new Set(all.filter((x) => x.start === m.start && x.end === m.end).map((x) => x.replacement.trim()))].filter((w) => w && w !== answer.trim());
721
+ const fp = fingerprint({ type: "cloze", site: n.key, mutant: m.id });
722
+ const short = answer.length <= 28 && wrong.length >= 1 && wrong.every((w) => w.length <= 28 && !w.includes("\n"));
723
+ const choices = short ? seededShuffle([answer.trim(), ...wrong.slice(0, 3)], fp) : undefined;
724
+ const spec = {
725
+ fingerprint: fp, template_key: "cloze.blank", type: "cloze",
726
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "lang.control-flow", weight: 0.5 }],
727
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.5, grading_method: "cloze",
728
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `mutant:${m.id.slice(0, 16)}`, operator: m.operator } },
729
+ voice_compatible: Boolean(choices), est_seconds: 90,
730
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line: m.line, ...(choices ? { choices } : {}) },
731
+ expected: { answer: answer.trim(), wrong, language: n.language, ...(choices ? { choices, correct_choice: choices.indexOf(answer.trim()) } : {}) },
732
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
733
+ };
734
+ return { spec, fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1], text: sliceLines(blanked, n.span[0], n.span[1]) } };
735
+ }
736
+ function stateTraceSpec(g, n, args, cp) {
737
+ const fp = fingerprint({ type: "state_trace", site: n.key, input: args, line: cp.line, var: cp.var });
738
+ const value = display(`OK:${JSON.stringify(cp.value)}`);
739
+ return {
740
+ fingerprint: fp, template_key: "state_trace.checkpoint", type: "state_trace",
741
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "lang.control-flow", weight: 0.6 }],
742
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.6, grading_method: "exact_output",
743
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `trace:${createHash("sha256").update(`${n.key}|${args}|${cp.line}|${cp.var}`).digest("hex").slice(0, 16)}` } },
744
+ voice_compatible: value.length <= 24, est_seconds: 120,
745
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, call: `${n.name}(${args})`, line: cp.line, hit: cp.hit, var: cp.var },
746
+ expected: { output: value },
747
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
748
+ };
749
+ }
750
+ /** N9: a function of 4-9 simple lines (no docstring, no continuation lines) as shuffled blocks + 1 distractor. */
751
+ export function parsonsBlocks(source, n, killed) {
752
+ const all = source.split("\n").slice(n.span[0] - 1, n.span[1]);
753
+ const def = all[0];
754
+ if (!/^\s*(async\s+)?def\s/.test(def) || !def.trimEnd().endsWith(":"))
755
+ return null;
756
+ const body = all.slice(1).filter((l) => l.trim() && !l.trim().startsWith("#"));
757
+ if (body.length < 4 || body.length > 9)
758
+ return null;
759
+ if (body.some((l) => /["']{3}/.test(l) || /[([{,\\]\s*$/.test(l)))
760
+ return null;
761
+ const base = def.length - def.trimStart().length;
762
+ const unit = Math.min(...body.map((l) => l.length - l.trimStart().length)) - base;
763
+ if (unit <= 0)
764
+ return null;
765
+ const indents = body.map((l) => (l.length - l.trimStart().length - base) / unit - 1);
766
+ if (indents.some((x) => !Number.isInteger(x) || x < 0))
767
+ return null;
768
+ const texts = body.map((l) => l.trim());
769
+ const distractors = [];
770
+ for (const m of killed) {
771
+ const mutated = m.text.split("\n")[m.line - 1]?.trim();
772
+ if (mutated && !texts.includes(mutated) && m.text.split("\n").length === source.split("\n").length) {
773
+ distractors.push(mutated);
774
+ break;
775
+ }
776
+ }
777
+ if (!distractors.length)
778
+ return null;
779
+ const pool = [...texts.map((t, i) => ({ t, real: i })), ...distractors.map((t) => ({ t, real: -1 }))];
780
+ const key = (x) => createHash("sha256").update(`${n.key}|${x.t}`).digest("hex");
781
+ const shuffled = [...pool].sort((a, b) => (key(a) < key(b) ? -1 : 1));
782
+ const lines = [def.trim(), ...shuffled.map((x) => x.t)];
783
+ const order = texts.map((_, i) => shuffled.findIndex((x) => x.real === i) + 1);
784
+ const distractorIds = shuffled.flatMap((x, i) => (x.real === -1 ? [i + 1] : []));
785
+ return { lines, order, indents, distractors: distractorIds };
786
+ }
787
+ function parsonsSpec(g, n, pz) {
788
+ const fp = fingerprint({ type: "parsons", site: n.key, blocks: pz.lines.length });
789
+ return {
790
+ fingerprint: fp, template_key: "parsons.arrange", type: "parsons",
791
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "lang.control-flow", weight: 0.6 }],
792
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.55, grading_method: "local_exec",
793
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `parsons:${fp.slice(0, 16)}` } },
794
+ voice_compatible: false, est_seconds: 240,
795
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, blocks: pz.lines.length - 1, distractors: pz.distractors.length },
796
+ // Reference arrangement (one of possibly several the tests accept); stays server-side.
797
+ expected: { order: pz.order, indents: pz.indents, distractors: pz.distractors, line_count: pz.order.length },
798
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
799
+ };
800
+ }
801
+ function contractSpec(g, n, c) {
802
+ const fp = fingerprint({ type: "null_contract", site: n.key });
803
+ return {
804
+ fingerprint: fp, template_key: "null_contract.can_be_none", type: "null_contract",
805
+ concepts: [{ slug: "lang.null-absence", weight: 0.8 }, ...g.conceptsOrParent(n.key).slice(0, 2).map((x) => ({ ...x, weight: Math.min(x.weight, 0.3) }))],
806
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.55, grading_method: "contract",
807
+ verification: { kind: "structural", all_edges_resolved: true, evidence: { ref: `contract:${fp.slice(0, 16)}` } },
808
+ voice_compatible: false, est_seconds: 90,
809
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line_count: n.loc },
810
+ expected: { can_be_none: c.canBeNone, lines: c.lines, reasons: c.reasons },
811
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
812
+ };
813
+ }
814
+ function raceSpec(g, n, m, lostFinal) {
815
+ const fp = fingerprint({ type: "race_schedule", site: n.key, read: m.read - n.span[0], write: m.write - n.span[0] });
816
+ return {
817
+ fingerprint: fp, template_key: `race_schedule.${m.kind}`, type: "race_schedule",
818
+ concepts: [...(m.kind === "async" ? [{ slug: "conc.shared-state-races", weight: 0.8 }, { slug: "conc.async-io", weight: 0.3 }] : [{ slug: "data.race-conditions", weight: 0.8 }, { slug: "data.atomic-updates", weight: 0.4 }]), ...g.conceptsOrParent(n.key).slice(0, 2).map((x) => ({ ...x, weight: Math.min(x.weight, 0.3) }))],
819
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.6, grading_method: "race",
820
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `race:${fp.slice(0, 16)}` } },
821
+ voice_compatible: false, est_seconds: 120,
822
+ // Lines and the model are structural (no code): which lines read, switch and write, and the starting value.
823
+ prompt: {
824
+ target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path },
825
+ kind: m.kind, tasks: ["A", "B"], initial: RACE_INITIAL, delta: m.delta,
826
+ steps: [{ op: "read" }, { op: "write" }],
827
+ },
828
+ expected: { delta: m.delta, initial: RACE_INITIAL, expected_final: RACE_INITIAL + 2 * m.delta, lost_final: lostFinal, read: m.read, gap: m.gap, write: m.write, switch_lines: [m.kind === "async" ? m.gap : m.read] },
829
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
830
+ };
831
+ }
832
+ export const COST_CLASSES = ["O(1)", "O(log n)", "O(n)", "O(n log n)", "O(n²)"];
833
+ /** Fit the growth of the hottest line (not the def line) across n = 10, 100, 1000. Null when the fit is ambiguous. */
834
+ export function costClass(c10, c100, c1000, defLine) {
835
+ const lines = Object.keys(c1000).map(Number).filter((l) => l !== defLine);
836
+ if (!lines.length)
837
+ return null;
838
+ const line = lines.sort((a, b) => c1000[String(b)] - c1000[String(a)] || a - b)[0];
839
+ const [a, b, c] = [c10[String(line)] ?? 0, c100[String(line)] ?? 0, c1000[String(line)] ?? 0];
840
+ if (a <= 0 || b <= 0 || c <= 0)
841
+ return null;
842
+ const s1 = Math.log10(b / a), s2 = Math.log10(c / b);
843
+ const cls = s2 < 0.1 && s1 < 0.1 ? "O(1)" : s2 >= 0.85 && s2 < 1.08 && s1 >= 0.85 && s1 < 1.08 ? "O(n)"
844
+ : s2 >= 1.08 && s2 < 1.5 && s1 >= 1.05 && s1 < 1.5 ? "O(n log n)" : s2 >= 1.8 && s2 < 2.2 && s1 >= 1.6 ? "O(n²)" : s2 > 0.15 && s2 < 0.6 && c > b ? "O(log n)" : null;
845
+ if (!cls || (cls === "O(1)" && c < 2))
846
+ return null;
847
+ return { line, cls, counts: [a, b, c] };
848
+ }
849
+ function costScaleSpec(g, n, args, fit) {
850
+ const fp = fingerprint({ type: "cost_scale", site: n.key, input: args, line: fit.line });
851
+ return {
852
+ fingerprint: fp, template_key: "cost_scale.line", type: "cost_scale",
853
+ concepts: [{ slug: "perf.complexity", weight: 0.8 }, ...g.conceptsOrParent(n.key).slice(0, 2).map((c) => ({ ...c, weight: Math.min(c.weight, 0.3) }))],
854
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.65, grading_method: "cost",
855
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `count:${fp.slice(0, 16)}` } },
856
+ voice_compatible: true, est_seconds: 150,
857
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, call: `${n.name}(${args})`, line: fit.line, n: 100, classes: COST_CLASSES },
858
+ expected: { class: fit.cls, count: fit.counts[1], counts: fit.counts },
859
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
860
+ };
861
+ }
862
+ /** Behaviour-preserving edits for N7: flip a comparison (a < b -> b > a), or `x = x + y` -> `x += y` on a name.
863
+ * Never on the broken mutant's own line, so the two versions differ in different places. */
864
+ export function safeRefactors(source, n, avoid) {
865
+ const lines = source.split("\n");
866
+ const out = [];
867
+ const FLIP = { "<": ">", ">": "<", "<=": ">=", ">=": "<=" };
868
+ for (let i = n.span[0]; i < n.span[1]; i++) {
869
+ if (i + 1 === avoid.line)
870
+ continue;
871
+ const line = lines[i];
872
+ const cmp = /^(\s*(?:if|elif|while|return)\s+)([\w.\[\]'"]+)\s*(<=|>=|<|>)\s*([\w.\[\]'"]+)\s*(:?)\s*$/.exec(line);
873
+ if (cmp) {
874
+ const text = [...lines.slice(0, i), `${cmp[1]}${cmp[4]} ${FLIP[cmp[3]]} ${cmp[2]}${cmp[5]}`, ...lines.slice(i + 1)].join("\n");
875
+ out.push({ kind: "flip_comparison", text });
876
+ }
877
+ const aug = /^(\s*)(\w+) = \2 ([+\-*]) (.+)$/.exec(line);
878
+ if (aug)
879
+ out.push({ kind: "augmented_assignment", text: [...lines.slice(0, i), `${aug[1]}${aug[2]} ${aug[3]}= ${aug[4]}`, ...lines.slice(i + 1)].join("\n") });
880
+ }
881
+ return out;
882
+ }
883
+ function spotSpec(g, n, broken, safeKind, params) {
884
+ const fp = fingerprint({ type: "spot_difference", site: n.key, mutant: broken.id, safe: safeKind });
885
+ const brokenLabel = parseInt(fp.slice(0, 2), 16) % 2 === 0 ? "A" : "B";
886
+ return {
887
+ fingerprint: fp, template_key: "spot_difference.pick", type: "spot_difference",
888
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "lang.control-flow", weight: 0.6 }],
889
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.65, grading_method: "spot",
890
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `mutant:${broken.id.slice(0, 16)}`, operator: broken.operator, safe: safeKind } },
891
+ voice_compatible: false, est_seconds: 180,
892
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, function: n.name, params, versions: ["A", "B"] },
893
+ expected: { broken: brokenLabel, safe_kind: safeKind, operator: broken.operator, line: broken.line },
894
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
895
+ };
896
+ }
897
+ const VULN_CONCEPTS = {
898
+ authorization: [{ slug: "auth.permissions-objects", weight: 0.7 }, { slug: "auth.authentication-vs-authorization", weight: 0.4 }],
899
+ injection: [{ slug: "sql.parameterized-queries", weight: 0.7 }, { slug: "auth.injection", weight: 0.5 }],
900
+ xss: [{ slug: "auth.xss", weight: 0.8 }],
901
+ csrf: [{ slug: "auth.csrf", weight: 0.8 }],
902
+ path_traversal: [{ slug: "auth.input-validation", weight: 0.8 }],
903
+ };
904
+ function vulnSpec(g, n, m) {
905
+ const fp = fingerprint({ type: "find_vuln", site: n.key, mutant: m.id });
906
+ const own = g.conceptsOrParent(n.key).filter((c) => !VULN_CONCEPTS[m.vuln].some((v) => v.slug === c.slug));
907
+ return {
908
+ fingerprint: fp, template_key: "find_vuln.locate", type: "find_vuln",
909
+ concepts: [...VULN_CONCEPTS[m.vuln], ...own.map((c) => ({ ...c, weight: Math.min(c.weight, 0.3) }))].slice(0, 4),
910
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.7, grading_method: "vuln",
911
+ // Structural evidence: the planted code matches the rule for its class and the original does not.
912
+ verification: { kind: "structural", all_edges_resolved: true, evidence: { ref: `rule:${m.operator}`, rule: m.operator } },
913
+ voice_compatible: false, est_seconds: 150,
914
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line_count: n.loc, classes: VULN_CLASSES },
915
+ expected: { line: m.line, vuln_class: m.vuln, operator: m.operator, removed: m.removed },
916
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
917
+ };
918
+ }
919
+ function queryCountSpec(g, view, test, testPath, testStart, req, viewText) {
920
+ const v = req.view;
921
+ const fp = fingerprint({ type: "query_count", site: view.key, test: `${testPath}::${test}`, line: req.line, method: req.method });
922
+ const concepts = [{ slug: "django.orm.n-plus-one", weight: 0.6 }, { slug: "django.orm.querysets-lazy", weight: 0.3 }];
923
+ if (/prefetch_related\(/.test(viewText))
924
+ concepts.push({ slug: "django.orm.prefetch_related", weight: 0.3 });
925
+ if (/select_related\(/.test(viewText))
926
+ concepts.push({ slug: "django.orm.select_related", weight: 0.3 });
927
+ return {
928
+ fingerprint: fp, template_key: "query_count.request", type: "query_count",
929
+ concepts: concepts.slice(0, 4),
930
+ component_node_id: view.id, criticality: view.criticality ?? 0, difficulty: 0.65, grading_method: "count",
931
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `queries:${fp.slice(0, 16)}` } },
932
+ voice_compatible: true, est_seconds: 150,
933
+ prompt: {
934
+ target: { id: view.id, name: view.local ?? view.name, kind: view.kind, path: view.path },
935
+ test, test_path: testPath, test_start_line: testStart, request_line: req.line, method: req.method, route: v.route,
936
+ view: v.name, action: v.action,
937
+ },
938
+ // Shapes are verb + table names only (structural); the SQL text never leaves the sandbox.
939
+ expected: { count: req.count, shapes: req.shapes.slice(0, 40) },
940
+ fragment: { path: view.path, start_line: v.span.start, end_line: v.span.end },
941
+ };
942
+ }
943
+ function killMutantSpec(g, n, m, params, exampleArgs) {
944
+ const fp = fingerprint({ type: "kill_mutant", site: n.key, mutant: m.id });
945
+ return {
946
+ fingerprint: fp, template_key: "kill_mutant.write_test", type: "kill_mutant",
947
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "testing.unit-tests", weight: 0.6 }],
948
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.65, grading_method: "local_exec",
949
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `mutant:${m.id.slice(0, 16)}`, operator: m.operator } },
950
+ voice_compatible: false, est_seconds: 180,
951
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, function: n.name, params },
952
+ // A known killing call stays server-side (never shown) as a reference for review and disputes.
953
+ expected: { reference_args: exampleArgs, operator: m.operator },
954
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
955
+ };
956
+ }
957
+ function reverseTraceSpec(g, n, params, goal, referenceArgs) {
958
+ const fp = fingerprint({ type: "reverse_trace", site: n.key, goal });
959
+ return {
960
+ fingerprint: fp, template_key: "reverse_trace.return", type: "reverse_trace",
961
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "lang.control-flow", weight: 0.6 }],
962
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.6, grading_method: "local_exec",
963
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `harness:${createHash("sha256").update(`${n.key}|${goal}`).digest("hex").slice(0, 16)}` } },
964
+ voice_compatible: false, est_seconds: 150,
965
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, function: n.name, params, goal },
966
+ expected: { goal, reference_args: referenceArgs },
967
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
968
+ };
969
+ }
970
+ function fixBugSpec(g, n, m, failing) {
971
+ const fp = fingerprint({ type: "fix_bug", site: n.key, mutant: m.id });
972
+ return {
973
+ fingerprint: fp, template_key: "fix_bug.patch", type: "fix_bug",
974
+ concepts: g.conceptsOrParent(n.key).length ? g.conceptsOrParent(n.key) : [{ slug: "testing.regression-tests", weight: 0.5 }],
975
+ component_node_id: n.id, criticality: n.criticality ?? 0, difficulty: 0.7, grading_method: "local_exec",
976
+ verification: { kind: "execution", all_edges_resolved: true, evidence: { ref: `pytest:${createHash("sha256").update(failing.join("\n")).digest("hex").slice(0, 16)}` } },
977
+ voice_compatible: false, est_seconds: 300,
978
+ prompt: { target: { id: n.id, name: n.local ?? n.name, kind: n.kind, path: n.path }, line_count: n.loc, failing_count: failing.length },
979
+ expected: { line: m.line, operator: m.operator, line_count: n.loc, failing_tests: failing.slice(0, 5) },
980
+ fragment: { path: n.path, start_line: n.span[0], end_line: n.span[1] },
981
+ };
982
+ }
983
+ //# sourceMappingURL=items.js.map