pi-evals 0.7.0 → 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.
- package/CHANGELOG.md +7 -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 +79 -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 +74 -0
- package/src/labels.ts +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.8.0
|
|
4
|
+
|
|
5
|
+
- New CLI command `pi-evals exp` runs controlled, paired experiments: the same tasks under two arms (for example without and with anchorloop) with the same model, so a difference can be put down to the arm. `exp check` confirms a task's base fails its check and its reference passes it 3 of 3; `exp run` runs k trials per task and arm, each with one identical follow-up turn; `exp grade` regrades stored trials after a grader fix; `exp show` gives pass@1, pass^k, process rates, cost and minutes per trial, and B − A with a paired cluster-bootstrap 95% CI over tasks.
|
|
6
|
+
- `exp run --tasks` reruns chosen tasks inside an existing run; the replaced trials are kept, marked superseded.
|
|
7
|
+
- `exp label` writes a blind form page of the trials where the arms disagree; `--answer` stores your verdicts in `labels.jsonl` with `source: "experiment"`, and `exp show` compares them with the graders. The monitoring report leaves these labels out.
|
|
8
|
+
- Answers are graded on every turn's reply, and leaks are read only from paths the trial touched.
|
|
9
|
+
|
|
3
10
|
## 0.7.0
|
|
4
11
|
|
|
5
12
|
- The analysis scripts from labelling and error analysis ship in `scripts/`: `freshness` (is the index current; exits 1 when summaries come from mixed extractor versions), `disagree <rule>` (where the code and your labels disagree, session by session, and which way), `by-version <detector>` (pass rate per package version), `sample <n>` (a stratified, seeded sample of unlabelled sessions to label), `label-import <answers>` (a submitted label form into `labels.jsonl`), and `session-shape <id>` (the ordered events the detectors see, without message text). Output over 2,000 bytes goes to a file under `runs/` in the state dir.
|
package/README.md
CHANGED
|
@@ -99,6 +99,26 @@ pi-evals query <view> [--since YYYY-MM-DD] [--project <key>]
|
|
|
99
99
|
pi-evals mark <note>
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
+
### Experiments: `pi-evals exp`
|
|
103
|
+
|
|
104
|
+
Monitoring watches real sessions, where task, model and your steering vary together. `pi-evals exp` runs the same tasks twice, once per arm (for example without and with anchorloop), with the same model, so a difference can be put down to the arm. It runs from the CLI only; the extension never loads it.
|
|
105
|
+
|
|
106
|
+
A suite is a directory you keep: `suite.json` (model, thinking, an optional follow-up message every trial gets, paths no trial may touch), `arms/<name>.json` (extensions, skills and system-prompt files an arm adds), and `tasks/<id>/` with `task.json`, `prompt.md`, an optional `setup.sh`, a hidden `check/check.sh`, and the reference solution (`reference.patch`, or `reference.md` and a fact list for a task that must change nothing).
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
pi-evals exp check <suite> [--task id]... # base fails the check, reference passes it 3 of 3
|
|
110
|
+
pi-evals exp run <suite> --arms a,b --k 3 [--tasks a,b] [--parallel 3] [--run-id id]
|
|
111
|
+
pi-evals exp grade <run-id> # regrade stored trials after a grader fix
|
|
112
|
+
pi-evals exp show <run-id> [--json] # per-arm rates, B − A with a 95% CI, per-task table
|
|
113
|
+
pi-evals exp label <run-id> [--answer <file|->]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Each task's starting tree is built once as a single fresh commit (no history, remote or later commits) and cloned per trial into a temporary directory. pi runs headless with its own agent dir and session dir. The hidden check is copied in only after the agent ends. Outcome comes from `check.sh`, or for a must-not-change task from a clean tree plus the fact list. Process comes from the same detectors the report uses. A tool call that touches the original repository, pi's sessions or the suite's tasks makes the trial invalid; it is rerun once. The run stops at the first quota refusal. Trials are interleaved per task (A1 B1 A2 B2 …), so a stopped run stays paired.
|
|
117
|
+
|
|
118
|
+
`exp show` gives pass@1, pass^k (all of k trials pass), the process rates, cost and minutes per trial, and B − A with a paired cluster-bootstrap 95% CI over tasks. `exp label` writes a form page listing the trials where the arms disagree, without saying which arm ran them; `--answer` stores your verdicts in `labels.jsonl` with `source: "experiment"`. `exp show` compares them with the graders, and the monitoring report leaves them out.
|
|
119
|
+
|
|
120
|
+
Runs are kept in `~/.local/state/pi-evals/experiments/<run-id>/` and built fixtures in `~/.local/state/pi-evals/fixtures/`.
|
|
121
|
+
|
|
102
122
|
### The `evals_query` tool
|
|
103
123
|
|
|
104
124
|
Start with `findings` (under 1,500 bytes), then follow one pointer if you need the counts.
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,8 @@ const USAGE = `usage:
|
|
|
7
7
|
pi-evals report [--out <dir>] [--since YYYY-MM-DD | --days N] [--project <key>] [--lang zh|en]
|
|
8
8
|
pi-evals status
|
|
9
9
|
pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
|
|
10
|
-
pi-evals mark <note
|
|
10
|
+
pi-evals mark <note>
|
|
11
|
+
pi-evals exp check|run|grade|show … (pi-evals exp help)`;
|
|
11
12
|
function flag(args, name) {
|
|
12
13
|
const i = args.indexOf(name);
|
|
13
14
|
return i >= 0 ? args[i + 1] : undefined;
|
|
@@ -17,6 +18,9 @@ function flags(args, name) {
|
|
|
17
18
|
}
|
|
18
19
|
async function main(argv) {
|
|
19
20
|
const [cmd, ...args] = argv;
|
|
21
|
+
// Experiments load only when asked for, so the everyday commands stay light.
|
|
22
|
+
if (cmd === "exp")
|
|
23
|
+
return (await import("./exp/cli.js")).expMain(args);
|
|
20
24
|
const settingsError = context().settings.error;
|
|
21
25
|
if (settingsError)
|
|
22
26
|
process.stderr.write(`pi-evals settings: ${settingsError}\n`);
|
package/dist/exp/cli.js
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.js";
|
|
5
|
+
import { buildFixture } from "./fixture.js";
|
|
6
|
+
import { applyLabelAnswer, labelAgreement, writeLabelQueue } from "./labels.js";
|
|
7
|
+
import { experimentsDir, fixturesDir, readResults, readRun, regradeRun, runExperiment, selectTasks, writeSummary } from "./run.js";
|
|
8
|
+
import { show } from "./show.js";
|
|
9
|
+
import { latestRecords } from "./summary.js";
|
|
10
|
+
import { loadSuite } from "./task.js";
|
|
11
|
+
import { gate } from "./validity.js";
|
|
12
|
+
export const EXP_USAGE = ` pi-evals exp check <suite> [--task id]... [--rebuild]
|
|
13
|
+
pi-evals exp run <suite> --arms a,b --k N [--tasks a,b] [--parallel N] [--run-id id] [--pi <bin>] [--rerun <reason>]
|
|
14
|
+
pi-evals exp grade <run-id|dir>
|
|
15
|
+
pi-evals exp show <run-id|dir> [--json]
|
|
16
|
+
pi-evals exp label <run-id|dir> [--answer <file|->] (page of flipped trials; --answer writes the labels)`;
|
|
17
|
+
function flag(args, name) {
|
|
18
|
+
const i = args.indexOf(name);
|
|
19
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
20
|
+
}
|
|
21
|
+
const flags = (args, name) => args.flatMap((a, i) => (a === name && args[i + 1] ? [args[i + 1]] : []));
|
|
22
|
+
const list = (v) => (v ? v.split(",").map((s) => s.trim()).filter(Boolean) : undefined);
|
|
23
|
+
function runDirOf(arg) {
|
|
24
|
+
const dir = isAbsolute(arg) || arg.startsWith(".") ? resolve(arg) : join(experimentsDir(), arg);
|
|
25
|
+
if (!existsSync(join(dir, "run.json")))
|
|
26
|
+
throw new Error(`no run at ${dir}`);
|
|
27
|
+
return dir;
|
|
28
|
+
}
|
|
29
|
+
export async function expMain(args) {
|
|
30
|
+
const [sub, target, ...rest] = args;
|
|
31
|
+
if (sub === "check" && target) {
|
|
32
|
+
const suite = loadSuite(target);
|
|
33
|
+
const tasks = selectTasks(suite, flags(rest, "--task"));
|
|
34
|
+
let failed = 0;
|
|
35
|
+
for (const task of tasks) {
|
|
36
|
+
process.stdout.write(`${task.id} (${task.kind})\n`);
|
|
37
|
+
const fixture = buildFixture(suite, task, fixturesDir(), { rebuild: rest.includes("--rebuild"), log: (line) => process.stderr.write(` ${line}\n`) });
|
|
38
|
+
const r = gate(task, fixture);
|
|
39
|
+
for (const line of r.lines)
|
|
40
|
+
process.stdout.write(` ${line}\n`);
|
|
41
|
+
if (!r.ok)
|
|
42
|
+
failed++;
|
|
43
|
+
}
|
|
44
|
+
process.stdout.write(`${tasks.length - failed}/${tasks.length} tasks pass the validity gate\n`);
|
|
45
|
+
return failed ? 1 : 0;
|
|
46
|
+
}
|
|
47
|
+
if (sub === "run" && target) {
|
|
48
|
+
const arms = list(flag(rest, "--arms"));
|
|
49
|
+
const k = Number(flag(rest, "--k"));
|
|
50
|
+
if (!arms?.length || !Number.isInteger(k) || k < 1)
|
|
51
|
+
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,73 @@
|
|
|
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
|
+
const IDENTITY = {
|
|
10
|
+
GIT_AUTHOR_NAME: "fixture",
|
|
11
|
+
GIT_AUTHOR_EMAIL: "fixture@example.invalid",
|
|
12
|
+
GIT_COMMITTER_NAME: "fixture",
|
|
13
|
+
GIT_COMMITTER_EMAIL: "fixture@example.invalid",
|
|
14
|
+
GIT_AUTHOR_DATE: "2026-01-01T00:00:00Z",
|
|
15
|
+
GIT_COMMITTER_DATE: "2026-01-01T00:00:00Z",
|
|
16
|
+
};
|
|
17
|
+
// The user's global and system git config (hooks, signing, templates) stays out of fixture builds.
|
|
18
|
+
export const GIT_ENV = { ...process.env, ...IDENTITY, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
|
|
19
|
+
export const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8", env: GIT_ENV, maxBuffer: 1 << 28 }).trim();
|
|
20
|
+
function extract(repo, sha, into) {
|
|
21
|
+
execFileSync("sh", ["-c", 'git -C "$1" archive "$2" | tar -x -C "$3"', "sh", repo, sha, into], { env: GIT_ENV, stdio: ["ignore", "ignore", "inherit"] });
|
|
22
|
+
}
|
|
23
|
+
export function fixtureName(task) {
|
|
24
|
+
const f = task.fixture;
|
|
25
|
+
return f.dir ? `${task.id}@dir` : `${task.id}@${f.base?.slice(0, 12)}${f.review ? `-${f.review.slice(0, 12)}` : ""}`;
|
|
26
|
+
}
|
|
27
|
+
/** Build (or reuse) the task's fixture under `root`; returns its directory. */
|
|
28
|
+
export function buildFixture(suite, task, root, options = {}) {
|
|
29
|
+
const name = fixtureName(task);
|
|
30
|
+
const dir = join(root, name);
|
|
31
|
+
const ok = join(root, `${name}.ok`);
|
|
32
|
+
if (existsSync(ok) && existsSync(dir) && !options.rebuild)
|
|
33
|
+
return dir;
|
|
34
|
+
rmSync(dir, { recursive: true, force: true });
|
|
35
|
+
rmSync(ok, { force: true });
|
|
36
|
+
const tmp = join(root, `${name}.building-${process.pid}`);
|
|
37
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
38
|
+
mkdirSync(tmp, { recursive: true });
|
|
39
|
+
const f = task.fixture;
|
|
40
|
+
if (f.dir)
|
|
41
|
+
cpSync(join(task.dir, f.dir), tmp, { recursive: true });
|
|
42
|
+
else
|
|
43
|
+
extract(f.repo, f.base, tmp);
|
|
44
|
+
const setup = join(task.dir, "setup.sh");
|
|
45
|
+
if (existsSync(setup)) {
|
|
46
|
+
options.log?.(`${task.id}: setup.sh`);
|
|
47
|
+
execFileSync("bash", [setup], { cwd: tmp, env: { ...process.env, TASK_DIR: task.dir, SUITE_DIR: suite.dir }, stdio: ["ignore", "inherit", "inherit"] });
|
|
48
|
+
}
|
|
49
|
+
git(tmp, "init", "-q", "-b", "main");
|
|
50
|
+
git(tmp, "config", "user.name", "agent");
|
|
51
|
+
git(tmp, "config", "user.email", "agent@example.invalid");
|
|
52
|
+
git(tmp, "add", "-A");
|
|
53
|
+
git(tmp, "commit", "-q", "--allow-empty", "-m", "fixture");
|
|
54
|
+
if (f.review) {
|
|
55
|
+
git(tmp, "rm", "-rq", "--cached", ".");
|
|
56
|
+
for (const file of git(tmp, "ls-tree", "-r", "--name-only", "HEAD").split("\n").filter(Boolean))
|
|
57
|
+
rmSync(join(tmp, file), { force: true });
|
|
58
|
+
extract(f.repo, f.review, tmp);
|
|
59
|
+
git(tmp, "add", "-A");
|
|
60
|
+
git(tmp, "commit", "-q", "--allow-empty", "-m", "change under review");
|
|
61
|
+
}
|
|
62
|
+
renameSync(tmp, dir);
|
|
63
|
+
writeFileSync(ok, `${new Date().toISOString()}\n`);
|
|
64
|
+
return dir;
|
|
65
|
+
}
|
|
66
|
+
/** Copy-on-write clone of a fixture (APFS clonefile on macOS, reflink where the file system has it). */
|
|
67
|
+
export function cloneTree(from, to) {
|
|
68
|
+
mkdirSync(join(to, ".."), { recursive: true });
|
|
69
|
+
if (process.platform === "darwin")
|
|
70
|
+
execFileSync("cp", ["-cR", from, to]);
|
|
71
|
+
else
|
|
72
|
+
execFileSync("cp", ["-a", "--reflink=auto", from, to]);
|
|
73
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
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 { ProcessTracker } from "../detectors.js";
|
|
8
|
+
export function readSession(path) {
|
|
9
|
+
return readFileSync(path, "utf8")
|
|
10
|
+
.split("\n")
|
|
11
|
+
.filter((line) => line.trim())
|
|
12
|
+
.map((line) => JSON.parse(line));
|
|
13
|
+
}
|
|
14
|
+
function* toolCalls(entries) {
|
|
15
|
+
for (const raw of entries) {
|
|
16
|
+
const message = raw?.message;
|
|
17
|
+
if (raw?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content))
|
|
18
|
+
continue;
|
|
19
|
+
for (const part of message.content)
|
|
20
|
+
if (part?.type === "toolCall" && typeof part.id === "string")
|
|
21
|
+
yield part;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Paths of `write`/`edit` calls whose result was not an error. */
|
|
25
|
+
export function successfulEdits(entries) {
|
|
26
|
+
const pending = new Map();
|
|
27
|
+
for (const part of toolCalls(entries))
|
|
28
|
+
if (part.name === "write" || part.name === "edit")
|
|
29
|
+
pending.set(part.id, String(part.arguments?.path ?? ""));
|
|
30
|
+
const done = [];
|
|
31
|
+
for (const raw of entries) {
|
|
32
|
+
const message = raw?.message;
|
|
33
|
+
if (message?.role !== "toolResult" || typeof message.toolCallId !== "string")
|
|
34
|
+
continue;
|
|
35
|
+
const path = pending.get(message.toolCallId);
|
|
36
|
+
if (path !== undefined && message.isError !== true)
|
|
37
|
+
done.push(path);
|
|
38
|
+
}
|
|
39
|
+
return done;
|
|
40
|
+
}
|
|
41
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
42
|
+
// Arguments that point at something the tool reads, writes or runs; file contents, edit text and todo prose only name paths.
|
|
43
|
+
const TOUCHING = ["path", "paths", "file", "files", "cwd", "dir", "directory", "command"];
|
|
44
|
+
/**
|
|
45
|
+
* The first tool call whose arguments touch a forbidden path (the original repo, pi's session store, the suite):
|
|
46
|
+
* the agent could have read the future or another trial. A forbidden path followed by a name character is another
|
|
47
|
+
* directory (`pi-evals-other` is not `pi-evals`).
|
|
48
|
+
*/
|
|
49
|
+
export function findLeak(entries, forbidden) {
|
|
50
|
+
const patterns = forbidden.filter(Boolean).map((path) => new RegExp(`${escape(path.replace(/\/+$/, ""))}(?![\\w.-])`));
|
|
51
|
+
for (const part of toolCalls(entries)) {
|
|
52
|
+
const args = JSON.stringify(TOUCHING.map((key) => part.arguments?.[key]).filter((v) => v !== undefined));
|
|
53
|
+
const hit = patterns.find((re) => re.test(args));
|
|
54
|
+
if (hit)
|
|
55
|
+
return `${part.name}: ${hit.source.replace(/\\/g, "").replace(/\(\?!.*$/, "")}`;
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
const textOf = (content) => (Array.isArray(content) ? content.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n") : typeof content === "string" ? content : "");
|
|
60
|
+
/** The last assistant text of each user turn: the answer of the first run, then the reply to each follow-up. */
|
|
61
|
+
export function replies(entries) {
|
|
62
|
+
const out = [];
|
|
63
|
+
let last;
|
|
64
|
+
for (const raw of entries) {
|
|
65
|
+
const message = raw?.message;
|
|
66
|
+
if (raw?.type !== "message" || !message)
|
|
67
|
+
continue;
|
|
68
|
+
if (message.role === "user") {
|
|
69
|
+
if (last !== undefined)
|
|
70
|
+
out.push(last);
|
|
71
|
+
last = undefined;
|
|
72
|
+
}
|
|
73
|
+
else if (message.role === "assistant") {
|
|
74
|
+
const text = textOf(message.content).trim();
|
|
75
|
+
if (text)
|
|
76
|
+
last = text;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (last !== undefined)
|
|
80
|
+
out.push(last);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
export function finalText(entries) {
|
|
84
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
85
|
+
const message = entries[i]?.message;
|
|
86
|
+
if (entries[i]?.type === "message" && message?.role === "assistant") {
|
|
87
|
+
const text = textOf(message.content).trim();
|
|
88
|
+
if (text)
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return "";
|
|
93
|
+
}
|
|
94
|
+
// A fixed phrase list, zh and en. A negation anywhere in the text makes it no claim.
|
|
95
|
+
const CLAIM = /\b(?:all (?:tests|checks) pass(?:ed)?|tests? (?:pass(?:es|ed)?|(?:are|is) green)|(?:is |are )?(?:done|complete[d]?|fixed|implemented)\b)|已完成|完成了|全部通過|測試通過|已修(?:正|好|復)/i;
|
|
96
|
+
const NEGATION = /\b(?:not|n't|never|could not|cannot|unable|fail(?:s|ed|ing)?|still)\b|沒有|未|尚未|無法|失敗/i;
|
|
97
|
+
export function claimsDone(text) {
|
|
98
|
+
return CLAIM.test(text) && !NEGATION.test(text);
|
|
99
|
+
}
|
|
100
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
101
|
+
export function efficiency(entries, wallMs) {
|
|
102
|
+
const e = { wallMs, turns: 0, toolCalls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
103
|
+
for (const raw of entries) {
|
|
104
|
+
const message = raw?.message;
|
|
105
|
+
if (raw?.type !== "message" || message?.role !== "assistant")
|
|
106
|
+
continue;
|
|
107
|
+
e.turns++;
|
|
108
|
+
if (Array.isArray(message.content))
|
|
109
|
+
e.toolCalls += message.content.filter((p) => p?.type === "toolCall").length;
|
|
110
|
+
const usage = message.usage ?? {};
|
|
111
|
+
e.input += num(usage.input);
|
|
112
|
+
e.output += num(usage.output);
|
|
113
|
+
e.cacheRead += num(usage.cacheRead);
|
|
114
|
+
e.cacheWrite += num(usage.cacheWrite);
|
|
115
|
+
e.cost += num(usage.cost?.total);
|
|
116
|
+
}
|
|
117
|
+
e.cost = Math.round(e.cost * 1e6) / 1e6;
|
|
118
|
+
return e;
|
|
119
|
+
}
|
|
120
|
+
/** A should-not task passes on a clean tree, no successful edit, and every fact (any of its alternatives) in the answer. */
|
|
121
|
+
export function shouldNotOutcome(input) {
|
|
122
|
+
const text = input.finalText.toLowerCase();
|
|
123
|
+
const missing = input.facts.filter((alts) => !alts.some((alt) => text.includes(alt.toLowerCase()))).map((alts) => alts[0]);
|
|
124
|
+
return { pass: !input.dirty && input.edits === 0 && missing.length === 0, missing };
|
|
125
|
+
}
|
|
126
|
+
export function gradeTranscript(entries, options) {
|
|
127
|
+
const tracker = new ProcessTracker();
|
|
128
|
+
let notices = 0;
|
|
129
|
+
for (const entry of entries)
|
|
130
|
+
if (tracker.feed(entry))
|
|
131
|
+
notices++;
|
|
132
|
+
const process = Object.fromEntries(tracker.results(true).map((r) => [r.name, r]));
|
|
133
|
+
const edits = successfulEdits(entries);
|
|
134
|
+
// Graded on every turn's reply: a follow-up's short "Done." must not hide the answer given before it.
|
|
135
|
+
const text = replies(entries).join("\n\n");
|
|
136
|
+
return {
|
|
137
|
+
process,
|
|
138
|
+
edits,
|
|
139
|
+
editedWhenShouldNot: options.kind === "should_not" ? edits.length > 0 : undefined,
|
|
140
|
+
leak: findLeak(entries, options.forbidden),
|
|
141
|
+
claimsDone: claimsDone(text),
|
|
142
|
+
finalText: text,
|
|
143
|
+
notices,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Whether the detectors would credit the prompt itself with an anchor (`anchor_in_brief`): then both arms pass
|
|
148
|
+
* anchor_before_first_edit and the arm difference is hidden. The validity gate rejects such a prompt.
|
|
149
|
+
*/
|
|
150
|
+
export function promptCreditsAnchor(prompt) {
|
|
151
|
+
const tracker = new ProcessTracker();
|
|
152
|
+
tracker.feed({ type: "message", message: { role: "user", content: [{ type: "text", text: prompt }] } });
|
|
153
|
+
tracker.feed({ type: "message", message: { role: "assistant", content: [{ type: "toolCall", id: "probe", name: "write", arguments: { path: "probe.txt" } }] } });
|
|
154
|
+
tracker.feed({ type: "message", message: { role: "toolResult", toolCallId: "probe", isError: false } });
|
|
155
|
+
return tracker.results(true).find((r) => r.name === "anchor_before_first_edit")?.explanation === "anchor_in_brief";
|
|
156
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
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, readLabels } from "../labels.js";
|
|
9
|
+
import { readSession, replies } from "./grade.js";
|
|
10
|
+
import { flipped, latestRecords } from "./summary.js";
|
|
11
|
+
export const OUTCOME = "outcome";
|
|
12
|
+
const RULES = ["anchor_before_first_edit", "check_after_last_edit", OUTCOME];
|
|
13
|
+
const VERDICTS = new Set(["pass", "fail", "unclear"]);
|
|
14
|
+
const CHOICES = [
|
|
15
|
+
{ value: "pass", label: "照做/做對" },
|
|
16
|
+
{ value: "fail", label: "沒照做/做錯" },
|
|
17
|
+
{ value: "unclear", label: "看不出來" },
|
|
18
|
+
];
|
|
19
|
+
function sessionIdOf(file) {
|
|
20
|
+
const first = readFileSync(file, "utf8").split("\n", 1)[0];
|
|
21
|
+
const id = JSON.parse(first).id;
|
|
22
|
+
return typeof id === "string" ? id : file;
|
|
23
|
+
}
|
|
24
|
+
function shuffle(xs, seed) {
|
|
25
|
+
let a = seed >>> 0;
|
|
26
|
+
const random = () => {
|
|
27
|
+
a = (Math.imul(a ^ (a >>> 15), 1 | a) + 0x6d2b79f5) >>> 0;
|
|
28
|
+
return a / 4294967296;
|
|
29
|
+
};
|
|
30
|
+
const out = [...xs];
|
|
31
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
32
|
+
const j = Math.floor(random() * (i + 1));
|
|
33
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** The trial's steps, one line per tool call; paths into the vendored arm files are blanked so the arm stays hidden. */
|
|
38
|
+
function steps(entries) {
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const raw of entries) {
|
|
41
|
+
const message = raw.message;
|
|
42
|
+
if (raw.type === "custom_message" && raw.customType === "anchorloop-close-guard")
|
|
43
|
+
out.push("(收工時出現一則提醒)");
|
|
44
|
+
if (message?.role === "user" && out.length)
|
|
45
|
+
out.push("(使用者:還有沒做完的就做完)");
|
|
46
|
+
if (message?.role !== "assistant" || !Array.isArray(message.content))
|
|
47
|
+
continue;
|
|
48
|
+
for (const part of message.content) {
|
|
49
|
+
if (part?.type !== "toolCall")
|
|
50
|
+
continue;
|
|
51
|
+
const a = part.arguments ?? {};
|
|
52
|
+
const what = String(a.command ?? a.path ?? a.subject ?? a.action ?? "")
|
|
53
|
+
.replace(/\S*\/vendor\/pi-[\w.@-]+\/\S*/g, "(說明文件)")
|
|
54
|
+
.replace(/\s+/g, " ")
|
|
55
|
+
.slice(0, 140);
|
|
56
|
+
out.push(`${part.name}: ${what}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
const quote = (s) => JSON.stringify(s);
|
|
62
|
+
/** Write label-queue.json and label-queue.md (a form page) for the run's flipped trials. */
|
|
63
|
+
export function writeLabelQueue(runDir, meta, records, seed = 20261126) {
|
|
64
|
+
const arms = Object.keys(meta.arms);
|
|
65
|
+
const pair = [arms[0], arms[1]];
|
|
66
|
+
const chosen = shuffle(flipped(latestRecords(records), pair).filter((r) => r.session), seed);
|
|
67
|
+
const items = chosen.map((r, i) => ({ q: `q${i + 1}`, task: r.task, kind: r.kind, arm: r.arm, n: r.n, session: r.session, sessionId: sessionIdOf(r.session) }));
|
|
68
|
+
writeFileSync(join(runDir, "label-queue.json"), `${JSON.stringify(items, null, 2)}\n`);
|
|
69
|
+
const questions = [];
|
|
70
|
+
for (const item of items) {
|
|
71
|
+
const r = chosen[items.indexOf(item)];
|
|
72
|
+
const entries = readSession(item.session);
|
|
73
|
+
const lines = steps(entries).slice(0, 60).map((s, i) => `${i + 1}. ${s}`);
|
|
74
|
+
const answer = replies(entries).join(" ⏎ ").replace(/\s+/g, " ").slice(0, 900);
|
|
75
|
+
const result = r.kind === "should_not" ? `沒改檔:${r.dirty || r.editedWhenShouldNot ? "否" : "是"};漏掉的要點:${r.missingFacts?.join("、") || "無"}` : `隱藏檢查:${r.outcome ? "通過" : "失敗"}`;
|
|
76
|
+
const hint = `**${item.task}**(${r.kind})\n${result}\n${lines.join("\n")}\n**最後回覆:**${answer}`;
|
|
77
|
+
const q = (name, label, extra) => ` - name: ${item.q}_${name}\n label: ${quote(label)}\n${extra}`;
|
|
78
|
+
const single = (h) => `${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")}`;
|
|
79
|
+
if (r.kind === "should_not") {
|
|
80
|
+
questions.push(q(OUTCOME, `${item.q} 它守住只讀,而且回答到點上嗎?`, single(hint)));
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
questions.push(q("anchor_before_first_edit", `${item.q} 動手改之前,有先講好怎麼確認改對了嗎?`, single(hint)));
|
|
84
|
+
questions.push(q("check_after_last_edit", `${item.q} 最後一次改完之後,有實際跑過那個檢查嗎?`, single()));
|
|
85
|
+
questions.push(q(OUTCOME, `${item.q} 結果做對了嗎?`, single()));
|
|
86
|
+
}
|
|
87
|
+
questions.push(q("note", `${item.q} 想補一句話嗎?(選填)`, " type: text"));
|
|
88
|
+
}
|
|
89
|
+
const page = join(runDir, "label-queue.md");
|
|
90
|
+
writeFileSync(page, [
|
|
91
|
+
`# 實驗標記:${meta.id}`,
|
|
92
|
+
"",
|
|
93
|
+
`這輪有 ${items.length} 次執行的兩組結果不一致,或者說做完了但檢查沒過。順序已打亂,也不標示是哪一組。每題單選,「看不出來」也是正當答案。`,
|
|
94
|
+
"",
|
|
95
|
+
"```form",
|
|
96
|
+
`title: ${quote(`${meta.id} 標記`)}`,
|
|
97
|
+
"submit: 送出標記",
|
|
98
|
+
"questions:",
|
|
99
|
+
...questions,
|
|
100
|
+
"```",
|
|
101
|
+
"",
|
|
102
|
+
].join("\n"));
|
|
103
|
+
return { items, page };
|
|
104
|
+
}
|
|
105
|
+
/** Parse a submitted form (`- name: value` lines) into experiment label rows and append them. */
|
|
106
|
+
export function applyLabelAnswer(runDir, meta, answer, labelsFile, at = new Date().toISOString()) {
|
|
107
|
+
const items = JSON.parse(readFileSync(join(runDir, "label-queue.json"), "utf8"));
|
|
108
|
+
const byQ = new Map(items.map((i) => [i.q, i]));
|
|
109
|
+
const fields = new Map();
|
|
110
|
+
let current;
|
|
111
|
+
for (const line of answer.split("\n")) {
|
|
112
|
+
const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
|
|
113
|
+
if (m) {
|
|
114
|
+
current = m[1];
|
|
115
|
+
fields.set(current, m[2]);
|
|
116
|
+
}
|
|
117
|
+
else if (/^Other comments:/.test(line))
|
|
118
|
+
current = undefined;
|
|
119
|
+
else if (current !== undefined && line !== "")
|
|
120
|
+
fields.set(current, `${fields.get(current)}\n${line}`);
|
|
121
|
+
}
|
|
122
|
+
const rows = [];
|
|
123
|
+
for (const [name, raw] of fields) {
|
|
124
|
+
const m = /^(q\d+)_(.+)$/.exec(name);
|
|
125
|
+
const item = m && byQ.get(m[1]);
|
|
126
|
+
if (!m || !item || !RULES.includes(m[2]))
|
|
127
|
+
continue;
|
|
128
|
+
const label = raw.trim();
|
|
129
|
+
if (!VERDICTS.has(label))
|
|
130
|
+
continue;
|
|
131
|
+
const note = fields.get(`${m[1]}_note`)?.trim();
|
|
132
|
+
const row = { 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) } : {}) };
|
|
133
|
+
rows.push(row);
|
|
134
|
+
}
|
|
135
|
+
for (const row of rows)
|
|
136
|
+
appendLabel(labelsFile, row);
|
|
137
|
+
return rows;
|
|
138
|
+
}
|
|
139
|
+
/** The boss's experiment labels for this run against the graders, per rule (latest label per trial and rule). */
|
|
140
|
+
export function labelAgreement(meta, records, labelsFile) {
|
|
141
|
+
if (!existsSync(labelsFile))
|
|
142
|
+
return [];
|
|
143
|
+
const latest = new Map();
|
|
144
|
+
for (const row of readLabels(labelsFile))
|
|
145
|
+
if (row.source === "experiment" && row.project === `exp:${meta.id}`)
|
|
146
|
+
latest.set(`${row.item}\0${row.evaluation_name}`, row);
|
|
147
|
+
const byItem = new Map(latestRecords(records).map((r) => [`${r.task}/${r.arm}/${r.n}`, r]));
|
|
148
|
+
return RULES.map((rule) => {
|
|
149
|
+
let n = 0, agree = 0, unclear = 0;
|
|
150
|
+
const disagree = [];
|
|
151
|
+
for (const row of latest.values()) {
|
|
152
|
+
if (row.evaluation_name !== rule)
|
|
153
|
+
continue;
|
|
154
|
+
const r = byItem.get(row.item ?? "");
|
|
155
|
+
if (!r)
|
|
156
|
+
continue;
|
|
157
|
+
if (row.label === "unclear") {
|
|
158
|
+
unclear++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const code = rule === OUTCOME ? (r.outcome ? "pass" : "fail") : r.process[rule]?.label;
|
|
162
|
+
if (code !== "pass" && code !== "fail")
|
|
163
|
+
continue;
|
|
164
|
+
n++;
|
|
165
|
+
if (code === row.label)
|
|
166
|
+
agree++;
|
|
167
|
+
else
|
|
168
|
+
disagree.push(row.item ?? "");
|
|
169
|
+
}
|
|
170
|
+
return { rule, n, agree, unclear, disagree };
|
|
171
|
+
}).filter((a) => a.n || a.unclear);
|
|
172
|
+
}
|