pi-evals 0.6.1 → 0.8.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +36 -0
  3. package/dist/analysis.js +314 -0
  4. package/dist/cli.js +5 -1
  5. package/dist/detectors.js +3 -1
  6. package/dist/exp/cli.js +97 -0
  7. package/dist/exp/fixture.js +73 -0
  8. package/dist/exp/grade.js +156 -0
  9. package/dist/exp/labels.js +172 -0
  10. package/dist/exp/run.js +154 -0
  11. package/dist/exp/show.js +54 -0
  12. package/dist/exp/stats.js +63 -0
  13. package/dist/exp/summary.js +125 -0
  14. package/dist/exp/task.js +57 -0
  15. package/dist/exp/trial.js +191 -0
  16. package/dist/exp/validity.js +79 -0
  17. package/dist/index.js +43 -3
  18. package/dist/labels.js +2 -1
  19. package/dist/plan-graph.js +5 -1
  20. package/dist/shape.js +149 -0
  21. package/package.json +1 -1
  22. package/scripts/by-version.mjs +9 -0
  23. package/scripts/disagree.mjs +9 -0
  24. package/scripts/freshness.mjs +7 -0
  25. package/scripts/label-import.mjs +9 -0
  26. package/scripts/query-lib.mjs +41 -11
  27. package/scripts/sample.mjs +9 -0
  28. package/scripts/session-shape.mjs +8 -0
  29. package/skills/analyzing-evals/SKILL.md +8 -5
  30. package/src/analysis.ts +275 -0
  31. package/src/cli.ts +4 -1
  32. package/src/detectors.ts +3 -1
  33. package/src/exp/cli.ts +97 -0
  34. package/src/exp/fixture.ts +74 -0
  35. package/src/exp/grade.ts +185 -0
  36. package/src/exp/labels.ts +178 -0
  37. package/src/exp/run.ts +178 -0
  38. package/src/exp/show.ts +57 -0
  39. package/src/exp/stats.ts +77 -0
  40. package/src/exp/summary.ts +149 -0
  41. package/src/exp/task.ts +100 -0
  42. package/src/exp/trial.ts +239 -0
  43. package/src/exp/validity.ts +74 -0
  44. package/src/index.ts +44 -3
  45. package/src/labels.ts +4 -2
  46. package/src/plan-graph.ts +6 -1
  47. package/src/shape.ts +123 -0
@@ -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
+ }
@@ -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
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The validity gate per task: the fixture builds; the prompt does not hand both arms an anchor; the base fails the
3
+ * hidden check; the reference passes it 3 of 3 times (flake screen), each run under 3 minutes. For should-not tasks the
4
+ * reference answer passes the fact list on a clean tree and an empty answer fails it.
5
+ */
6
+ import { execFileSync, spawnSync } from "node:child_process";
7
+ import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { cloneTree } from "./fixture.js";
11
+ import { promptCreditsAnchor, shouldNotOutcome } from "./grade.js";
12
+ const LIMIT_MS = 180_000;
13
+ function check(task, work) {
14
+ rmSync(join(work, ".exp-check"), { recursive: true, force: true });
15
+ cpSync(join(task.dir, "check"), join(work, ".exp-check"), { recursive: true });
16
+ const started = Date.now();
17
+ const env = { ...process.env, ...(task.home === "work" ? { HOME: work } : {}), EXP_CHECK_DIR: join(work, ".exp-check") };
18
+ const r = spawnSync("bash", [join(".exp-check", "check.sh")], { cwd: work, env, encoding: "utf8", timeout: (task.check_timeout_s ?? 300) * 1000, maxBuffer: 1 << 26 });
19
+ const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n");
20
+ return { exit: r.status, ms: Date.now() - started, tail: out.slice(-3).join(" | ") };
21
+ }
22
+ export function gate(task, fixture, options = {}) {
23
+ const lines = [];
24
+ let ok = true;
25
+ const fail = (line) => {
26
+ ok = false;
27
+ lines.push(`FAIL ${line}`);
28
+ };
29
+ // Process metrics count only on tasks that ask for a change, so only their prompts must leave the anchor to the agent.
30
+ if (task.kind === "should_not")
31
+ lines.push("n/a prompt anchor (process is not scored on should_not tasks)");
32
+ else if (promptCreditsAnchor(task.prompt))
33
+ fail("prompt names a check: the detectors would credit both arms with an anchor (anchor_in_brief)");
34
+ else
35
+ lines.push("ok prompt hands no anchor to either arm");
36
+ if (task.kind === "should_not") {
37
+ const answer = readFileSync(join(task.dir, task.reference.answer), "utf8");
38
+ const ref = shouldNotOutcome({ finalText: answer, dirty: false, edits: 0, facts: task.facts ?? [] });
39
+ if (ref.pass)
40
+ lines.push(`ok reference answer names all ${task.facts?.length} facts`);
41
+ else
42
+ fail(`reference answer misses ${ref.missing.join(", ")}`);
43
+ if (shouldNotOutcome({ finalText: "", dirty: false, edits: 0, facts: task.facts ?? [] }).pass)
44
+ fail("an empty answer passes");
45
+ else
46
+ lines.push("ok an empty answer fails");
47
+ if (shouldNotOutcome({ finalText: answer, dirty: true, edits: 1, facts: task.facts ?? [] }).pass)
48
+ fail("an edited tree passes");
49
+ else
50
+ lines.push("ok the reference answer with an edit fails");
51
+ return { task: task.id, ok, lines };
52
+ }
53
+ const box = mkdtempSync(join(tmpdir(), `pi-evals-gate-${task.id}-`));
54
+ try {
55
+ const base = join(box, "base");
56
+ cloneTree(fixture, base);
57
+ const b = check(task, base);
58
+ if (b.exit === 0)
59
+ fail(`base passes the check (${b.tail})`);
60
+ else
61
+ lines.push(`ok base fails the check (exit ${b.exit}, ${(b.ms / 1000).toFixed(1)} s: ${b.tail})`);
62
+ const ref = join(box, "reference");
63
+ cloneTree(fixture, ref);
64
+ execFileSync("git", ["apply", "--whitespace=nowarn", join(task.dir, task.reference.patch)], { cwd: ref });
65
+ for (let i = 1; i <= (options.runs ?? 3); i++) {
66
+ const r = check(task, ref);
67
+ if (r.exit !== 0)
68
+ fail(`reference run ${i} fails the check (exit ${r.exit}: ${r.tail})`);
69
+ else if (r.ms > LIMIT_MS)
70
+ fail(`reference run ${i} takes ${(r.ms / 1000).toFixed(0)} s (limit ${LIMIT_MS / 1000} s)`);
71
+ else
72
+ lines.push(`ok reference run ${i} passes (${(r.ms / 1000).toFixed(1)} s)`);
73
+ }
74
+ }
75
+ finally {
76
+ rmSync(box, { recursive: true, force: true });
77
+ }
78
+ return { task: task.id, ok, lines };
79
+ }
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), `/ask-ai`, and the `evals_query` and `evals_label` tools.
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label, run), `/ask-ai`, and the `evals_query` and `evals_label` tools.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
@@ -20,7 +20,30 @@ export function cliPath() {
20
20
  const found = candidates.find((p) => existsSync(p));
21
21
  return found ? { cmd: process.execPath, args: [found] } : undefined;
22
22
  }
23
- const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label"];
23
+ const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label", "run"];
24
+ /** The shipped analysis scripts (`scripts/<name>.mjs`) `/evals run` offers, with what each is for. */
25
+ export const SCRIPTS = {
26
+ freshness: "索引是不是最新的:最後擷取時間、各擷取器版本的摘要數;版本混雜時數字不能看",
27
+ disagree: "某條規則上程式判定和你的標記哪裡不一致,逐段列出,看偏哪一邊(用法:disagree <規則> [--range 天數])",
28
+ "by-version": "某項檢查在各套件版本下的通過率(用法:by-version <檢查> [--pkg 套件])",
29
+ sample: "分層抽樣還沒標過的工作段,給你手動標記(只有 id 與屬性)(用法:sample <數量> [--since 時間] [--seed 數字])",
30
+ "label-import": "把填好的標記表單答案寫進 labels.jsonl(用法:label-import <答案檔> [--sample 樣本檔])",
31
+ "session-shape": "一段工作的結構軌跡:檢查看到的事件順序,不含訊息內容(用法:session-shape <session id>)",
32
+ "change-impact": "某次調整前後的數字(用法:change-impact <時間或 sha> [套件或種類])",
33
+ "skill-days": "某個 skill 每天被載入的工作段數(用法:skill-days <skill> [專案])",
34
+ "package-errors": "某個套件每天的工具出錯數(用法:package-errors <套件> [專案])",
35
+ };
36
+ /** Runs one shipped script with the session's environment; resolves with its exit code and output. */
37
+ function runScript(name, args, env) {
38
+ return new Promise((resolve) => {
39
+ const child = spawn(process.execPath, [fileURLToPath(new URL(`../scripts/${name}.mjs`, import.meta.url)), ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
40
+ let out = "";
41
+ child.stdout?.on("data", (c) => void (out += c.toString()));
42
+ child.stderr?.on("data", (c) => void (out += c.toString()));
43
+ child.on("error", (error) => resolve({ code: -1, out: error.message }));
44
+ child.on("close", (code) => resolve({ code, out: out.trim() }));
45
+ });
46
+ }
24
47
  function parseFlags(args) {
25
48
  const out = { rest: [] };
26
49
  for (let i = 0; i < args.length; i++) {
@@ -102,8 +125,12 @@ export function createEvals(options = {}) {
102
125
  });
103
126
  };
104
127
  pi.registerCommand("evals", {
105
- description: "Usage and process records: /evals [status|findings|extract|report|mark <note>|label]",
128
+ description: "Usage and process records: /evals [status|findings|extract|report|mark <note>|label|run <script>]",
106
129
  getArgumentCompletions: (prefix) => {
130
+ if (prefix.startsWith("run ")) {
131
+ const names = Object.keys(SCRIPTS).filter((n) => n.startsWith(prefix.slice(4)));
132
+ return names.length ? names.map((n) => ({ value: `run ${n}`, label: n, description: SCRIPTS[n] })) : null;
133
+ }
107
134
  const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
108
135
  return items.length ? items : null;
109
136
  },
@@ -149,6 +176,19 @@ export function createEvals(options = {}) {
149
176
  else if (sub === "label") {
150
177
  await labels.command(words.slice(1), ctx);
151
178
  }
179
+ else if (sub === "run") {
180
+ const name = words[1];
181
+ if (!name) {
182
+ ctx.ui.notify(`pi-evals scripts (/evals run <script> [args]):\n${Object.entries(SCRIPTS).map(([n, what]) => `${n} ${what}`).join("\n")}`, "info");
183
+ return;
184
+ }
185
+ if (!Object.hasOwn(SCRIPTS, name)) {
186
+ ctx.ui.notify(`Unknown script "${name}". /evals run lists them.`, "warning");
187
+ return;
188
+ }
189
+ const { code, out } = await runScript(name, words.slice(2), env);
190
+ ctx.ui.notify(out || `${name}: no output (exit ${code})`, code === 0 ? "info" : "warning");
191
+ }
152
192
  else {
153
193
  ctx.ui.notify(`Unknown subcommand "${sub}". Use: ${SUBCOMMANDS.join(", ")}.`, "warning");
154
194
  }
package/dist/labels.js CHANGED
@@ -154,7 +154,8 @@ export function labelsModel(labelsFile, evalsFile, scope, versionOf) {
154
154
  return true;
155
155
  return r.source !== undefined && !scope.indexed?.has(id) && typeof r.at === "string" && inDates(r.at) && (!scope.project || r.project === scope.project);
156
156
  };
157
- const rows = readLabels(labelsFile).filter(inScope);
157
+ // Experiment trials are not production sessions: their labels are read by `pi-evals exp show` only.
158
+ const rows = readLabels(labelsFile).filter((r) => r.source !== "experiment" && inScope(r));
158
159
  const human = rows.filter((r) => r.annotator !== "agent");
159
160
  const by = new Map();
160
161
  const sessions = { batch: new Set(), live: new Set() };
@@ -31,6 +31,10 @@ function text(content) {
31
31
  return content;
32
32
  return Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "";
33
33
  }
34
+ /** A main's kind from the sb role prompt section, if it is a main's prompt. */
35
+ export function sbKindOf(section) {
36
+ return STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1];
37
+ }
34
38
  export class PlanGraphTracker {
35
39
  kind;
36
40
  wasMain = false;
@@ -65,7 +69,7 @@ export class PlanGraphTracker {
65
69
  const section = obj(message.sections)["straw-boss"];
66
70
  if (typeof section !== "string")
67
71
  return;
68
- this.setKind(STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1]);
72
+ this.setKind(sbKindOf(section));
69
73
  }
70
74
  else if (message.role === "assistant" && Array.isArray(message.content)) {
71
75
  for (const raw of message.content) {