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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
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
+
10
+ ## 0.7.0
11
+
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.
13
+ - `/evals run` lists the scripts with what each is for; `/evals run <script> [args]` runs one and shows its output, with script names completed.
14
+ - The analyzing-evals skill names these scripts at the steps that use them: freshness first, disagree and session-shape when a number looks wrong, sample and label-import for hand labels.
15
+
3
16
  ## 0.6.1
4
17
 
5
18
  - An extract stopped part-way after an extractor upgrade no longer passes off old results as current. Each session file's summary now records the extractor version that wrote it, and any other version is read again. Before, the first 0.6.0 extract was killed by a timeout and saved the new version mark while most summaries were still old, so the next run skipped them: check agreement read 11/20 instead of 23/24 until a full rebuild. Every session is read once more (extractor version 6).
package/README.md CHANGED
@@ -51,10 +51,26 @@ The observer loads in every session, subagents included.
51
51
  | `/evals label <rule> pass\|fail\|unclear [note]` | The same in one line; `<rule>` is a check name (`anchor_before_first_edit`, `check_after_last_edit`, `todo_evidence`, `close_guard_quiet`, `plan_names_graph`) or `other`. |
52
52
  | `/evals label <your words>` | Anything else, e.g. `/evals label 剛剛沒先跑測試就說完成`: the agent turns your words into labels with `evals_label` and says in one line what it recorded. The verdict is yours and your words are kept as the note. |
53
53
  | `/evals label undo` | Withdraws the current session's last label given in the moment. |
54
+ | `/evals run` | Lists the shipped analysis scripts, each with what it is for. |
55
+ | `/evals run <script> [args]` | Runs one and shows its output; output over 2,000 bytes goes to a file under `runs/` in the state dir and the reply names it. |
54
56
 
55
57
  A label records the session, the time, and the key of the todo item in progress, if any (its `uid`, else `<session>#<id>`, as work items are keyed).
56
58
  It reaches the report and `evals_query` at their next read, without an extract.
57
59
 
60
+ ### Analysis scripts
61
+
62
+ Shipped in `scripts/`; run them with `/evals run`, or with `node <package>/scripts/<name>.mjs` (agents do, through the analyzing-evals skill). They read the index, checkpoint, labels and change timeline, never a transcript into their output; `session-shape` reads one session file to classify its events and prints no message text.
63
+
64
+ | Script | What it answers |
65
+ | --- | --- |
66
+ | `freshness` | Is the index current: last extract, summaries per extractor version, a run stopped part-way. Exits 1 when versions are mixed. |
67
+ | `disagree <rule> [--range DAYS]` | Each labelled session where the code and your verdict in effect disagree, with the code's reason and where the label came from, and which way they lean. |
68
+ | `by-version <detector> [--pkg PACKAGE]` | Pass rate and n per package version at session start (anchorloop by default; pi-straw-boss for `plan_names_graph`). |
69
+ | `sample <n> [--since ISO] [--seed N]` | A seeded sample of judged sessions you have not labelled, spread over project, kind, model and size, written to `labels/sample-<date>.json` (ids and metadata only). |
70
+ | `label-import <answer-file> [--sample FILE]` | Your submitted label form (`- <n>_<rule>: pass`, `- <n>_type: …`, `- <n>_note: …`) as after-the-fact labels in `labels.jsonl`. |
71
+ | `session-shape <session id>` | The events the detectors see, in order: tools, edit paths, check runs by exit code, todo statuses and evidence, close-guard reminders, the sb role; then each detector's verdict. |
72
+ | `change-impact`, `skill-days`, `package-errors` | A change's numbers before and after; a skill's sessions per day; a package's errors per day. |
73
+
58
74
  ### `/ask-ai`: get an answer before the agent acts
59
75
 
60
76
  | Command | What it does |
@@ -83,6 +99,26 @@ pi-evals query <view> [--since YYYY-MM-DD] [--project <key>]
83
99
  pi-evals mark <note>
84
100
  ```
85
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
+
86
122
  ### The `evals_query` tool
87
123
 
88
124
  Start with `findings` (under 1,500 bytes), then follow one pointer if you need the counts.
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The analysis scripts' logic (scripts/*.mjs are thin wrappers): freshness, disagree, by-version, sample and
3
+ * label-import. Each reads the index, checkpoint, labels or change timeline and returns lines; none prints message
4
+ * text or a label's note.
5
+ */
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { loadRows } from "./build.js";
9
+ import { readChanges, versionAt } from "./changes.js";
10
+ import { DETECTORS, ERA_START } from "./detectors.js";
11
+ import { EXTRACTOR_VERSION, loadCheckpoint } from "./extract/run.js";
12
+ import { appendLabel, cleanNote, FAILURE_TYPES, readLabels, RULES } from "./labels.js";
13
+ import { DETECTOR_META } from "./meta.js";
14
+ import { safeName } from "./schema.js";
15
+ import { ANCHORLOOP } from "./work/join.js";
16
+ export class AnalysisError extends Error {
17
+ }
18
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
19
+ const pct = (num, den) => (den ? `${((100 * num) / den).toFixed(1)}%` : "n/a");
20
+ function checkpointOf(lay) {
21
+ if (!existsSync(lay.checkpoint))
22
+ throw new AnalysisError("No checkpoint. Run /evals extract first.");
23
+ return loadCheckpoint(lay.checkpoint);
24
+ }
25
+ function lastExtractOf(lay, cp) {
26
+ try {
27
+ return JSON.parse(readFileSync(lay.status, "utf8")).lastExtract ?? cp.lastExtract;
28
+ }
29
+ catch {
30
+ return cp.lastExtract;
31
+ }
32
+ }
33
+ /** Last extract, summaries per extractor version, and signs of a run stopped part-way; status 1 when versions are mixed. */
34
+ export function freshness(lay, now = Date.now()) {
35
+ const cp = checkpointOf(lay);
36
+ const last = lastExtractOf(lay, cp);
37
+ const by = new Map();
38
+ for (const f of Object.values(cp.files)) {
39
+ const key = f.extractor === undefined ? "unstamped (0.6.0 or older)" : String(f.extractor);
40
+ by.set(key, (by.get(key) ?? 0) + 1);
41
+ }
42
+ const lines = [`last extract ${last ?? "never"}${last ? ` (${((now - Date.parse(last)) / 3_600_000).toFixed(1)} h ago)` : ""}`, `this pi-evals writes extractor ${EXTRACTOR_VERSION}`];
43
+ for (const [version, n] of [...by].sort())
44
+ lines.push(`extractor ${version}: ${plural(n, "summary", "summaries")}`);
45
+ const saved = statSync(lay.checkpoint).mtimeMs;
46
+ if (last && saved > Date.parse(last) + 120_000)
47
+ lines.push("The checkpoint was saved after the last finished extract: a run stopped part-way.");
48
+ if (existsSync(lay.days) && last) {
49
+ const built = JSON.parse(readFileSync(lay.days, "utf8")).built;
50
+ if (built && built < last)
51
+ lines.push(`The index (built ${built}) is older than the last extract: run /evals extract to rebuild it.`);
52
+ }
53
+ const mixed = [...by.keys()].some((v) => v !== String(EXTRACTOR_VERSION));
54
+ if (mixed)
55
+ lines.push(`STALE: some summaries are from another extractor version. Run /evals extract to finish; do not read the numbers until this passes.`);
56
+ else
57
+ lines.push("Fresh: every summary is from the current extractor.");
58
+ return { lines, status: mixed ? 1 : 0 };
59
+ }
60
+ const sourceOf = (r) => (r.source === "live" ? "live" : r.source === "live-prompt" ? "prompt" : "after");
61
+ /** Code verdicts and explanations by session id, with each session's start. */
62
+ function verdicts(cp, rule) {
63
+ const out = new Map();
64
+ for (const f of Object.values(cp.files)) {
65
+ const r = f.summary.evals[rule];
66
+ if (r)
67
+ out.set(f.summary.sessionId, { label: r.label, why: r.explanation, start: f.summary.start });
68
+ }
69
+ return out;
70
+ }
71
+ /** Per labelled session, the user's verdict in effect against the code's, and which way the disagreements lean. */
72
+ export function disagree(lay, rule, rangeDays) {
73
+ if (!DETECTORS.includes(rule))
74
+ throw new AnalysisError(`Unknown rule. Rules: ${DETECTORS.join(", ")}.`);
75
+ const cp = checkpointOf(lay);
76
+ const code = verdicts(cp, rule);
77
+ const last = Date.parse(lastExtractOf(lay, cp) ?? new Date().toISOString());
78
+ const rows = readLabels(lay.labels).filter((r) => r.annotator !== "agent" && r.evaluation_name === rule && !r.undo);
79
+ let agree = 0, unclear = 0, noCode = 0, under = 0, over = 0;
80
+ const listed = [];
81
+ for (const r of rows) {
82
+ const c = code.get(r.session_id);
83
+ if (rangeDays !== undefined && (!c || Date.parse(c.start) < last - rangeDays * 86_400_000))
84
+ continue;
85
+ if (r.label === "unclear") {
86
+ unclear += 1;
87
+ continue;
88
+ }
89
+ if (!c || c.label === "na") {
90
+ noCode += 1;
91
+ continue;
92
+ }
93
+ if (c.label === r.label) {
94
+ agree += 1;
95
+ continue;
96
+ }
97
+ if (c.label === "fail")
98
+ under += 1;
99
+ else
100
+ over += 1;
101
+ listed.push(`${safeName(r.session_id)} human ${r.label}, code ${c.label} (${safeName(c.why)}), ${sourceOf(r)}`);
102
+ }
103
+ const lean = !listed.length ? "No disagreements." : under === over ? "The disagreements split evenly." : under > over
104
+ ? "Most disagreements are code fail / human pass: the detector undercounts; its rate is too low."
105
+ : "Most disagreements are code pass / human fail: the detector overcounts; its rate is too high.";
106
+ return {
107
+ lines: [
108
+ `${rule}${rangeDays !== undefined ? ` (sessions of the last ${rangeDays} days)` : ""}: ${agree + listed.length} labelled, ${agree} agree, ${listed.length} disagree; unclear ${unclear}; no code verdict ${noCode}`,
109
+ ...listed,
110
+ `code fail / human pass: ${under} (detector undercounts)`,
111
+ `code pass / human fail: ${over} (detector overcounts)`,
112
+ lean,
113
+ ],
114
+ };
115
+ }
116
+ const numeric = (v) => (/^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : undefined);
117
+ function byVersionOrder(a, b) {
118
+ const x = numeric(a), y = numeric(b);
119
+ if (!x || !y)
120
+ return x ? -1 : y ? 1 : a.localeCompare(b);
121
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
122
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
123
+ return (x[i] ?? 0) - (y[i] ?? 0);
124
+ return 0;
125
+ }
126
+ /** A detector's pass rate per version of a package at each session's start. */
127
+ export function byVersion(lay, detector, pkg) {
128
+ if (!DETECTORS.includes(detector))
129
+ throw new AnalysisError(`Unknown detector. Detectors: ${DETECTORS.join(", ")}.`);
130
+ const names = pkg ? [pkg] : DETECTOR_META[detector]?.introducedIn ? [DETECTOR_META[detector].introducedIn.package] : ANCHORLOOP;
131
+ const changes = readChanges(lay.changes);
132
+ const cells = new Map();
133
+ for (const r of loadRows(lay)) {
134
+ const v = r.ev[detector];
135
+ if (v === undefined)
136
+ continue;
137
+ const version = versionAt(changes, names, r.s) ?? "unknown";
138
+ const cell = cells.get(version) ?? { pass: 0, n: 0 };
139
+ cell.pass += v;
140
+ cell.n += 1;
141
+ cells.set(version, cell);
142
+ }
143
+ if (!cells.size)
144
+ return { lines: [`${detector} by ${names[0]} version: no judged sessions in the index.`] };
145
+ return {
146
+ lines: [
147
+ `${detector} by ${names[0]} version at session start (pass / judged):`,
148
+ ...[...cells].sort(([a], [b]) => byVersionOrder(a, b)).map(([v, c]) => `${v}: ${c.pass}/${c.n} ${pct(c.pass, c.n)}`),
149
+ "Versions differ in time as well as code: other changes landed in the same days.",
150
+ ],
151
+ };
152
+ }
153
+ /** Small seeded generator (mulberry32). */
154
+ function random(seed) {
155
+ let a = seed >>> 0;
156
+ return () => {
157
+ a = (a + 0x6d2b79f5) >>> 0;
158
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
159
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
160
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
161
+ };
162
+ }
163
+ const sizeOf = (calls) => (calls < 20 ? "small" : calls < 100 ? "medium" : "large");
164
+ /** A stratified sample of judged sessions the user has not labelled yet, written to `<state>/labels/sample-<date>.json`. */
165
+ export function sample(lay, n, options = {}) {
166
+ if (!Number.isSafeInteger(n) || n < 1 || n > 500)
167
+ throw new AnalysisError("n must be 1 to 500.");
168
+ const since = options.since ?? ERA_START;
169
+ if (!Number.isFinite(Date.parse(since)))
170
+ throw new AnalysisError("--since must be an ISO time.");
171
+ const now = options.now ?? new Date();
172
+ const seed = options.seed ?? Number(now.toISOString().slice(0, 10).replaceAll("-", ""));
173
+ const labelled = new Set(readLabels(lay.labels).filter((r) => r.annotator !== "agent").map((r) => r.session_id));
174
+ const strata = new Map();
175
+ const seen = new Set();
176
+ let judged = 0;
177
+ for (const f of Object.values(checkpointOf(lay).files)) {
178
+ const s = f.summary;
179
+ if (!s.sessionId || seen.has(s.sessionId) || labelled.has(s.sessionId) || s.start < since)
180
+ continue;
181
+ seen.add(s.sessionId);
182
+ if (!Object.values(s.evals).some((r) => r && r.label !== "na"))
183
+ continue;
184
+ judged += 1;
185
+ const row = { session_id: s.sessionId, project: s.project, kind: s.kind, model: safeName(s.model ?? "unknown"), start: s.start, tool_calls: s.toolCalls, size: sizeOf(s.toolCalls) };
186
+ const key = `${row.project}|${row.kind}|${row.model}|${row.size}`;
187
+ strata.set(key, [...(strata.get(key) ?? []), row]);
188
+ }
189
+ const next = random(seed);
190
+ const shuffle = (list) => {
191
+ for (let i = list.length - 1; i > 0; i--) {
192
+ const j = Math.floor(next() * (i + 1));
193
+ [list[i], list[j]] = [list[j], list[i]];
194
+ }
195
+ return list;
196
+ };
197
+ const groups = shuffle([...strata.keys()].sort()).map((k) => shuffle([...strata.get(k)].sort((a, b) => a.session_id.localeCompare(b.session_id))));
198
+ const chosen = [];
199
+ while (chosen.length < n && groups.some((g) => g.length)) {
200
+ for (const g of groups)
201
+ if (g.length && chosen.length < n)
202
+ chosen.push({ n: chosen.length + 1, ...g.pop() });
203
+ }
204
+ const dir = join(lay.state, "labels");
205
+ mkdirSync(dir, { recursive: true });
206
+ const file = join(dir, `sample-${now.toISOString().slice(0, 10)}.json`);
207
+ writeFileSync(file, `${JSON.stringify(chosen, null, 1)}\n`);
208
+ const tally = (key) => [...new Set(chosen.map((c) => c[key]))].map((v) => `${v} ${chosen.filter((c) => c[key] === v).length}`).join(", ");
209
+ return {
210
+ lines: [
211
+ `${chosen.length} of ${judged} judged, unlabelled sessions since ${since} (${strata.size} strata by project, kind, model, size; seed ${seed}; labelled sessions left out)`,
212
+ `kind: ${tally("kind")}`,
213
+ `size: ${tally("size")}`,
214
+ `projects: ${new Set(chosen.map((c) => c.project)).size}`,
215
+ `sample: ${file}`,
216
+ ],
217
+ };
218
+ }
219
+ /** The newest `sample-*.json` under `<state>/labels`. */
220
+ function latestSample(lay) {
221
+ const dir = join(lay.state, "labels");
222
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => /^sample-.*\.json$/.test(f)).sort() : [];
223
+ if (!files.length)
224
+ throw new AnalysisError("No sample under <state>/labels; run the sample script or pass --sample.");
225
+ return join(dir, files.at(-1));
226
+ }
227
+ /**
228
+ * Form answers (`- <n>_<rule>: pass|fail|unclear`, `- <n>_type: <failure type>`, `- <n>_note: ...`) become after-the-fact
229
+ * human rows, appended to labels.jsonl; a later import of the same session and rule replaces the earlier in effect.
230
+ */
231
+ export function labelImport(lay, answerFile, sampleFile, at = new Date().toISOString()) {
232
+ let answer;
233
+ let entries;
234
+ try {
235
+ answer = readFileSync(answerFile, "utf8");
236
+ }
237
+ catch {
238
+ throw new AnalysisError("Cannot read the answer file.");
239
+ }
240
+ try {
241
+ entries = JSON.parse(readFileSync(sampleFile ?? latestSample(lay), "utf8"));
242
+ }
243
+ catch (error) {
244
+ throw error instanceof AnalysisError ? error : new AnalysisError("Cannot read the sample file.");
245
+ }
246
+ const sessionOf = (n) => entries.find((e) => e.n === n)?.session_id ?? (entries.some((e) => e.n !== undefined) ? undefined : entries[n - 1]?.session_id);
247
+ const fields = new Map();
248
+ let current;
249
+ for (const line of answer.split("\n")) {
250
+ const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
251
+ if (m)
252
+ fields.set((current = m[1]), m[2]);
253
+ else if (/^Other comments:/.test(line))
254
+ current = undefined;
255
+ else if (current !== undefined && line !== "")
256
+ fields.set(current, `${fields.get(current)}\n${line}`);
257
+ }
258
+ const rules = RULES.filter((r) => r !== "other");
259
+ const rows = [];
260
+ const problems = [];
261
+ const noted = new Set();
262
+ for (const [name, raw] of fields) {
263
+ const m = /^(\d+)_([a-z_]+)$/.exec(name);
264
+ if (!m || !rules.includes(m[2]))
265
+ continue;
266
+ const n = Number(m[1]);
267
+ const session = sessionOf(n);
268
+ if (!session) {
269
+ problems.push(`${name}: no session #${n} in the sample`);
270
+ continue;
271
+ }
272
+ const label = raw.trim();
273
+ if (!label)
274
+ continue;
275
+ if (label !== "pass" && label !== "fail" && label !== "unclear") {
276
+ problems.push(`${name}: unknown verdict`);
277
+ continue;
278
+ }
279
+ const row = { session_id: session, evaluation_name: m[2], label, at, annotator: "human", source: "batch" };
280
+ const type = fields.get(`${n}_type`)?.trim();
281
+ if (type && label === "fail") {
282
+ if (FAILURE_TYPES.includes(type))
283
+ row.type = type;
284
+ else
285
+ problems.push(`${n}_type: unknown failure type`);
286
+ }
287
+ const note = cleanNote(fields.get(`${n}_note`));
288
+ if (note && !noted.has(n)) {
289
+ row.note = note;
290
+ noted.add(n);
291
+ }
292
+ rows.push(row);
293
+ }
294
+ for (const row of rows)
295
+ appendLabel(lay.labels, row);
296
+ const per = new Map();
297
+ for (const r of rows)
298
+ per.set(r.evaluation_name, (per.get(r.evaluation_name) ?? 0) + 1);
299
+ return {
300
+ lines: [
301
+ `wrote ${plural(rows.length, "label", "labels")} (after the fact, human) to labels.jsonl${per.size ? `: ${[...per].map(([k, v]) => `${k} ${v}`).join(", ")}` : ""}`,
302
+ ...problems.map((p) => `warning: ${p}`),
303
+ "A later import of the same session and rule replaces this one; labels.jsonl keeps both.",
304
+ ],
305
+ status: rows.length ? 0 : 1,
306
+ };
307
+ }
308
+ /** The session file holding a session id, from the checkpoint. */
309
+ export function sessionFile(lay, id) {
310
+ for (const [path, f] of Object.entries(checkpointOf(lay).files))
311
+ if (f.summary.sessionId === id)
312
+ return path;
313
+ throw new AnalysisError("No such session in the index.");
314
+ }
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/detectors.js CHANGED
@@ -42,7 +42,7 @@ function commandsOf(text, bare) {
42
42
  }
43
43
  const LABEL = String.raw `(?:reality anchor|anchor|checks?|gates?|verify|verification|done when|驗證|檢查|驗收)`;
44
44
  const LABELLED = new RegExp(String.raw `^[ \t>*_#-]*${LABEL}[*_]*\s*[::][*_]*\s*(.+)$`, "gim");
45
- function anchorLine(text) {
45
+ export function anchorLine(text) {
46
46
  return [...text.matchAll(LABELLED)].at(-1)?.[1];
47
47
  }
48
48
  /** Tools and scripts whose run checks a change: tests, builds, linters, type checkers, and named check scripts. */
@@ -64,6 +64,8 @@ const DOTNET_SCRIPT = String.raw `\S*dotnet[\w-]*\.py\s+(?:build|test)\b`;
64
64
  const RUN_START = new RegExp(String.raw `^(?:(?:\S*/)?(?:${RUNNER.source})|${INTERPRETER}?(?:${CHECK_SCRIPT}|${DOTNET_SCRIPT}|\S*\btests?/\S+))`, "i");
65
65
  // A mention in prose, as in a brief: a runner or a check script anywhere in a line.
66
66
  const MENTION = new RegExp(String.raw `(?:^|[\s\x60("'>/])(?:${RUNNER.source}|${CHECK_SCRIPT})`, "im");
67
+ /** Whether a brief names a check: a labelled check line, or a runner or check script anywhere in it. */
68
+ export const namesCheck = (text) => anchorLine(text) !== undefined || MENTION.test(text);
67
69
  // Shell lead-ins stripped from each command segment before matching.
68
70
  const LEAD = /^(?:[({!]\s*|(?:time|exec|command|nice|sudo\s+-n|timeout\s+\d+[smh]?|set\s+-\S+(?:\s+\S+)?)\s+|[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+/;
69
71
  /** Whether a shell command runs a check: one of its `&&`, `||`, `;`, `|` or line segments starts with a check runner. */
@@ -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
+ }