pi-evals 0.7.0 → 0.8.1
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/CHANGELOG.md +11 -0
- package/README.md +20 -0
- package/dist/cli.js +5 -1
- package/dist/exp/cli.js +97 -0
- package/dist/exp/fixture.js +73 -0
- package/dist/exp/grade.js +156 -0
- package/dist/exp/labels.js +172 -0
- package/dist/exp/run.js +154 -0
- package/dist/exp/show.js +54 -0
- package/dist/exp/stats.js +63 -0
- package/dist/exp/summary.js +125 -0
- package/dist/exp/task.js +57 -0
- package/dist/exp/trial.js +191 -0
- package/dist/exp/validity.js +81 -0
- package/dist/labels.js +2 -1
- package/package.json +1 -1
- package/src/cli.ts +4 -1
- package/src/exp/cli.ts +97 -0
- package/src/exp/fixture.ts +74 -0
- package/src/exp/grade.ts +185 -0
- package/src/exp/labels.ts +178 -0
- package/src/exp/run.ts +178 -0
- package/src/exp/show.ts +57 -0
- package/src/exp/stats.ts +77 -0
- package/src/exp/summary.ts +149 -0
- package/src/exp/task.ts +100 -0
- package/src/exp/trial.ts +239 -0
- package/src/exp/validity.ts +76 -0
- package/src/labels.ts +4 -2
package/dist/exp/run.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A run: every chosen task × arm × k trials, interleaved per task (A1 B1 A2 B2 …) so a run stopped early stays paired,
|
|
3
|
+
* at most `parallel` at once. A leaking trial is rerun once. The first quota refusal stops new trials.
|
|
4
|
+
*/
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir, hostname } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { stateDir } from "../paths.js";
|
|
10
|
+
import { buildFixture } from "./fixture.js";
|
|
11
|
+
import { summarize } from "./summary.js";
|
|
12
|
+
import { loadSuite } from "./task.js";
|
|
13
|
+
import { gradeTrial, runTrial, trialDirOf } from "./trial.js";
|
|
14
|
+
export const experimentsDir = (env = process.env) => join(stateDir(env), "experiments");
|
|
15
|
+
export const fixturesDir = (env = process.env) => join(stateDir(env), "fixtures");
|
|
16
|
+
const safe = (f) => {
|
|
17
|
+
try {
|
|
18
|
+
return f();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
export function selectTasks(suite, ids) {
|
|
25
|
+
if (!ids?.length)
|
|
26
|
+
return suite.tasks;
|
|
27
|
+
const unknown = ids.filter((id) => !suite.tasks.some((t) => t.id === id));
|
|
28
|
+
if (unknown.length)
|
|
29
|
+
throw new Error(`unknown task ${unknown.join(", ")}; tasks: ${suite.tasks.map((t) => t.id).join(", ")}`);
|
|
30
|
+
return suite.tasks.filter((t) => ids.includes(t.id));
|
|
31
|
+
}
|
|
32
|
+
export function readResults(runDir) {
|
|
33
|
+
const file = join(runDir, "results.jsonl");
|
|
34
|
+
if (!existsSync(file))
|
|
35
|
+
return [];
|
|
36
|
+
return readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
|
|
37
|
+
}
|
|
38
|
+
export function readRun(runDir) {
|
|
39
|
+
return JSON.parse(readFileSync(join(runDir, "run.json"), "utf8"));
|
|
40
|
+
}
|
|
41
|
+
export function writeSummary(runDir, meta) {
|
|
42
|
+
const summary = summarize(readResults(runDir), Object.keys(meta.arms), { k: meta.k });
|
|
43
|
+
writeFileSync(join(runDir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
|
44
|
+
return summary;
|
|
45
|
+
}
|
|
46
|
+
export async function runExperiment(options) {
|
|
47
|
+
const suite = loadSuite(options.suiteDir);
|
|
48
|
+
for (const arm of options.arms)
|
|
49
|
+
if (!suite.arms.has(arm))
|
|
50
|
+
throw new Error(`unknown arm ${arm}; arms: ${[...suite.arms.keys()].join(", ")}`);
|
|
51
|
+
const tasks = selectTasks(suite, options.tasks);
|
|
52
|
+
const id = options.runId ?? new Date().toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
|
|
53
|
+
const runDir = join(experimentsDir(), id);
|
|
54
|
+
mkdirSync(runDir, { recursive: true });
|
|
55
|
+
const parallel = Math.max(1, options.parallel ?? 3);
|
|
56
|
+
const meta = {
|
|
57
|
+
id,
|
|
58
|
+
suite: suite.dir,
|
|
59
|
+
suiteSha: safe(() => execFileSync("git", ["-C", suite.dir, "rev-parse", "HEAD"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()),
|
|
60
|
+
arms: Object.fromEntries(options.arms.map((a) => {
|
|
61
|
+
const arm = suite.arms.get(a);
|
|
62
|
+
return [a, { extensions: arm.extensions, skills: arm.skills, appendSystemPrompt: arm.appendSystemPrompt }];
|
|
63
|
+
})),
|
|
64
|
+
extensions: suite.extensions,
|
|
65
|
+
model: suite.model,
|
|
66
|
+
thinking: suite.thinking,
|
|
67
|
+
...(suite.followUp ? { followUp: suite.followUp } : {}),
|
|
68
|
+
pi: safe(() => execFileSync(options.piBin ?? "pi", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()),
|
|
69
|
+
k: options.k,
|
|
70
|
+
tasks: tasks.map((t) => t.id),
|
|
71
|
+
host: hostname(),
|
|
72
|
+
parallel,
|
|
73
|
+
startedAt: new Date().toISOString(),
|
|
74
|
+
};
|
|
75
|
+
let record = meta;
|
|
76
|
+
if (options.rerun !== undefined) {
|
|
77
|
+
if (!existsSync(join(runDir, "run.json")))
|
|
78
|
+
throw new Error(`no run ${id} to rerun tasks in`);
|
|
79
|
+
const old = readRun(runDir);
|
|
80
|
+
const same = old.model === meta.model && old.thinking === meta.thinking && old.k === meta.k && Object.keys(old.arms).join() === Object.keys(meta.arms).join();
|
|
81
|
+
if (!same)
|
|
82
|
+
throw new Error(`rerun must match run ${id}: model ${old.model}/${old.thinking}, arms ${Object.keys(old.arms).join(",")}, k ${old.k}; got k ${meta.k}`);
|
|
83
|
+
record = { ...old, tasks: [...new Set([...old.tasks, ...meta.tasks])], reruns: [...(old.reruns ?? []), { tasks: meta.tasks, reason: options.rerun, at: meta.startedAt, ...(meta.suiteSha ? { suiteSha: meta.suiteSha } : {}) }] };
|
|
84
|
+
}
|
|
85
|
+
writeFileSync(join(runDir, "run.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
86
|
+
const progress = options.onProgress ?? (() => { });
|
|
87
|
+
const fixtures = new Map();
|
|
88
|
+
for (const task of tasks) {
|
|
89
|
+
progress({ fixture: task.id });
|
|
90
|
+
fixtures.set(task.id, buildFixture(suite, task, fixturesDir(), { log: (line) => progress({ log: line }) }));
|
|
91
|
+
}
|
|
92
|
+
const jobs = [];
|
|
93
|
+
for (const task of tasks)
|
|
94
|
+
for (let n = 1; n <= options.k; n++)
|
|
95
|
+
for (const arm of options.arms)
|
|
96
|
+
jobs.push({ task, arm, n });
|
|
97
|
+
const done = new Set(options.rerun === undefined ? readResults(runDir).filter((r) => r.valid).map((r) => `${r.task}\0${r.arm}\0${r.n}`) : []);
|
|
98
|
+
const queue = jobs.filter((j) => !done.has(`${j.task.id}\0${j.arm}\0${j.n}`));
|
|
99
|
+
const total = jobs.length;
|
|
100
|
+
let finished = jobs.length - queue.length;
|
|
101
|
+
let stopped;
|
|
102
|
+
const records = [];
|
|
103
|
+
const authFile = join(homedir(), ".pi", "agent", "auth.json");
|
|
104
|
+
const one = async (job) => {
|
|
105
|
+
const spec = { suite, task: job.task, arm: job.arm, n: job.n, runDir, fixture: fixtures.get(job.task.id), piBin: options.piBin, authFile };
|
|
106
|
+
let record = await runTrial(spec);
|
|
107
|
+
if (!record.valid && record.leak && !stopped) {
|
|
108
|
+
progress({ rerun: `${job.task.id}/${job.arm}/${job.n}`, reason: record.invalid });
|
|
109
|
+
appendFileSync(join(runDir, "results.jsonl"), `${JSON.stringify(record)}\n`);
|
|
110
|
+
record = await runTrial(spec);
|
|
111
|
+
}
|
|
112
|
+
if (record.quota)
|
|
113
|
+
stopped = `quota refusal in ${job.task.id}/${job.arm}/${job.n}`;
|
|
114
|
+
// pi that wrote no session did not start (a bad flag, a missing extension file): every later trial would fail too.
|
|
115
|
+
else if (record.invalid === "no_session")
|
|
116
|
+
stopped = `pi wrote no session in ${job.task.id}/${job.arm}/${job.n}; see its stderr.txt`;
|
|
117
|
+
appendFileSync(join(runDir, "results.jsonl"), `${JSON.stringify(record)}\n`);
|
|
118
|
+
records.push(record);
|
|
119
|
+
finished++;
|
|
120
|
+
progress({ progress: { done: finished, total }, trial: `${job.task.id}/${job.arm}/${job.n}`, outcome: record.outcome, valid: record.valid, cost: record.efficiency.cost, minutes: Math.round(record.efficiency.wallMs / 6000) / 10 });
|
|
121
|
+
};
|
|
122
|
+
const workers = Array.from({ length: Math.min(parallel, queue.length) }, async () => {
|
|
123
|
+
while (queue.length && !stopped)
|
|
124
|
+
await one(queue.shift());
|
|
125
|
+
});
|
|
126
|
+
await Promise.all(workers);
|
|
127
|
+
if (options.rerun === undefined)
|
|
128
|
+
record.endedAt = new Date().toISOString();
|
|
129
|
+
if (stopped)
|
|
130
|
+
record.stopped = stopped;
|
|
131
|
+
writeFileSync(join(runDir, "run.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
132
|
+
writeSummary(runDir, record);
|
|
133
|
+
if (stopped)
|
|
134
|
+
progress({ monitorOutcome: { status: "blocked", message: stopped } });
|
|
135
|
+
return { runDir, records, stopped };
|
|
136
|
+
}
|
|
137
|
+
/** Regrade every stored trial of a run (after a grader fix); rewrites results.jsonl and summary.json. */
|
|
138
|
+
export function regradeRun(runDir) {
|
|
139
|
+
const meta = readRun(runDir);
|
|
140
|
+
const suite = loadSuite(meta.suite);
|
|
141
|
+
const records = [];
|
|
142
|
+
for (const task of selectTasks(suite, meta.tasks)) {
|
|
143
|
+
for (const arm of Object.keys(meta.arms)) {
|
|
144
|
+
for (let n = 1; n <= meta.k; n++) {
|
|
145
|
+
const trialDir = trialDirOf(runDir, task.id, arm, n);
|
|
146
|
+
if (existsSync(join(trialDir, "outcome.json")))
|
|
147
|
+
records.push(gradeTrial({ suite, task, arm, n, trialDir }));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
writeFileSync(join(runDir, "results.jsonl"), records.map((r) => `${JSON.stringify(r)}\n`).join(""));
|
|
152
|
+
writeSummary(runDir, meta);
|
|
153
|
+
return records;
|
|
154
|
+
}
|
package/dist/exp/show.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const NAMES = {
|
|
2
|
+
outcome: "outcome pass@1",
|
|
3
|
+
outcome_pass3: "outcome pass^3",
|
|
4
|
+
process: "process (anchor+check)",
|
|
5
|
+
anchor: "anchor before first edit",
|
|
6
|
+
check: "check after last edit",
|
|
7
|
+
todo_evidence: "todo evidence",
|
|
8
|
+
close_guard_quiet: "close guard quiet",
|
|
9
|
+
edited_when_should_not: "edited when should not",
|
|
10
|
+
done_claim_fail: "done claim, check failed",
|
|
11
|
+
};
|
|
12
|
+
const pct = (v) => (v === undefined || Number.isNaN(v) ? "—" : `${Math.round(v * 100)}%`);
|
|
13
|
+
const pp = (v) => `${v >= 0 ? "+" : ""}${Math.round(v * 100)}`;
|
|
14
|
+
const pad = (s, n) => s + " ".repeat(Math.max(0, n - s.length));
|
|
15
|
+
export function show(meta, summary, records, agreement = []) {
|
|
16
|
+
const arms = summary.arms.map((a) => a.arm);
|
|
17
|
+
const guarded = (arm) => [...(meta.arms[arm]?.extensions ?? [])].some((e) => /close-guard/.test(e));
|
|
18
|
+
const out = [];
|
|
19
|
+
const valid = records.filter((r) => r.valid).length;
|
|
20
|
+
out.push(`run ${meta.id} · ${meta.model} (${meta.thinking}) · pi ${meta.pi ?? "?"} · k=${meta.k} · ${meta.tasks.length} tasks · ${summary.arms.reduce((s, a) => s + a.trials, 0)} valid trials${meta.stopped ? ` · STOPPED: ${meta.stopped}` : ""}`);
|
|
21
|
+
out.push(`started ${meta.startedAt}${meta.endedAt ? ` · ended ${meta.endedAt}` : " · running"} · ${records.length - valid} invalid record(s)`);
|
|
22
|
+
for (const r of meta.reruns ?? [])
|
|
23
|
+
out.push(`rerun ${r.at}: ${r.tasks.join(", ")} (${r.reason}); earlier trials superseded, kept in results.jsonl`);
|
|
24
|
+
out.push("");
|
|
25
|
+
const w = 28;
|
|
26
|
+
out.push(pad("metric", w) + arms.map((a) => pad(a, 12)).join("") + (summary.pair ? `${summary.pair[1]} − ${summary.pair[0]} (95% CI)` : ""));
|
|
27
|
+
for (const metric of Object.keys(NAMES)) {
|
|
28
|
+
const cells = summary.arms.map((a) => pad(metric === "close_guard_quiet" && !guarded(a.arm) ? "—" : pct(a.metrics[metric]), 12));
|
|
29
|
+
const d = summary.deltas[metric];
|
|
30
|
+
const delta = d && metric !== "close_guard_quiet" ? `${pp(d.delta)} pp (${pp(d.lo)} to ${pp(d.hi)})${d.lo <= 0 && d.hi >= 0 ? " no clear difference" : ""} · ${d.tasks} tasks` : "";
|
|
31
|
+
out.push(pad(NAMES[metric], w) + cells.join("") + delta);
|
|
32
|
+
}
|
|
33
|
+
out.push(pad("cost per trial (USD equiv.)", w) + summary.arms.map((a) => pad(`$${a.costPerTrial.toFixed(2)}`, 12)).join(""));
|
|
34
|
+
out.push(pad("minutes per trial", w) + summary.arms.map((a) => pad(a.minutesPerTrial.toFixed(1), 12)).join(""));
|
|
35
|
+
out.push(pad("total cost", w) + summary.arms.map((a) => pad(`$${a.costTotal.toFixed(2)}`, 12)).join(""));
|
|
36
|
+
out.push(pad("invalid trials", w) + summary.arms.map((a) => pad(String(a.invalid), 12)).join(""));
|
|
37
|
+
out.push("");
|
|
38
|
+
out.push(pad("task", 24) + pad("kind", 12) + arms.map((a) => pad(`${a} pass`, 16)).join("") + "Δ pass@1");
|
|
39
|
+
for (const row of summary.tasks) {
|
|
40
|
+
const cells = arms.map((a) => {
|
|
41
|
+
const c = row.arms[a];
|
|
42
|
+
return pad(c ? `${c.pass}/${c.n}${c.process === undefined ? "" : ` p${pct(c.process)}`}` : "—", 16);
|
|
43
|
+
});
|
|
44
|
+
out.push(pad(row.task, 24) + pad(row.kind, 12) + cells.join("") + (row.delta === undefined ? "" : pp(row.delta)));
|
|
45
|
+
}
|
|
46
|
+
if (summary.doneClaimFail.length)
|
|
47
|
+
out.push("", `done claimed but check failed: ${summary.doneClaimFail.map((d) => `${d.task}/${d.arm}/${d.n}`).join(", ")}`);
|
|
48
|
+
for (const a of agreement)
|
|
49
|
+
out.push(`labels vs graders, ${a.rule}: ${a.agree}/${a.n} agree${a.unclear ? `, ${a.unclear} unclear` : ""}${a.disagree.length ? `; disagree: ${a.disagree.join(", ")}` : ""}`);
|
|
50
|
+
const invalid = records.filter((r) => !r.valid);
|
|
51
|
+
if (invalid.length)
|
|
52
|
+
out.push(`invalid: ${invalid.map((r) => `${r.task}/${r.arm}/${r.n} (${r.invalid})`).join(", ")}`);
|
|
53
|
+
return out.join("\n");
|
|
54
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trial statistics: unbiased pass@1, pass^k and pass@k from c passes in n trials, and a paired cluster bootstrap over
|
|
3
|
+
* tasks for the difference between two arms (tasks resampled, then trials resampled within each task and arm).
|
|
4
|
+
*/
|
|
5
|
+
function choose(n, k) {
|
|
6
|
+
if (k < 0 || k > n)
|
|
7
|
+
return 0;
|
|
8
|
+
let r = 1;
|
|
9
|
+
for (let i = 1; i <= k; i++)
|
|
10
|
+
r = (r * (n - k + i)) / i;
|
|
11
|
+
return r;
|
|
12
|
+
}
|
|
13
|
+
export const passAt1 = (c, n) => c / n;
|
|
14
|
+
/** All k of k fresh trials pass: C(c,k)/C(n,k). */
|
|
15
|
+
export function passHatK(c, n, k) {
|
|
16
|
+
if (k > n)
|
|
17
|
+
throw new Error(`pass^k needs k > n trials: k ${k} > n ${n}`);
|
|
18
|
+
return choose(c, k) / choose(n, k);
|
|
19
|
+
}
|
|
20
|
+
/** At least one of k fresh trials passes: 1 − C(n−c,k)/C(n,k). */
|
|
21
|
+
export function passAtK(c, n, k) {
|
|
22
|
+
if (k > n)
|
|
23
|
+
throw new Error(`pass@k needs k > n trials: k ${k} > n ${n}`);
|
|
24
|
+
return 1 - choose(n - c, k) / choose(n, k);
|
|
25
|
+
}
|
|
26
|
+
/** Mean of the defined values; undefined when none is defined (a metric that does not apply to the task). */
|
|
27
|
+
export function taskRate(values) {
|
|
28
|
+
const defined = values.filter((v) => typeof v === "number");
|
|
29
|
+
return defined.length ? defined.reduce((s, v) => s + v, 0) / defined.length : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** mulberry32: a small seeded PRNG so a summary is reproducible. */
|
|
32
|
+
function rng(seed) {
|
|
33
|
+
let a = seed >>> 0;
|
|
34
|
+
return () => {
|
|
35
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
36
|
+
let t = a;
|
|
37
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
38
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
39
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Paired cluster bootstrap: the statistic is computed per task and arm from that task's trial values, the delta is the
|
|
44
|
+
* mean over tasks of B − A. Tasks with no trial in either arm are left out. 95% percentile interval.
|
|
45
|
+
*/
|
|
46
|
+
export function pairedBootstrap(tasks, stat, options = {}) {
|
|
47
|
+
const paired = tasks.filter((t) => t.a.length && t.b.length);
|
|
48
|
+
if (!paired.length)
|
|
49
|
+
return { delta: Number.NaN, lo: Number.NaN, hi: Number.NaN, tasks: 0 };
|
|
50
|
+
const mean = (xs) => xs.reduce((s, x) => s + x, 0) / xs.length;
|
|
51
|
+
const delta = mean(paired.map((t) => stat(t.b) - stat(t.a)));
|
|
52
|
+
const random = rng(options.seed ?? 20261126);
|
|
53
|
+
const pick = (xs) => xs[Math.floor(random() * xs.length)];
|
|
54
|
+
const resample = (xs) => xs.map(() => pick(xs));
|
|
55
|
+
const draws = [];
|
|
56
|
+
for (let i = 0; i < (options.resamples ?? 10_000); i++) {
|
|
57
|
+
const sample = paired.map(() => pick(paired));
|
|
58
|
+
draws.push(mean(sample.map((t) => stat(resample(t.b)) - stat(resample(t.a)))));
|
|
59
|
+
}
|
|
60
|
+
draws.sort((x, y) => x - y);
|
|
61
|
+
const at = (q) => draws[Math.min(draws.length - 1, Math.max(0, Math.floor(q * draws.length)))];
|
|
62
|
+
return { delta, lo: at(0.025), hi: at(0.975), tasks: paired.length };
|
|
63
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-arm and per-task aggregates from results.jsonl, and paired B − A deltas with cluster-bootstrap CIs. Only valid
|
|
3
|
+
* trials count; a rerun trial replaces the earlier record of the same task, arm and number.
|
|
4
|
+
*/
|
|
5
|
+
import { pairedBootstrap, passHatK, taskRate } from "./stats.js";
|
|
6
|
+
export const METRICS = ["outcome", "outcome_pass3", "process", "anchor", "check", "todo_evidence", "close_guard_quiet", "edited_when_should_not", "done_claim_fail"];
|
|
7
|
+
const label = (r, name) => r.process[name]?.label;
|
|
8
|
+
const bit = (l) => (l === "pass" ? 1 : l === "fail" ? 0 : undefined);
|
|
9
|
+
const doing = (r) => r.kind !== "should_not";
|
|
10
|
+
/** A trial's value for a metric, or undefined where the metric does not apply. */
|
|
11
|
+
export function trialValue(r, metric) {
|
|
12
|
+
switch (metric) {
|
|
13
|
+
case "outcome":
|
|
14
|
+
case "outcome_pass3":
|
|
15
|
+
return r.outcome ? 1 : 0;
|
|
16
|
+
case "anchor":
|
|
17
|
+
return doing(r) ? bit(label(r, "anchor_before_first_edit")) : undefined;
|
|
18
|
+
case "check":
|
|
19
|
+
return doing(r) ? bit(label(r, "check_after_last_edit")) : undefined;
|
|
20
|
+
case "process": {
|
|
21
|
+
// 照流程: anchor and check both pass, on tasks that ask for a change and where a change was made.
|
|
22
|
+
if (!doing(r))
|
|
23
|
+
return undefined;
|
|
24
|
+
const a = label(r, "anchor_before_first_edit"), c = label(r, "check_after_last_edit");
|
|
25
|
+
if (a === "na")
|
|
26
|
+
return undefined;
|
|
27
|
+
return a === "pass" && c === "pass" ? 1 : 0;
|
|
28
|
+
}
|
|
29
|
+
case "todo_evidence":
|
|
30
|
+
return bit(label(r, "todo_evidence"));
|
|
31
|
+
case "close_guard_quiet":
|
|
32
|
+
return bit(label(r, "close_guard_quiet"));
|
|
33
|
+
case "edited_when_should_not":
|
|
34
|
+
return r.kind === "should_not" ? (r.editedWhenShouldNot ? 1 : 0) : undefined;
|
|
35
|
+
case "done_claim_fail":
|
|
36
|
+
return r.doneClaimVsOutcome ? 1 : 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** The per-task statistic over that task's trial values: pass^3 for outcome_pass3, else the mean. */
|
|
40
|
+
function statOf(metric, k) {
|
|
41
|
+
return (xs) => (metric === "outcome_pass3" ? passHatK(xs.filter((x) => x === 1).length, xs.length, Math.min(k, xs.length)) : xs.reduce((s, x) => s + x, 0) / xs.length);
|
|
42
|
+
}
|
|
43
|
+
export function latestRecords(records) {
|
|
44
|
+
const by = new Map();
|
|
45
|
+
for (const r of records)
|
|
46
|
+
by.set(`${r.task}\0${r.arm}\0${r.n}`, r);
|
|
47
|
+
return [...by.values()];
|
|
48
|
+
}
|
|
49
|
+
export function summarize(all, arms, options = {}) {
|
|
50
|
+
const records = latestRecords(all);
|
|
51
|
+
const valid = records.filter((r) => r.valid);
|
|
52
|
+
const k = options.k ?? 3;
|
|
53
|
+
const tasks = [...new Set(records.map((r) => r.task))].sort();
|
|
54
|
+
const values = (task, arm, metric) => valid.filter((r) => r.task === task && r.arm === arm).map((r) => trialValue(r, metric)).filter((v) => v !== undefined);
|
|
55
|
+
const armSummaries = arms.map((arm) => {
|
|
56
|
+
const mine = valid.filter((r) => r.arm === arm);
|
|
57
|
+
const metrics = {};
|
|
58
|
+
for (const metric of METRICS) {
|
|
59
|
+
const perTask = tasks.map((t) => {
|
|
60
|
+
const xs = values(t, arm, metric);
|
|
61
|
+
return xs.length ? statOf(metric, k)(xs) : undefined;
|
|
62
|
+
});
|
|
63
|
+
const rate = taskRate(perTask);
|
|
64
|
+
if (rate !== undefined)
|
|
65
|
+
metrics[metric] = rate;
|
|
66
|
+
}
|
|
67
|
+
const cost = mine.reduce((s, r) => s + r.efficiency.cost, 0);
|
|
68
|
+
return {
|
|
69
|
+
arm,
|
|
70
|
+
trials: mine.length,
|
|
71
|
+
invalid: records.filter((r) => r.arm === arm && !r.valid).length,
|
|
72
|
+
metrics,
|
|
73
|
+
costPerTrial: mine.length ? cost / mine.length : 0,
|
|
74
|
+
minutesPerTrial: mine.length ? mine.reduce((s, r) => s + r.efficiency.wallMs, 0) / mine.length / 60_000 : 0,
|
|
75
|
+
costTotal: cost,
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
const pair = arms.length >= 2 ? [arms[0], arms[1]] : undefined;
|
|
79
|
+
const deltas = {};
|
|
80
|
+
if (pair) {
|
|
81
|
+
for (const metric of METRICS) {
|
|
82
|
+
const paired = tasks.map((t) => ({ a: values(t, pair[0], metric), b: values(t, pair[1], metric) }));
|
|
83
|
+
const d = pairedBootstrap(paired, statOf(metric, k), { resamples: options.resamples, seed: options.seed });
|
|
84
|
+
if (d.tasks)
|
|
85
|
+
deltas[metric] = d;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const rows = tasks.map((task) => {
|
|
89
|
+
const kind = records.find((r) => r.task === task)?.kind ?? "";
|
|
90
|
+
const row = { task, kind, arms: {} };
|
|
91
|
+
for (const arm of arms) {
|
|
92
|
+
const xs = values(task, arm, "outcome");
|
|
93
|
+
const p = values(task, arm, "process");
|
|
94
|
+
row.arms[arm] = { pass: xs.filter((x) => x === 1).length, n: xs.length, ...(p.length ? { process: p.reduce((s, x) => s + x, 0) / p.length } : {}) };
|
|
95
|
+
}
|
|
96
|
+
if (pair) {
|
|
97
|
+
const [a, b] = [row.arms[pair[0]], row.arms[pair[1]]];
|
|
98
|
+
if (a.n && b.n)
|
|
99
|
+
row.delta = b.pass / b.n - a.pass / a.n;
|
|
100
|
+
}
|
|
101
|
+
return row;
|
|
102
|
+
});
|
|
103
|
+
// Regressions first: the most negative B − A at the top, never averaged away.
|
|
104
|
+
rows.sort((x, y) => (x.delta ?? 0) - (y.delta ?? 0) || x.task.localeCompare(y.task));
|
|
105
|
+
const doneClaimFail = valid.filter((r) => r.doneClaimVsOutcome).map((r) => ({ task: r.task, arm: r.arm, n: r.n }));
|
|
106
|
+
return { arms: armSummaries, tasks: rows, deltas, ...(pair ? { pair } : {}), doneClaimFail };
|
|
107
|
+
}
|
|
108
|
+
/** Trials whose task the two arms disagree on (outcome or process), plus every done claim on a failed outcome. */
|
|
109
|
+
export function flipped(all, pair) {
|
|
110
|
+
const records = latestRecords(all).filter((r) => r.valid);
|
|
111
|
+
const out = new Set();
|
|
112
|
+
for (const task of new Set(records.map((r) => r.task))) {
|
|
113
|
+
const a = records.filter((r) => r.task === task && r.arm === pair[0]);
|
|
114
|
+
const b = records.filter((r) => r.task === task && r.arm === pair[1]);
|
|
115
|
+
const rate = (xs, m) => taskRate(xs.map((r) => trialValue(r, m)));
|
|
116
|
+
const differs = (m) => rate(a, m) !== rate(b, m);
|
|
117
|
+
if (differs("outcome") || differs("process") || differs("edited_when_should_not"))
|
|
118
|
+
for (const r of [...a, ...b])
|
|
119
|
+
out.add(r);
|
|
120
|
+
}
|
|
121
|
+
for (const r of records)
|
|
122
|
+
if (r.doneClaimVsOutcome)
|
|
123
|
+
out.add(r);
|
|
124
|
+
return [...out];
|
|
125
|
+
}
|
package/dist/exp/task.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A suite is a directory: `suite.json` (model, thinking, forbidden paths), `arms/<name>.json` (extensions, skills and
|
|
3
|
+
* system-prompt files added to the bare flags, paths relative to the suite), and `tasks/<id>/` (task.json, prompt.md,
|
|
4
|
+
* prompt.original.md, optional setup.sh, hidden check/, reference).
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
7
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
8
|
+
const KINDS = ["anchor", "light", "should_not"];
|
|
9
|
+
function json(file) {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function loadSuite(dir) {
|
|
18
|
+
const root = resolve(dir);
|
|
19
|
+
const abs = (p) => (isAbsolute(p) ? p : join(root, p));
|
|
20
|
+
const meta = json(join(root, "suite.json"));
|
|
21
|
+
if (!meta.model || !meta.thinking)
|
|
22
|
+
throw new Error(`${root}/suite.json: model and thinking are required`);
|
|
23
|
+
const arms = new Map();
|
|
24
|
+
for (const file of readdirSync(join(root, "arms")).filter((f) => f.endsWith(".json")).sort()) {
|
|
25
|
+
const name = file.replace(/\.json$/, "");
|
|
26
|
+
const a = json(join(root, "arms", file));
|
|
27
|
+
arms.set(name, { name, extensions: (a.extensions ?? []).map(abs), skills: (a.skills ?? []).map(abs), appendSystemPrompt: (a.appendSystemPrompt ?? []).map(abs) });
|
|
28
|
+
}
|
|
29
|
+
const tasksDir = join(root, "tasks");
|
|
30
|
+
const tasks = readdirSync(tasksDir, { withFileTypes: true })
|
|
31
|
+
.filter((d) => d.isDirectory() && existsSync(join(tasksDir, d.name, "task.json")))
|
|
32
|
+
.map((d) => loadTask(join(tasksDir, d.name)))
|
|
33
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
34
|
+
return { dir: root, model: meta.model, thinking: meta.thinking, forbidden: [...(meta.forbidden ?? []), join(root, "tasks")], ...(meta.followUp ? { followUp: meta.followUp } : {}), extensions: (meta.extensions ?? []).map(abs), arms, tasks };
|
|
35
|
+
}
|
|
36
|
+
export function loadTask(dir) {
|
|
37
|
+
const raw = json(join(dir, "task.json"));
|
|
38
|
+
const where = `${dir}/task.json`;
|
|
39
|
+
if (!raw.id)
|
|
40
|
+
throw new Error(`${where}: id is required`);
|
|
41
|
+
if (!KINDS.includes(raw.kind))
|
|
42
|
+
throw new Error(`${where}: kind must be one of ${KINDS.join(", ")}`);
|
|
43
|
+
const f = raw.fixture ?? {};
|
|
44
|
+
if (!(f.dir || (f.repo && f.base)))
|
|
45
|
+
throw new Error(`${where}: fixture needs dir, or repo and base`);
|
|
46
|
+
if (raw.kind === "should_not") {
|
|
47
|
+
if (!raw.facts?.length || !raw.reference?.answer)
|
|
48
|
+
throw new Error(`${where}: a should_not task needs facts and reference.answer`);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
if (!raw.reference?.patch)
|
|
52
|
+
throw new Error(`${where}: reference.patch is required`);
|
|
53
|
+
if (!existsSync(join(dir, "check", "check.sh")))
|
|
54
|
+
throw new Error(`${dir}: check/check.sh is required`);
|
|
55
|
+
}
|
|
56
|
+
return { ...raw, dir, prompt: readFileSync(join(dir, "prompt.md"), "utf8") };
|
|
57
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One trial: clone the fixture into a fresh work dir outside the run dir, run pi headless with the arm's flags and a
|
|
3
|
+
* private agent dir and session dir, then (only after the agent ended) copy the hidden check in and run it, keep the
|
|
4
|
+
* diff, grade, and delete the work dir.
|
|
5
|
+
*/
|
|
6
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
7
|
+
import { cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { homedir, tmpdir } from "node:os";
|
|
9
|
+
import { basename, join } from "node:path";
|
|
10
|
+
import { stateDir } from "../paths.js";
|
|
11
|
+
import { cloneTree, git } from "./fixture.js";
|
|
12
|
+
import { efficiency, gradeTranscript, readSession, shouldNotOutcome } from "./grade.js";
|
|
13
|
+
export const trialDirOf = (runDir, task, arm, n) => join(runDir, "trials", task, arm, String(n));
|
|
14
|
+
const QUOTA = /usage limit|quota|rate.?limit|too many requests|\b429\b/i;
|
|
15
|
+
/** Every spelling of a path an agent might type: absolute, `~/…`, `$HOME/…` (absolute only when HOME is the trial's). */
|
|
16
|
+
function spellings(path, ownHome) {
|
|
17
|
+
const home = homedir();
|
|
18
|
+
if (ownHome || !path.startsWith(`${home}/`))
|
|
19
|
+
return [path];
|
|
20
|
+
const rest = path.slice(home.length + 1);
|
|
21
|
+
return [path, `~/${rest}`, `$HOME/${rest}`, `\${HOME}/${rest}`];
|
|
22
|
+
}
|
|
23
|
+
export function forbiddenFor(suite, task) {
|
|
24
|
+
const paths = [...suite.forbidden, ...(task.leak_paths ?? []), join(homedir(), ".pi", "agent", "sessions"), join(stateDir(), "experiments")];
|
|
25
|
+
if (task.fixture.repo)
|
|
26
|
+
paths.push(task.fixture.repo);
|
|
27
|
+
return [...new Set(paths.flatMap((p) => spellings(p, task.home === "work")))];
|
|
28
|
+
}
|
|
29
|
+
/** The headless pi command line; `session` resumes that session file (the follow-up turn) instead of starting one. */
|
|
30
|
+
export function piArgs(suite, task, arm, sessionDir, followUp) {
|
|
31
|
+
const a = suite.arms.get(arm);
|
|
32
|
+
if (!a)
|
|
33
|
+
throw new Error(`unknown arm ${arm}; arms: ${[...suite.arms.keys()].join(", ")}`);
|
|
34
|
+
const args = ["-p", "--mode", "json", "--model", suite.model, "--thinking", suite.thinking, "-ns", "-ne", "-nc", "-np", "--no-mcp", "--no-themes", "-na", "--offline", "--session-dir", sessionDir];
|
|
35
|
+
if (followUp)
|
|
36
|
+
args.push("--session", followUp.session);
|
|
37
|
+
for (const e of [...suite.extensions, ...a.extensions])
|
|
38
|
+
args.push("-e", e);
|
|
39
|
+
for (const s of a.skills)
|
|
40
|
+
args.push("--skill", s);
|
|
41
|
+
for (const p of a.appendSystemPrompt)
|
|
42
|
+
args.push("--append-system-prompt", p);
|
|
43
|
+
args.push("--", followUp ? followUp.prompt : task.prompt.trim());
|
|
44
|
+
return args;
|
|
45
|
+
}
|
|
46
|
+
function cleanEnv(extra) {
|
|
47
|
+
const env = {};
|
|
48
|
+
// The parent's pi, Herdr and sb session variables must not reach the trial.
|
|
49
|
+
for (const [k, v] of Object.entries(process.env))
|
|
50
|
+
if (!/^(?:PI_|HERDR_|SB_|PI$)/.test(k))
|
|
51
|
+
env[k] = v;
|
|
52
|
+
return { ...env, ...extra };
|
|
53
|
+
}
|
|
54
|
+
function findSession(dir) {
|
|
55
|
+
if (!existsSync(dir))
|
|
56
|
+
return undefined;
|
|
57
|
+
for (const entry of readdirSync(dir, { withFileTypes: true, recursive: true })) {
|
|
58
|
+
if (entry.isFile() && entry.name.endsWith(".jsonl"))
|
|
59
|
+
return join(entry.parentPath, entry.name);
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
function runAgent(bin, args, cwd, env, trialDir, timeoutMs, suffix = "") {
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const child = spawn(bin, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
66
|
+
child.stdout.pipe(createWriteStream(join(trialDir, `events${suffix}.jsonl`)));
|
|
67
|
+
child.stderr.pipe(createWriteStream(join(trialDir, `stderr${suffix}.txt`)));
|
|
68
|
+
let timedOut = false;
|
|
69
|
+
const timer = setTimeout(() => {
|
|
70
|
+
timedOut = true;
|
|
71
|
+
try {
|
|
72
|
+
process.kill(-child.pid, "SIGTERM");
|
|
73
|
+
}
|
|
74
|
+
catch { }
|
|
75
|
+
setTimeout(() => {
|
|
76
|
+
try {
|
|
77
|
+
process.kill(-child.pid, "SIGKILL");
|
|
78
|
+
}
|
|
79
|
+
catch { }
|
|
80
|
+
}, 10_000).unref();
|
|
81
|
+
}, timeoutMs);
|
|
82
|
+
child.on("error", reject);
|
|
83
|
+
child.on("close", (exit, signal) => {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
resolve({ exit, signal, timedOut });
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function runCheck(task, workDir, env, trialDir) {
|
|
90
|
+
cpSync(join(task.dir, "check"), join(workDir, ".exp-check"), { recursive: true });
|
|
91
|
+
const started = Date.now();
|
|
92
|
+
const r = spawnSync("bash", [join(".exp-check", "check.sh")], { cwd: workDir, env: { ...env, EXP_CHECK_DIR: join(workDir, ".exp-check") }, encoding: "utf8", timeout: (task.check_timeout_s ?? 300) * 1000, maxBuffer: 1 << 26 });
|
|
93
|
+
writeFileSync(join(trialDir, "check.log"), `${r.stdout ?? ""}${r.stderr ?? ""}${r.error ? `\n${r.error.message}\n` : ""}\nexit ${r.status}\n`);
|
|
94
|
+
return { exit: r.status, ms: Date.now() - started };
|
|
95
|
+
}
|
|
96
|
+
/** Grade a finished trial from its stored files; rerunnable after a grader fix. */
|
|
97
|
+
export function gradeTrial(spec) {
|
|
98
|
+
const { suite, task, arm, n, trialDir } = spec;
|
|
99
|
+
const raw = JSON.parse(readFileSync(join(trialDir, "outcome.json"), "utf8"));
|
|
100
|
+
const session = findSession(join(trialDir, "session"));
|
|
101
|
+
const entries = session ? readSession(session) : [];
|
|
102
|
+
const g = gradeTranscript(entries, { kind: task.kind, forbidden: forbiddenFor(suite, task) });
|
|
103
|
+
const eff = efficiency(entries, raw.wallMs);
|
|
104
|
+
let outcome;
|
|
105
|
+
let missingFacts;
|
|
106
|
+
if (task.kind === "should_not") {
|
|
107
|
+
const s = shouldNotOutcome({ finalText: g.finalText, dirty: raw.dirty, edits: g.edits.length, facts: task.facts ?? [] });
|
|
108
|
+
outcome = s.pass;
|
|
109
|
+
missingFacts = s.missing;
|
|
110
|
+
}
|
|
111
|
+
else
|
|
112
|
+
outcome = raw.checkExit === 0;
|
|
113
|
+
const invalid = raw.quota ? "quota" : !session ? "no_session" : eff.turns === 0 ? "no_turn" : g.leak ? `leak: ${g.leak}` : undefined;
|
|
114
|
+
const record = {
|
|
115
|
+
task: task.id,
|
|
116
|
+
kind: task.kind,
|
|
117
|
+
arm,
|
|
118
|
+
n,
|
|
119
|
+
valid: !invalid,
|
|
120
|
+
...(invalid ? { invalid } : {}),
|
|
121
|
+
outcome,
|
|
122
|
+
...(raw.checkExit === undefined ? {} : { checkExit: raw.checkExit }),
|
|
123
|
+
...(missingFacts ? { missingFacts } : {}),
|
|
124
|
+
dirty: raw.dirty,
|
|
125
|
+
process: Object.fromEntries(Object.entries(g.process).map(([k, r]) => [k, { label: r.label, explanation: r.explanation, ...(r.value === undefined ? {} : { value: r.value }) }])),
|
|
126
|
+
...(g.editedWhenShouldNot === undefined ? {} : { editedWhenShouldNot: g.editedWhenShouldNot || raw.dirty }),
|
|
127
|
+
...(g.leak ? { leak: g.leak } : {}),
|
|
128
|
+
claimsDone: g.claimsDone,
|
|
129
|
+
doneClaimVsOutcome: g.claimsDone && !outcome,
|
|
130
|
+
notices: g.notices,
|
|
131
|
+
timedOut: raw.timedOut,
|
|
132
|
+
quota: raw.quota,
|
|
133
|
+
efficiency: eff,
|
|
134
|
+
...(session ? { session } : {}),
|
|
135
|
+
workDir: spec.workDir ?? "",
|
|
136
|
+
};
|
|
137
|
+
writeFileSync(join(trialDir, "grade.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
138
|
+
return record;
|
|
139
|
+
}
|
|
140
|
+
export async function runTrial(spec) {
|
|
141
|
+
const { suite, task, arm, n, runDir, fixture } = spec;
|
|
142
|
+
const trialDir = trialDirOf(runDir, task.id, arm, n);
|
|
143
|
+
// An earlier attempt (a leak rerun) is kept beside it, not overwritten.
|
|
144
|
+
if (existsSync(trialDir))
|
|
145
|
+
renameSync(trialDir, `${trialDir}.prev-${Date.now()}`);
|
|
146
|
+
mkdirSync(trialDir, { recursive: true });
|
|
147
|
+
const box = mkdtempSync(join(spec.tmpRoot ?? tmpdir(), `pi-evals-trial-${basename(runDir)}-${task.id}-${arm}-${n}-`));
|
|
148
|
+
const workDir = join(box, "work");
|
|
149
|
+
cloneTree(fixture, workDir);
|
|
150
|
+
const fixtureHead = git(workDir, "rev-parse", "HEAD");
|
|
151
|
+
const agentDir = join(trialDir, "agent");
|
|
152
|
+
mkdirSync(agentDir, { recursive: true });
|
|
153
|
+
writeFileSync(join(agentDir, "settings.json"), "{}\n");
|
|
154
|
+
if (spec.authFile && existsSync(spec.authFile))
|
|
155
|
+
symlinkSync(spec.authFile, join(agentDir, "auth.json"));
|
|
156
|
+
const sessionDir = join(trialDir, "session");
|
|
157
|
+
mkdirSync(sessionDir, { recursive: true });
|
|
158
|
+
const env = cleanEnv({ PI_CODING_AGENT_DIR: agentDir, PI_OFFLINE: "1", ...(task.home === "work" ? { HOME: workDir } : {}) });
|
|
159
|
+
const args = piArgs(suite, task, arm, sessionDir);
|
|
160
|
+
writeFileSync(join(trialDir, "command.json"), `${JSON.stringify({ bin: spec.piBin ?? "pi", args, cwd: workDir, home: task.home === "work" ? workDir : undefined }, null, 2)}\n`);
|
|
161
|
+
const startedAt = new Date();
|
|
162
|
+
const timeoutMs = (task.timeout_min ?? 60) * 60_000;
|
|
163
|
+
let r = await runAgent(spec.piBin ?? "pi", args, workDir, env, trialDir, timeoutMs);
|
|
164
|
+
// One identical follow-up turn in every arm, so a close-guard notice left at settle can be read and acted on.
|
|
165
|
+
const first = findSession(sessionDir);
|
|
166
|
+
let followedUp = false;
|
|
167
|
+
if (suite.followUp && first && r.exit === 0 && !r.timedOut) {
|
|
168
|
+
const more = piArgs(suite, task, arm, sessionDir, { session: first, prompt: suite.followUp });
|
|
169
|
+
r = await runAgent(spec.piBin ?? "pi", more, workDir, env, trialDir, Math.max(60_000, timeoutMs - (Date.now() - startedAt.getTime())), "-2");
|
|
170
|
+
followedUp = true;
|
|
171
|
+
}
|
|
172
|
+
const endedAt = new Date();
|
|
173
|
+
const dirty = git(workDir, "status", "--porcelain").length > 0 || git(workDir, "rev-parse", "HEAD") !== fixtureHead;
|
|
174
|
+
git(workDir, "add", "-A");
|
|
175
|
+
writeFileSync(join(trialDir, "diff.patch"), execFileSync("git", ["diff", "--cached", "--binary", fixtureHead], { cwd: workDir, maxBuffer: 1 << 28 }));
|
|
176
|
+
const tail = (file) => (existsSync(file) ? readFileSync(file, "utf8").slice(-20_000) : "");
|
|
177
|
+
const suffix = followedUp ? "-2" : "";
|
|
178
|
+
const quota = r.exit !== 0 && QUOTA.test(tail(join(trialDir, `stderr${suffix}.txt`)) + tail(join(trialDir, `events${suffix}.jsonl`)));
|
|
179
|
+
const raw = { exit: r.exit, signal: r.signal, timedOut: r.timedOut, wallMs: endedAt.getTime() - startedAt.getTime(), startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString(), dirty, quota, followedUp };
|
|
180
|
+
if (task.kind !== "should_not") {
|
|
181
|
+
const c = runCheck(task, workDir, cleanEnv(task.home === "work" ? { HOME: workDir } : {}), trialDir);
|
|
182
|
+
raw.checkExit = c.exit;
|
|
183
|
+
raw.checkMs = c.ms;
|
|
184
|
+
}
|
|
185
|
+
writeFileSync(join(trialDir, "outcome.json"), `${JSON.stringify(raw, null, 2)}\n`);
|
|
186
|
+
writeFileSync(join(trialDir, "timing.json"), `${JSON.stringify({ startedAt: raw.startedAt, endedAt: raw.endedAt, wallMs: raw.wallMs, checkMs: raw.checkMs }, null, 2)}\n`);
|
|
187
|
+
const record = gradeTrial({ suite, task, arm, n, trialDir, workDir });
|
|
188
|
+
rmSync(box, { recursive: true, force: true });
|
|
189
|
+
rmSync(join(agentDir, "auth.json"), { force: true });
|
|
190
|
+
return record;
|
|
191
|
+
}
|