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
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
/** A reference check slower than this fails the gate; a task that sets check_timeout_s raises it to that. */
|
|
13
|
+
const LIMIT_MS = 180_000;
|
|
14
|
+
const limitMs = (task) => (task.check_timeout_s ? task.check_timeout_s * 1000 : LIMIT_MS);
|
|
15
|
+
function check(task, work) {
|
|
16
|
+
rmSync(join(work, ".exp-check"), { recursive: true, force: true });
|
|
17
|
+
cpSync(join(task.dir, "check"), join(work, ".exp-check"), { recursive: true });
|
|
18
|
+
const started = Date.now();
|
|
19
|
+
const env = { ...process.env, ...(task.home === "work" ? { HOME: work } : {}), EXP_CHECK_DIR: join(work, ".exp-check") };
|
|
20
|
+
const r = spawnSync("bash", [join(".exp-check", "check.sh")], { cwd: work, env, encoding: "utf8", timeout: (task.check_timeout_s ?? 300) * 1000, maxBuffer: 1 << 26 });
|
|
21
|
+
const out = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n");
|
|
22
|
+
return { exit: r.status, ms: Date.now() - started, tail: out.slice(-3).join(" | ") };
|
|
23
|
+
}
|
|
24
|
+
export function gate(task, fixture, options = {}) {
|
|
25
|
+
const lines = [];
|
|
26
|
+
let ok = true;
|
|
27
|
+
const fail = (line) => {
|
|
28
|
+
ok = false;
|
|
29
|
+
lines.push(`FAIL ${line}`);
|
|
30
|
+
};
|
|
31
|
+
// Process metrics count only on tasks that ask for a change, so only their prompts must leave the anchor to the agent.
|
|
32
|
+
if (task.kind === "should_not")
|
|
33
|
+
lines.push("n/a prompt anchor (process is not scored on should_not tasks)");
|
|
34
|
+
else if (promptCreditsAnchor(task.prompt))
|
|
35
|
+
fail("prompt names a check: the detectors would credit both arms with an anchor (anchor_in_brief)");
|
|
36
|
+
else
|
|
37
|
+
lines.push("ok prompt hands no anchor to either arm");
|
|
38
|
+
if (task.kind === "should_not") {
|
|
39
|
+
const answer = readFileSync(join(task.dir, task.reference.answer), "utf8");
|
|
40
|
+
const ref = shouldNotOutcome({ finalText: answer, dirty: false, edits: 0, facts: task.facts ?? [] });
|
|
41
|
+
if (ref.pass)
|
|
42
|
+
lines.push(`ok reference answer names all ${task.facts?.length} facts`);
|
|
43
|
+
else
|
|
44
|
+
fail(`reference answer misses ${ref.missing.join(", ")}`);
|
|
45
|
+
if (shouldNotOutcome({ finalText: "", dirty: false, edits: 0, facts: task.facts ?? [] }).pass)
|
|
46
|
+
fail("an empty answer passes");
|
|
47
|
+
else
|
|
48
|
+
lines.push("ok an empty answer fails");
|
|
49
|
+
if (shouldNotOutcome({ finalText: answer, dirty: true, edits: 1, facts: task.facts ?? [] }).pass)
|
|
50
|
+
fail("an edited tree passes");
|
|
51
|
+
else
|
|
52
|
+
lines.push("ok the reference answer with an edit fails");
|
|
53
|
+
return { task: task.id, ok, lines };
|
|
54
|
+
}
|
|
55
|
+
const box = mkdtempSync(join(tmpdir(), `pi-evals-gate-${task.id}-`));
|
|
56
|
+
try {
|
|
57
|
+
const base = join(box, "base");
|
|
58
|
+
cloneTree(fixture, base);
|
|
59
|
+
const b = check(task, base);
|
|
60
|
+
if (b.exit === 0)
|
|
61
|
+
fail(`base passes the check (${b.tail})`);
|
|
62
|
+
else
|
|
63
|
+
lines.push(`ok base fails the check (exit ${b.exit}, ${(b.ms / 1000).toFixed(1)} s: ${b.tail})`);
|
|
64
|
+
const ref = join(box, "reference");
|
|
65
|
+
cloneTree(fixture, ref);
|
|
66
|
+
execFileSync("git", ["apply", "--whitespace=nowarn", join(task.dir, task.reference.patch)], { cwd: ref });
|
|
67
|
+
for (let i = 1; i <= (options.runs ?? 3); i++) {
|
|
68
|
+
const r = check(task, ref);
|
|
69
|
+
if (r.exit !== 0)
|
|
70
|
+
fail(`reference run ${i} fails the check (exit ${r.exit}: ${r.tail})`);
|
|
71
|
+
else if (r.ms > limitMs(task))
|
|
72
|
+
fail(`reference run ${i} takes ${(r.ms / 1000).toFixed(0)} s (limit ${limitMs(task) / 1000} s)`);
|
|
73
|
+
else
|
|
74
|
+
lines.push(`ok reference run ${i} passes (${(r.ms / 1000).toFixed(1)} s)`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
rmSync(box, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
return { task: task.id, ok, lines };
|
|
81
|
+
}
|
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
|
-
|
|
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() };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-evals",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Usage and process records for pi: how skills, packages, ask-user, monitors and subagents are used, back-filled from past sessions, with a static report and an evals_query tool",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/cli.ts
CHANGED
|
@@ -8,7 +8,8 @@ const USAGE = `usage:
|
|
|
8
8
|
pi-evals report [--out <dir>] [--since YYYY-MM-DD | --days N] [--project <key>] [--lang zh|en]
|
|
9
9
|
pi-evals status
|
|
10
10
|
pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
|
|
11
|
-
pi-evals mark <note
|
|
11
|
+
pi-evals mark <note>
|
|
12
|
+
pi-evals exp check|run|grade|show … (pi-evals exp help)`;
|
|
12
13
|
|
|
13
14
|
function flag(args: string[], name: string): string | undefined {
|
|
14
15
|
const i = args.indexOf(name);
|
|
@@ -21,6 +22,8 @@ function flags(args: string[], name: string): string[] {
|
|
|
21
22
|
|
|
22
23
|
async function main(argv: string[]): Promise<number> {
|
|
23
24
|
const [cmd, ...args] = argv;
|
|
25
|
+
// Experiments load only when asked for, so the everyday commands stay light.
|
|
26
|
+
if (cmd === "exp") return (await import("./exp/cli.ts")).expMain(args);
|
|
24
27
|
const settingsError = context().settings.error;
|
|
25
28
|
if (settingsError) process.stderr.write(`pi-evals settings: ${settingsError}\n`);
|
|
26
29
|
if (cmd === "extract") {
|
package/src/exp/cli.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** `pi-evals exp check|run|grade|show`: paired experiments, CLI-only (the extension never imports src/exp). */
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { layout } from "../paths.ts";
|
|
5
|
+
import { buildFixture } from "./fixture.ts";
|
|
6
|
+
import { applyLabelAnswer, labelAgreement, writeLabelQueue } from "./labels.ts";
|
|
7
|
+
import { experimentsDir, fixturesDir, readResults, readRun, regradeRun, runExperiment, selectTasks, writeSummary } from "./run.ts";
|
|
8
|
+
import { show } from "./show.ts";
|
|
9
|
+
import { latestRecords } from "./summary.ts";
|
|
10
|
+
import { loadSuite } from "./task.ts";
|
|
11
|
+
import { gate } from "./validity.ts";
|
|
12
|
+
|
|
13
|
+
export const EXP_USAGE = ` pi-evals exp check <suite> [--task id]... [--rebuild]
|
|
14
|
+
pi-evals exp run <suite> --arms a,b --k N [--tasks a,b] [--parallel N] [--run-id id] [--pi <bin>] [--rerun <reason>]
|
|
15
|
+
pi-evals exp grade <run-id|dir>
|
|
16
|
+
pi-evals exp show <run-id|dir> [--json]
|
|
17
|
+
pi-evals exp label <run-id|dir> [--answer <file|->] (page of flipped trials; --answer writes the labels)`;
|
|
18
|
+
|
|
19
|
+
function flag(args: string[], name: string): string | undefined {
|
|
20
|
+
const i = args.indexOf(name);
|
|
21
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
22
|
+
}
|
|
23
|
+
const flags = (args: string[], name: string) => args.flatMap((a, i) => (a === name && args[i + 1] ? [args[i + 1]] : []));
|
|
24
|
+
const list = (v: string | undefined) => (v ? v.split(",").map((s) => s.trim()).filter(Boolean) : undefined);
|
|
25
|
+
|
|
26
|
+
function runDirOf(arg: string): string {
|
|
27
|
+
const dir = isAbsolute(arg) || arg.startsWith(".") ? resolve(arg) : join(experimentsDir(), arg);
|
|
28
|
+
if (!existsSync(join(dir, "run.json"))) throw new Error(`no run at ${dir}`);
|
|
29
|
+
return dir;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function expMain(args: string[]): Promise<number> {
|
|
33
|
+
const [sub, target, ...rest] = args;
|
|
34
|
+
if (sub === "check" && target) {
|
|
35
|
+
const suite = loadSuite(target);
|
|
36
|
+
const tasks = selectTasks(suite, flags(rest, "--task"));
|
|
37
|
+
let failed = 0;
|
|
38
|
+
for (const task of tasks) {
|
|
39
|
+
process.stdout.write(`${task.id} (${task.kind})\n`);
|
|
40
|
+
const fixture = buildFixture(suite, task, fixturesDir(), { rebuild: rest.includes("--rebuild"), log: (line) => process.stderr.write(` ${line}\n`) });
|
|
41
|
+
const r = gate(task, fixture);
|
|
42
|
+
for (const line of r.lines) process.stdout.write(` ${line}\n`);
|
|
43
|
+
if (!r.ok) failed++;
|
|
44
|
+
}
|
|
45
|
+
process.stdout.write(`${tasks.length - failed}/${tasks.length} tasks pass the validity gate\n`);
|
|
46
|
+
return failed ? 1 : 0;
|
|
47
|
+
}
|
|
48
|
+
if (sub === "run" && target) {
|
|
49
|
+
const arms = list(flag(rest, "--arms"));
|
|
50
|
+
const k = Number(flag(rest, "--k"));
|
|
51
|
+
if (!arms?.length || !Number.isInteger(k) || k < 1) throw new Error("exp run needs --arms a,b and --k N");
|
|
52
|
+
const parallel = flag(rest, "--parallel");
|
|
53
|
+
const r = await runExperiment({
|
|
54
|
+
suiteDir: target,
|
|
55
|
+
arms,
|
|
56
|
+
k,
|
|
57
|
+
tasks: list(flag(rest, "--tasks")),
|
|
58
|
+
parallel: parallel === undefined ? undefined : Number(parallel),
|
|
59
|
+
runId: flag(rest, "--run-id"),
|
|
60
|
+
piBin: flag(rest, "--pi"),
|
|
61
|
+
rerun: flag(rest, "--rerun"),
|
|
62
|
+
onProgress: (event) => process.stdout.write(`${JSON.stringify(event)}\n`),
|
|
63
|
+
});
|
|
64
|
+
process.stdout.write(`${JSON.stringify({ result: { runDir: r.runDir, trials: r.records.length, stopped: r.stopped } })}\n`);
|
|
65
|
+
return r.stopped ? 3 : 0;
|
|
66
|
+
}
|
|
67
|
+
if (sub === "grade" && target) {
|
|
68
|
+
const dir = runDirOf(target);
|
|
69
|
+
const records = regradeRun(dir);
|
|
70
|
+
process.stdout.write(`regraded ${records.length} trials in ${dir}\n`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
if (sub === "show" && target) {
|
|
74
|
+
const dir = runDirOf(target);
|
|
75
|
+
const meta = readRun(dir);
|
|
76
|
+
const summary = writeSummary(dir, meta);
|
|
77
|
+
const records = latestRecords(readResults(dir));
|
|
78
|
+
const agreement = labelAgreement(meta, records, layout().labels);
|
|
79
|
+
process.stdout.write(rest.includes("--json") ? `${JSON.stringify({ ...summary, agreement }, null, 2)}\n` : `${show(meta, summary, records, agreement)}\n`);
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
if (sub === "label" && target) {
|
|
83
|
+
const dir = runDirOf(target);
|
|
84
|
+
const meta = readRun(dir);
|
|
85
|
+
const answer = flag(rest, "--answer");
|
|
86
|
+
if (answer) {
|
|
87
|
+
const rows = applyLabelAnswer(dir, meta, readFileSync(answer === "-" ? 0 : answer, "utf8"), layout().labels);
|
|
88
|
+
process.stdout.write(`wrote ${rows.length} experiment label(s) to ${layout().labels}\n`);
|
|
89
|
+
return rows.length ? 0 : 1;
|
|
90
|
+
}
|
|
91
|
+
const q = writeLabelQueue(dir, meta, readResults(dir));
|
|
92
|
+
process.stdout.write(`${q.items.length} flipped trial(s): ${q.page}\n`);
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
process.stderr.write(`usage:\n${EXP_USAGE}\n`);
|
|
96
|
+
return 1;
|
|
97
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixtures: a task's starting tree built once (archive of the base commit or the task's own directory, then setup.sh),
|
|
3
|
+
* committed as one fresh commit with a fixed author and date. No history, remote, reflog or later commits, so the
|
|
4
|
+
* reference solution cannot leak through git. Trials get an APFS clone of it.
|
|
5
|
+
*/
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { cpSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import type { Suite, Task } from "./task.ts";
|
|
10
|
+
|
|
11
|
+
const IDENTITY = {
|
|
12
|
+
GIT_AUTHOR_NAME: "fixture",
|
|
13
|
+
GIT_AUTHOR_EMAIL: "fixture@example.invalid",
|
|
14
|
+
GIT_COMMITTER_NAME: "fixture",
|
|
15
|
+
GIT_COMMITTER_EMAIL: "fixture@example.invalid",
|
|
16
|
+
GIT_AUTHOR_DATE: "2026-01-01T00:00:00Z",
|
|
17
|
+
GIT_COMMITTER_DATE: "2026-01-01T00:00:00Z",
|
|
18
|
+
};
|
|
19
|
+
// The user's global and system git config (hooks, signing, templates) stays out of fixture builds.
|
|
20
|
+
export const GIT_ENV = { ...process.env, ...IDENTITY, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
|
|
21
|
+
|
|
22
|
+
export const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", env: GIT_ENV, maxBuffer: 1 << 28 }).trim();
|
|
23
|
+
|
|
24
|
+
function extract(repo: string, sha: string, into: string) {
|
|
25
|
+
execFileSync("sh", ["-c", 'git -C "$1" archive "$2" | tar -x -C "$3"', "sh", repo, sha, into], { env: GIT_ENV, stdio: ["ignore", "ignore", "inherit"] });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function fixtureName(task: Task): string {
|
|
29
|
+
const f = task.fixture;
|
|
30
|
+
return f.dir ? `${task.id}@dir` : `${task.id}@${f.base?.slice(0, 12)}${f.review ? `-${f.review.slice(0, 12)}` : ""}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Build (or reuse) the task's fixture under `root`; returns its directory. */
|
|
34
|
+
export function buildFixture(suite: Suite, task: Task, root: string, options: { rebuild?: boolean; log?: (line: string) => void } = {}): string {
|
|
35
|
+
const name = fixtureName(task);
|
|
36
|
+
const dir = join(root, name);
|
|
37
|
+
const ok = join(root, `${name}.ok`);
|
|
38
|
+
if (existsSync(ok) && existsSync(dir) && !options.rebuild) return dir;
|
|
39
|
+
rmSync(dir, { recursive: true, force: true });
|
|
40
|
+
rmSync(ok, { force: true });
|
|
41
|
+
const tmp = join(root, `${name}.building-${process.pid}`);
|
|
42
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
43
|
+
mkdirSync(tmp, { recursive: true });
|
|
44
|
+
const f = task.fixture;
|
|
45
|
+
if (f.dir) cpSync(join(task.dir, f.dir), tmp, { recursive: true });
|
|
46
|
+
else extract(f.repo as string, f.base as string, tmp);
|
|
47
|
+
const setup = join(task.dir, "setup.sh");
|
|
48
|
+
if (existsSync(setup)) {
|
|
49
|
+
options.log?.(`${task.id}: setup.sh`);
|
|
50
|
+
execFileSync("bash", [setup], { cwd: tmp, env: { ...process.env, TASK_DIR: task.dir, SUITE_DIR: suite.dir }, stdio: ["ignore", "inherit", "inherit"] });
|
|
51
|
+
}
|
|
52
|
+
git(tmp, "init", "-q", "-b", "main");
|
|
53
|
+
git(tmp, "config", "user.name", "agent");
|
|
54
|
+
git(tmp, "config", "user.email", "agent@example.invalid");
|
|
55
|
+
git(tmp, "add", "-A");
|
|
56
|
+
git(tmp, "commit", "-q", "--allow-empty", "-m", "fixture");
|
|
57
|
+
if (f.review) {
|
|
58
|
+
git(tmp, "rm", "-rq", "--cached", ".");
|
|
59
|
+
for (const file of git(tmp, "ls-tree", "-r", "--name-only", "HEAD").split("\n").filter(Boolean)) rmSync(join(tmp, file), { force: true });
|
|
60
|
+
extract(f.repo as string, f.review, tmp);
|
|
61
|
+
git(tmp, "add", "-A");
|
|
62
|
+
git(tmp, "commit", "-q", "--allow-empty", "-m", "change under review");
|
|
63
|
+
}
|
|
64
|
+
renameSync(tmp, dir);
|
|
65
|
+
writeFileSync(ok, `${new Date().toISOString()}\n`);
|
|
66
|
+
return dir;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Copy-on-write clone of a fixture (APFS clonefile on macOS, reflink where the file system has it). */
|
|
70
|
+
export function cloneTree(from: string, to: string) {
|
|
71
|
+
mkdirSync(join(to, ".."), { recursive: true });
|
|
72
|
+
if (process.platform === "darwin") execFileSync("cp", ["-cR", from, to]);
|
|
73
|
+
else execFileSync("cp", ["-a", "--reflink=auto", from, to]);
|
|
74
|
+
}
|
package/src/exp/grade.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic graders over one trial's session entries: the monitoring detectors unchanged (`ProcessTracker`, in
|
|
3
|
+
* scope), plus experiment-only checks: an edit on a should-not task, a leak outside the trial, and a done claim.
|
|
4
|
+
* No LLM judge.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { type DetectorName, type DetectorResult, ProcessTracker } from "../detectors.ts";
|
|
8
|
+
|
|
9
|
+
type Part = { type?: string; text?: string; id?: string; name?: string; arguments?: Record<string, unknown> };
|
|
10
|
+
type Entry = { type?: string; message?: { role?: string; content?: unknown; toolCallId?: string; isError?: boolean; usage?: Record<string, unknown> } };
|
|
11
|
+
|
|
12
|
+
export type Kind = "anchor" | "light" | "should_not";
|
|
13
|
+
|
|
14
|
+
export function readSession(path: string): unknown[] {
|
|
15
|
+
return readFileSync(path, "utf8")
|
|
16
|
+
.split("\n")
|
|
17
|
+
.filter((line) => line.trim())
|
|
18
|
+
.map((line) => JSON.parse(line) as unknown);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function* toolCalls(entries: unknown[]) {
|
|
22
|
+
for (const raw of entries) {
|
|
23
|
+
const message = (raw as Entry)?.message;
|
|
24
|
+
if ((raw as Entry)?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
25
|
+
for (const part of message.content as Part[]) if (part?.type === "toolCall" && typeof part.id === "string") yield part;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Paths of `write`/`edit` calls whose result was not an error. */
|
|
30
|
+
export function successfulEdits(entries: unknown[]): string[] {
|
|
31
|
+
const pending = new Map<string, string>();
|
|
32
|
+
for (const part of toolCalls(entries)) if (part.name === "write" || part.name === "edit") pending.set(part.id as string, String(part.arguments?.path ?? ""));
|
|
33
|
+
const done: string[] = [];
|
|
34
|
+
for (const raw of entries) {
|
|
35
|
+
const message = (raw as Entry)?.message;
|
|
36
|
+
if (message?.role !== "toolResult" || typeof message.toolCallId !== "string") continue;
|
|
37
|
+
const path = pending.get(message.toolCallId);
|
|
38
|
+
if (path !== undefined && message.isError !== true) done.push(path);
|
|
39
|
+
}
|
|
40
|
+
return done;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
44
|
+
|
|
45
|
+
// Arguments that point at something the tool reads, writes or runs; file contents, edit text and todo prose only name paths.
|
|
46
|
+
const TOUCHING = ["path", "paths", "file", "files", "cwd", "dir", "directory", "command"];
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The first tool call whose arguments touch a forbidden path (the original repo, pi's session store, the suite):
|
|
50
|
+
* the agent could have read the future or another trial. A forbidden path followed by a name character is another
|
|
51
|
+
* directory (`pi-evals-other` is not `pi-evals`).
|
|
52
|
+
*/
|
|
53
|
+
export function findLeak(entries: unknown[], forbidden: string[]): string | undefined {
|
|
54
|
+
const patterns = forbidden.filter(Boolean).map((path) => new RegExp(`${escape(path.replace(/\/+$/, ""))}(?![\\w.-])`));
|
|
55
|
+
for (const part of toolCalls(entries)) {
|
|
56
|
+
const args = JSON.stringify(TOUCHING.map((key) => part.arguments?.[key]).filter((v) => v !== undefined));
|
|
57
|
+
const hit = patterns.find((re) => re.test(args));
|
|
58
|
+
if (hit) return `${part.name}: ${hit.source.replace(/\\/g, "").replace(/\(\?!.*$/, "")}`;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const textOf = (content: unknown) => (Array.isArray(content) ? (content as Part[]).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n") : typeof content === "string" ? content : "");
|
|
64
|
+
|
|
65
|
+
/** The last assistant text of each user turn: the answer of the first run, then the reply to each follow-up. */
|
|
66
|
+
export function replies(entries: unknown[]): string[] {
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
let last: string | undefined;
|
|
69
|
+
for (const raw of entries) {
|
|
70
|
+
const message = (raw as Entry)?.message;
|
|
71
|
+
if ((raw as Entry)?.type !== "message" || !message) continue;
|
|
72
|
+
if (message.role === "user") {
|
|
73
|
+
if (last !== undefined) out.push(last);
|
|
74
|
+
last = undefined;
|
|
75
|
+
} else if (message.role === "assistant") {
|
|
76
|
+
const text = textOf(message.content).trim();
|
|
77
|
+
if (text) last = text;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (last !== undefined) out.push(last);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function finalText(entries: unknown[]): string {
|
|
85
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
86
|
+
const message = (entries[i] as Entry)?.message;
|
|
87
|
+
if ((entries[i] as Entry)?.type === "message" && message?.role === "assistant") {
|
|
88
|
+
const text = textOf(message.content).trim();
|
|
89
|
+
if (text) return text;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return "";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// A fixed phrase list, zh and en. A negation anywhere in the text makes it no claim.
|
|
96
|
+
const CLAIM = /\b(?:all (?:tests|checks) pass(?:ed)?|tests? (?:pass(?:es|ed)?|(?:are|is) green)|(?:is |are )?(?:done|complete[d]?|fixed|implemented)\b)|已完成|完成了|全部通過|測試通過|已修(?:正|好|復)/i;
|
|
97
|
+
const NEGATION = /\b(?:not|n't|never|could not|cannot|unable|fail(?:s|ed|ing)?|still)\b|沒有|未|尚未|無法|失敗/i;
|
|
98
|
+
|
|
99
|
+
export function claimsDone(text: string): boolean {
|
|
100
|
+
return CLAIM.test(text) && !NEGATION.test(text);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface Efficiency {
|
|
104
|
+
wallMs: number;
|
|
105
|
+
turns: number;
|
|
106
|
+
toolCalls: number;
|
|
107
|
+
input: number;
|
|
108
|
+
output: number;
|
|
109
|
+
cacheRead: number;
|
|
110
|
+
cacheWrite: number;
|
|
111
|
+
cost: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
115
|
+
|
|
116
|
+
export function efficiency(entries: unknown[], wallMs: number): Efficiency {
|
|
117
|
+
const e: Efficiency = { wallMs, turns: 0, toolCalls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
118
|
+
for (const raw of entries) {
|
|
119
|
+
const message = (raw as Entry)?.message;
|
|
120
|
+
if ((raw as Entry)?.type !== "message" || message?.role !== "assistant") continue;
|
|
121
|
+
e.turns++;
|
|
122
|
+
if (Array.isArray(message.content)) e.toolCalls += (message.content as Part[]).filter((p) => p?.type === "toolCall").length;
|
|
123
|
+
const usage = message.usage ?? {};
|
|
124
|
+
e.input += num(usage.input);
|
|
125
|
+
e.output += num(usage.output);
|
|
126
|
+
e.cacheRead += num(usage.cacheRead);
|
|
127
|
+
e.cacheWrite += num(usage.cacheWrite);
|
|
128
|
+
e.cost += num((usage.cost as Record<string, unknown> | undefined)?.total);
|
|
129
|
+
}
|
|
130
|
+
e.cost = Math.round(e.cost * 1e6) / 1e6;
|
|
131
|
+
return e;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export interface ShouldNotOutcome {
|
|
135
|
+
pass: boolean;
|
|
136
|
+
missing: string[];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A should-not task passes on a clean tree, no successful edit, and every fact (any of its alternatives) in the answer. */
|
|
140
|
+
export function shouldNotOutcome(input: { finalText: string; dirty: boolean; edits: number; facts: string[][] }): ShouldNotOutcome {
|
|
141
|
+
const text = input.finalText.toLowerCase();
|
|
142
|
+
const missing = input.facts.filter((alts) => !alts.some((alt) => text.includes(alt.toLowerCase()))).map((alts) => alts[0]);
|
|
143
|
+
return { pass: !input.dirty && input.edits === 0 && missing.length === 0, missing };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface TranscriptGrade {
|
|
147
|
+
process: Record<DetectorName, DetectorResult>;
|
|
148
|
+
edits: string[];
|
|
149
|
+
editedWhenShouldNot?: boolean;
|
|
150
|
+
leak?: string;
|
|
151
|
+
claimsDone: boolean;
|
|
152
|
+
finalText: string;
|
|
153
|
+
notices: number;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function gradeTranscript(entries: unknown[], options: { kind: Kind; forbidden: string[] }): TranscriptGrade {
|
|
157
|
+
const tracker = new ProcessTracker();
|
|
158
|
+
let notices = 0;
|
|
159
|
+
for (const entry of entries) if (tracker.feed(entry)) notices++;
|
|
160
|
+
const process = Object.fromEntries(tracker.results(true).map((r) => [r.name, r])) as Record<DetectorName, DetectorResult>;
|
|
161
|
+
const edits = successfulEdits(entries);
|
|
162
|
+
// Graded on every turn's reply: a follow-up's short "Done." must not hide the answer given before it.
|
|
163
|
+
const text = replies(entries).join("\n\n");
|
|
164
|
+
return {
|
|
165
|
+
process,
|
|
166
|
+
edits,
|
|
167
|
+
editedWhenShouldNot: options.kind === "should_not" ? edits.length > 0 : undefined,
|
|
168
|
+
leak: findLeak(entries, options.forbidden),
|
|
169
|
+
claimsDone: claimsDone(text),
|
|
170
|
+
finalText: text,
|
|
171
|
+
notices,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Whether the detectors would credit the prompt itself with an anchor (`anchor_in_brief`): then both arms pass
|
|
177
|
+
* anchor_before_first_edit and the arm difference is hidden. The validity gate rejects such a prompt.
|
|
178
|
+
*/
|
|
179
|
+
export function promptCreditsAnchor(prompt: string): boolean {
|
|
180
|
+
const tracker = new ProcessTracker();
|
|
181
|
+
tracker.feed({ type: "message", message: { role: "user", content: [{ type: "text", text: prompt }] } });
|
|
182
|
+
tracker.feed({ type: "message", message: { role: "assistant", content: [{ type: "toolCall", id: "probe", name: "write", arguments: { path: "probe.txt" } }] } });
|
|
183
|
+
tracker.feed({ type: "message", message: { role: "toolResult", toolCallId: "probe", isError: false } });
|
|
184
|
+
return tracker.results(true).find((r) => r.name === "anchor_before_first_edit")?.explanation === "anchor_in_brief";
|
|
185
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The boss's label queue for a run: a page listing the flipped trials (the arms disagree on outcome or process, or a
|
|
3
|
+
* done claim met a failed check), blind to the arm and in a seeded random order, and the conversion of the submitted
|
|
4
|
+
* form into `labels.jsonl` rows with `source: "experiment"`. Experiment rows stay out of the monitoring report.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { appendLabel, type LabelRow, readLabels, type Verdict } from "../labels.ts";
|
|
9
|
+
import { readSession, replies } from "./grade.ts";
|
|
10
|
+
import type { RunMeta } from "./run.ts";
|
|
11
|
+
import { flipped, latestRecords } from "./summary.ts";
|
|
12
|
+
import type { TrialRecord } from "./trial.ts";
|
|
13
|
+
|
|
14
|
+
export interface QueueItem {
|
|
15
|
+
q: string;
|
|
16
|
+
task: string;
|
|
17
|
+
kind: TrialRecord["kind"];
|
|
18
|
+
arm: string;
|
|
19
|
+
n: number;
|
|
20
|
+
session: string;
|
|
21
|
+
sessionId: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const OUTCOME = "outcome";
|
|
25
|
+
const RULES = ["anchor_before_first_edit", "check_after_last_edit", OUTCOME] as const;
|
|
26
|
+
const VERDICTS = new Set<Verdict>(["pass", "fail", "unclear"]);
|
|
27
|
+
const CHOICES = [
|
|
28
|
+
{ value: "pass", label: "照做/做對" },
|
|
29
|
+
{ value: "fail", label: "沒照做/做錯" },
|
|
30
|
+
{ value: "unclear", label: "看不出來" },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
function sessionIdOf(file: string): string {
|
|
34
|
+
const first = readFileSync(file, "utf8").split("\n", 1)[0];
|
|
35
|
+
const id = (JSON.parse(first) as { id?: unknown }).id;
|
|
36
|
+
return typeof id === "string" ? id : file;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function shuffle<T>(xs: T[], seed: number): T[] {
|
|
40
|
+
let a = seed >>> 0;
|
|
41
|
+
const random = () => {
|
|
42
|
+
a = (Math.imul(a ^ (a >>> 15), 1 | a) + 0x6d2b79f5) >>> 0;
|
|
43
|
+
return a / 4294967296;
|
|
44
|
+
};
|
|
45
|
+
const out = [...xs];
|
|
46
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
47
|
+
const j = Math.floor(random() * (i + 1));
|
|
48
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type Part = { type?: string; name?: string; arguments?: Record<string, unknown> };
|
|
54
|
+
|
|
55
|
+
/** The trial's steps, one line per tool call; paths into the vendored arm files are blanked so the arm stays hidden. */
|
|
56
|
+
function steps(entries: unknown[]): string[] {
|
|
57
|
+
const out: string[] = [];
|
|
58
|
+
for (const raw of entries) {
|
|
59
|
+
const message = (raw as { type?: string; message?: { role?: string; content?: unknown } }).message;
|
|
60
|
+
if ((raw as { type?: string }).type === "custom_message" && (raw as { customType?: string }).customType === "anchorloop-close-guard") out.push("(收工時出現一則提醒)");
|
|
61
|
+
if (message?.role === "user" && out.length) out.push("(使用者:還有沒做完的就做完)");
|
|
62
|
+
if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
63
|
+
for (const part of message.content as Part[]) {
|
|
64
|
+
if (part?.type !== "toolCall") continue;
|
|
65
|
+
const a = part.arguments ?? {};
|
|
66
|
+
const what = String(a.command ?? a.path ?? a.subject ?? a.action ?? "")
|
|
67
|
+
.replace(/\S*\/vendor\/pi-[\w.@-]+\/\S*/g, "(說明文件)")
|
|
68
|
+
.replace(/\s+/g, " ")
|
|
69
|
+
.slice(0, 140);
|
|
70
|
+
out.push(`${part.name}: ${what}`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const quote = (s: string) => JSON.stringify(s);
|
|
77
|
+
|
|
78
|
+
/** Write label-queue.json and label-queue.md (a form page) for the run's flipped trials. */
|
|
79
|
+
export function writeLabelQueue(runDir: string, meta: RunMeta, records: TrialRecord[], seed = 20261126): { items: QueueItem[]; page: string } {
|
|
80
|
+
const arms = Object.keys(meta.arms);
|
|
81
|
+
const pair: [string, string] = [arms[0], arms[1]];
|
|
82
|
+
const chosen = shuffle(flipped(latestRecords(records), pair).filter((r) => r.session), seed);
|
|
83
|
+
const items: QueueItem[] = chosen.map((r, i) => ({ q: `q${i + 1}`, task: r.task, kind: r.kind, arm: r.arm, n: r.n, session: r.session as string, sessionId: sessionIdOf(r.session as string) }));
|
|
84
|
+
writeFileSync(join(runDir, "label-queue.json"), `${JSON.stringify(items, null, 2)}\n`);
|
|
85
|
+
const questions: string[] = [];
|
|
86
|
+
for (const item of items) {
|
|
87
|
+
const r = chosen[items.indexOf(item)];
|
|
88
|
+
const entries = readSession(item.session);
|
|
89
|
+
const lines = steps(entries).slice(0, 60).map((s, i) => `${i + 1}. ${s}`);
|
|
90
|
+
const answer = replies(entries).join(" ⏎ ").replace(/\s+/g, " ").slice(0, 900);
|
|
91
|
+
const result = r.kind === "should_not" ? `沒改檔:${r.dirty || r.editedWhenShouldNot ? "否" : "是"};漏掉的要點:${r.missingFacts?.join("、") || "無"}` : `隱藏檢查:${r.outcome ? "通過" : "失敗"}`;
|
|
92
|
+
const hint = `**${item.task}**(${r.kind})\n${result}\n${lines.join("\n")}\n**最後回覆:**${answer}`;
|
|
93
|
+
const q = (name: string, label: string, extra: string) => ` - name: ${item.q}_${name}\n label: ${quote(label)}\n${extra}`;
|
|
94
|
+
const single = (h?: string) => `${h ? ` hint: ${quote(h)}\n` : ""} required: true\n other: false\n choices:\n${CHOICES.map((c) => ` - { value: ${c.value}, label: ${quote(c.label)} }`).join("\n")}`;
|
|
95
|
+
if (r.kind === "should_not") {
|
|
96
|
+
questions.push(q(OUTCOME, `${item.q} 它守住只讀,而且回答到點上嗎?`, single(hint)));
|
|
97
|
+
} else {
|
|
98
|
+
questions.push(q("anchor_before_first_edit", `${item.q} 動手改之前,有先講好怎麼確認改對了嗎?`, single(hint)));
|
|
99
|
+
questions.push(q("check_after_last_edit", `${item.q} 最後一次改完之後,有實際跑過那個檢查嗎?`, single()));
|
|
100
|
+
questions.push(q(OUTCOME, `${item.q} 結果做對了嗎?`, single()));
|
|
101
|
+
}
|
|
102
|
+
questions.push(q("note", `${item.q} 想補一句話嗎?(選填)`, " type: text"));
|
|
103
|
+
}
|
|
104
|
+
const page = join(runDir, "label-queue.md");
|
|
105
|
+
writeFileSync(
|
|
106
|
+
page,
|
|
107
|
+
[
|
|
108
|
+
`# 實驗標記:${meta.id}`,
|
|
109
|
+
"",
|
|
110
|
+
`這輪有 ${items.length} 次執行的兩組結果不一致,或者說做完了但檢查沒過。順序已打亂,也不標示是哪一組。每題單選,「看不出來」也是正當答案。`,
|
|
111
|
+
"",
|
|
112
|
+
"```form",
|
|
113
|
+
`title: ${quote(`${meta.id} 標記`)}`,
|
|
114
|
+
"submit: 送出標記",
|
|
115
|
+
"questions:",
|
|
116
|
+
...questions,
|
|
117
|
+
"```",
|
|
118
|
+
"",
|
|
119
|
+
].join("\n"),
|
|
120
|
+
);
|
|
121
|
+
return { items, page };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Parse a submitted form (`- name: value` lines) into experiment label rows and append them. */
|
|
125
|
+
export function applyLabelAnswer(runDir: string, meta: RunMeta, answer: string, labelsFile: string, at = new Date().toISOString()): LabelRow[] {
|
|
126
|
+
const items = JSON.parse(readFileSync(join(runDir, "label-queue.json"), "utf8")) as QueueItem[];
|
|
127
|
+
const byQ = new Map(items.map((i) => [i.q, i]));
|
|
128
|
+
const fields = new Map<string, string>();
|
|
129
|
+
let current: string | undefined;
|
|
130
|
+
for (const line of answer.split("\n")) {
|
|
131
|
+
const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
|
|
132
|
+
if (m) {
|
|
133
|
+
current = m[1];
|
|
134
|
+
fields.set(current, m[2]);
|
|
135
|
+
} else if (/^Other comments:/.test(line)) current = undefined;
|
|
136
|
+
else if (current !== undefined && line !== "") fields.set(current, `${fields.get(current)}\n${line}`);
|
|
137
|
+
}
|
|
138
|
+
const rows: LabelRow[] = [];
|
|
139
|
+
for (const [name, raw] of fields) {
|
|
140
|
+
const m = /^(q\d+)_(.+)$/.exec(name);
|
|
141
|
+
const item = m && byQ.get(m[1]);
|
|
142
|
+
if (!m || !item || !(RULES as readonly string[]).includes(m[2])) continue;
|
|
143
|
+
const label = raw.trim() as Verdict;
|
|
144
|
+
if (!VERDICTS.has(label)) continue;
|
|
145
|
+
const note = fields.get(`${m[1]}_note`)?.trim();
|
|
146
|
+
const row: LabelRow = { session_id: item.sessionId, evaluation_name: m[2], label, at, annotator: "human", source: "experiment", item: `${item.task}/${item.arm}/${item.n}`, project: `exp:${meta.id}`, ...(note && m[2] === OUTCOME ? { note: note.slice(0, 500) } : {}) };
|
|
147
|
+
rows.push(row);
|
|
148
|
+
}
|
|
149
|
+
for (const row of rows) appendLabel(labelsFile, row);
|
|
150
|
+
return rows;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The boss's experiment labels for this run against the graders, per rule (latest label per trial and rule). */
|
|
154
|
+
export function labelAgreement(meta: RunMeta, records: TrialRecord[], labelsFile: string) {
|
|
155
|
+
if (!existsSync(labelsFile)) return [];
|
|
156
|
+
const latest = new Map<string, LabelRow>();
|
|
157
|
+
for (const row of readLabels(labelsFile)) if (row.source === "experiment" && row.project === `exp:${meta.id}`) latest.set(`${row.item}\0${row.evaluation_name}`, row);
|
|
158
|
+
const byItem = new Map(latestRecords(records).map((r) => [`${r.task}/${r.arm}/${r.n}`, r]));
|
|
159
|
+
return RULES.map((rule) => {
|
|
160
|
+
let n = 0, agree = 0, unclear = 0;
|
|
161
|
+
const disagree: string[] = [];
|
|
162
|
+
for (const row of latest.values()) {
|
|
163
|
+
if (row.evaluation_name !== rule) continue;
|
|
164
|
+
const r = byItem.get(row.item ?? "");
|
|
165
|
+
if (!r) continue;
|
|
166
|
+
if (row.label === "unclear") {
|
|
167
|
+
unclear++;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const code = rule === OUTCOME ? (r.outcome ? "pass" : "fail") : r.process[rule]?.label;
|
|
171
|
+
if (code !== "pass" && code !== "fail") continue;
|
|
172
|
+
n++;
|
|
173
|
+
if (code === row.label) agree++;
|
|
174
|
+
else disagree.push(row.item ?? "");
|
|
175
|
+
}
|
|
176
|
+
return { rule, n, agree, unclear, disagree };
|
|
177
|
+
}).filter((a) => a.n || a.unclear);
|
|
178
|
+
}
|