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/dist/shape.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * A session's structural trace, the events the detectors read, in file order, for error analysis (`session-shape`).
3
+ * It names tools, edit paths (safe names only), check runs by exit code, todo statuses and evidence results, close-guard
4
+ * notice kinds and the sb role; message text, commands and arguments are read only to classify and never printed.
5
+ */
6
+ import { createReadStream } from "node:fs";
7
+ import { createInterface } from "node:readline";
8
+ import { anchorLine, ERA_START, isCheckRun, namesCheck, noticeKind, ProcessTracker } from "./detectors.js";
9
+ import { graphOfTodo, sbKindOf } from "./plan-graph.js";
10
+ import { safeName } from "./schema.js";
11
+ const obj = (v) => (v && typeof v === "object" ? v : {});
12
+ const str = (v) => (typeof v === "string" ? v : undefined);
13
+ const text = (content) => (typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "");
14
+ function counts(list) {
15
+ const by = new Map();
16
+ for (const k of list)
17
+ by.set(k, (by.get(k) ?? 0) + 1);
18
+ return [...by].map(([k, n]) => `${n} ${k}`).join(", ");
19
+ }
20
+ /** Lines of the trace, then one line per detector result. */
21
+ export async function sessionShape(file) {
22
+ const out = [];
23
+ const tracker = new ProcessTracker();
24
+ const calls = new Map();
25
+ let start = "";
26
+ let seq = 0;
27
+ let firstUser = true;
28
+ let lastTodo = "";
29
+ const at = (ts) => {
30
+ const t = Date.parse(str(ts) ?? "");
31
+ if (!start || !Number.isFinite(t))
32
+ return "";
33
+ const s = Math.max(0, Math.round((t - Date.parse(start)) / 1000));
34
+ return ` +${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
35
+ };
36
+ const push = (entry, what) => out.push(`#${seq}${at(entry.timestamp)} ${what}`);
37
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Number.POSITIVE_INFINITY });
38
+ for await (const line of lines) {
39
+ if (!line || line.charCodeAt(0) !== 123)
40
+ continue;
41
+ let entry;
42
+ try {
43
+ entry = JSON.parse(line);
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ seq += 1;
49
+ tracker.feed(entry);
50
+ const type = entry.type;
51
+ if (type === "session") {
52
+ start = str(entry.timestamp) ?? "";
53
+ continue;
54
+ }
55
+ if (!start && str(entry.timestamp))
56
+ start = str(entry.timestamp);
57
+ if (type === "compaction")
58
+ push(entry, "compaction");
59
+ else if (type === "custom") {
60
+ const data = obj(entry.data);
61
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks)) {
62
+ const tasks = data.tasks.map(obj);
63
+ const ev = tasks.flatMap((t) => (Array.isArray(t.evidence) ? t.evidence.map((e) => `evidence ${obj(e).result === "pass" ? "pass" : "fail"}`) : []));
64
+ const graph = tasks.some((t) => graphOfTodo(t)) ? "; graph named" : "";
65
+ const now = `todo list: ${counts(tasks.map((t) => safeName(t.status)))}${ev.length ? `; ${counts(ev)}` : ""}${graph}`;
66
+ if (now !== lastTodo)
67
+ push(entry, now);
68
+ lastTodo = now;
69
+ }
70
+ else if (entry.customType === "straw-boss" && typeof data.duty === "string")
71
+ push(entry, `sb kind ${safeName(data.duty)} (kind entry)`);
72
+ }
73
+ else if (type === "custom_message") {
74
+ const details = obj(entry.details);
75
+ if (entry.customType === "anchorloop-close-guard")
76
+ push(entry, `close-guard ${noticeKind(entry.content)}`);
77
+ else if (entry.customType === "pi-loop-monitor") {
78
+ const o = obj(details.monitorOutcome);
79
+ if (details.deliveryGroup === "monitor-terminal")
80
+ push(entry, `monitor ${safeName(str(o.monitorId) ?? "?")} ended ${typeof o.exitCode === "number" ? `exit=${o.exitCode}` : safeName(o.status)}`);
81
+ }
82
+ else if (entry.customType === "straw-boss" && details.briefed) {
83
+ const b = obj(details.briefed);
84
+ push(entry, `sb role ${safeName(b.name ?? b.role)} ${b.duty ? safeName(b.duty) : ""}`.trim());
85
+ }
86
+ else if (entry.customType === "subagent_result")
87
+ push(entry, "subagent result");
88
+ }
89
+ else if (type === "message") {
90
+ const message = obj(entry.message);
91
+ if (message.role === "system") {
92
+ const section = obj(message.sections)["straw-boss"];
93
+ if (typeof section === "string")
94
+ push(entry, `sb kind ${sbKindOf(section) ?? "none (not a main)"} (role prompt)`);
95
+ }
96
+ else if (message.role === "user") {
97
+ const words = text(message.content);
98
+ push(entry, firstUser ? `user brief${namesCheck(words) ? " (names a check)" : ""}` : "user");
99
+ firstUser = false;
100
+ }
101
+ else if (message.role === "assistant" && Array.isArray(message.content)) {
102
+ for (const raw of message.content) {
103
+ const part = obj(raw);
104
+ if (part.type === "text" && typeof part.text === "string" && anchorLine(part.text) !== undefined)
105
+ push(entry, "anchor stated");
106
+ if (part.type !== "toolCall" || typeof part.id !== "string")
107
+ continue;
108
+ const args = obj(part.arguments);
109
+ const name = safeName(part.name);
110
+ const command = str(args.command);
111
+ const items = [args, ...(Array.isArray(args.tasks) ? args.tasks.map(obj) : [])];
112
+ const evidence = items.flatMap((i) => (Array.isArray(i.evidence) ? i.evidence.map((e) => (obj(e).result === "pass" ? "pass" : "fail")) : []));
113
+ calls.set(part.id, {
114
+ name,
115
+ path: str(args.path),
116
+ check: command !== undefined && isCheckRun(command),
117
+ evidence: evidence.length ? counts(evidence.map((e) => `evidence ${e}`)) : undefined,
118
+ action: str(args.action) ? safeName(args.action) : undefined,
119
+ role: name === "subagent" ? safeName(str(args.agent) ?? "default") : undefined,
120
+ });
121
+ if (name === "todo" && items.some((i) => (typeof i.anchor === "string" && i.anchor.trim()) || obj(i.metadata).anchor))
122
+ push(entry, "todo anchor set");
123
+ }
124
+ }
125
+ else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
126
+ const call = calls.get(message.toolCallId);
127
+ if (!call)
128
+ continue;
129
+ calls.delete(message.toolCallId);
130
+ const code = obj(message.structuredContent).exit_code;
131
+ const ok = typeof code === "number" ? code === 0 : message.isError !== true;
132
+ const status = typeof code === "number" ? `exit=${code}` : ok ? "ok" : "error";
133
+ if (call.name === "edit" || call.name === "write")
134
+ push(entry, `${call.name} ${call.path ? safeName(call.path) : "?"} ${ok ? "ok" : "error"}`);
135
+ else if (call.name === "bash" || call.name === "MonitorCreate")
136
+ push(entry, `${call.name === "bash" ? "bash" : "monitor start"}${call.check ? " check" : ""} ${status}`);
137
+ else if (call.name === "todo")
138
+ push(entry, `todo ${call.action ?? "?"} ${ok ? "ok" : "error"}${call.evidence ? `; ${call.evidence}` : ""}`);
139
+ else if (call.name === "subagent")
140
+ push(entry, `subagent ${call.role} ${ok ? "launched" : "error"}`);
141
+ else
142
+ push(entry, `${call.name} ${ok ? "ok" : "error"}`);
143
+ }
144
+ }
145
+ }
146
+ for (const r of tracker.results(start >= ERA_START))
147
+ out.push(`${r.name}: ${r.label} (${r.explanation})`);
148
+ return out;
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-evals",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
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",
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // A detector's pass rate per package version at session start.
4
+ const usage = 'node by-version.mjs DETECTOR [--pkg PACKAGE]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--pkg']);
7
+ if (f.rest.length !== 1) throw new QueryError(usage);
8
+ return analysis.byVersion(layout(), f.rest[0], f.pkg);
9
+ });
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // Where the code and the user's labels disagree on one rule, session by session.
4
+ const usage = 'node disagree.mjs RULE [--range DAYS]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--range']);
7
+ if (f.rest.length !== 1 || (f.range !== undefined && !/^\d+$/.test(f.range))) throw new QueryError(usage);
8
+ return analysis.disagree(layout(), f.rest[0], f.range === undefined ? undefined : Number(f.range));
9
+ });
@@ -0,0 +1,7 @@
1
+ import { analysis, layout, run } from './query-lib.mjs';
2
+
3
+ // Is the index current? Exit 1 when summaries come from more than one extractor version.
4
+ const usage = 'node freshness.mjs';
5
+ const check = args => { if (args.length) throw new Error(usage); return analysis.freshness(layout()); };
6
+ check.noArgs = true;
7
+ run(usage, check);
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // Submitted label-form answers into labels.jsonl, as after-the-fact human labels.
4
+ const usage = 'node label-import.mjs ANSWER_FILE [--sample SAMPLE_FILE]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--sample']);
7
+ if (f.rest.length !== 1) throw new QueryError(usage);
8
+ return analysis.labelImport(layout(), f.rest[0], f.sample);
9
+ });
@@ -1,27 +1,57 @@
1
- import { readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
3
  // Node strips types in checkouts but forbids it under node_modules. npm ships dist there.
4
4
  const installed = new URL(import.meta.url).pathname.split('/').includes('node_modules');
5
5
  const load = name => import(installed ? `../dist/${name}.js` : `../src/${name}.ts`);
6
- const [{ layout }, { loadIndex }, { recentDays, packageCounts }, { safeName }] = await Promise.all(
7
- ['paths', 'build', 'trends', 'schema'].map(load),
6
+ const [{ layout }, { loadIndex }, { recentDays, packageCounts }, { safeName }, analysis, shape] = await Promise.all(
7
+ ['paths', 'build', 'trends', 'schema', 'analysis', 'shape'].map(load),
8
8
  );
9
- export { packageCounts, safeName };
9
+ export { analysis, packageCounts, safeName, shape, layout };
10
10
 
11
- export function run(usage, fn) {
11
+ /** Bytes a script prints before it writes the whole output to a file under `<state>/runs` and prints the start and the path. */
12
+ const max = () => Number(process.env.PI_EVALS_SCRIPT_MAX) > 0 ? Number(process.env.PI_EVALS_SCRIPT_MAX) : 2000;
13
+
14
+ function emit(lines) {
15
+ const text = lines.join('\n') + '\n';
16
+ if (Buffer.byteLength(text) <= max()) return process.stdout.write(text);
17
+ const dir = join(layout().state, 'runs');
18
+ mkdirSync(dir, { recursive: true });
19
+ const file = join(dir, `${basename(process.argv[1], '.mjs')}-${new Date().toISOString().replace(/[:.]/g, '-')}.txt`);
20
+ writeFileSync(file, text);
21
+ const tail = `… ${lines.length} lines; full output: ${file}\n`;
22
+ let head = '';
23
+ for (const line of lines) {
24
+ if (Buffer.byteLength(head + line + '\n' + tail) > max()) break;
25
+ head += line + '\n';
26
+ }
27
+ process.stdout.write(head + tail);
28
+ }
29
+
30
+ /** `fn(args)` returns lines, or `{ lines, status }`; it may be async. */
31
+ export async function run(usage, fn) {
12
32
  try {
13
33
  const args = process.argv.slice(2);
14
- if (!args.length || args.some(x => !x || safeName(x) !== x)) throw new Error(usage);
15
- const text = fn(args).join('\n') + '\n';
16
- if (Buffer.byteLength(text) > 2000) throw new Error('Result exceeds the output limit.');
17
- process.stdout.write(text);
34
+ if (!args.length && fn.length && !fn.noArgs || args.some(x => !x || safeName(x) !== x)) throw new QueryError(usage);
35
+ const out = await fn(args);
36
+ const { lines, status } = Array.isArray(out) ? { lines: out, status: 0 } : out;
37
+ emit(lines);
38
+ process.exitCode = status ?? 0;
18
39
  } catch (error) {
19
40
  // Never echo unknown arguments, local paths or JSON parse excerpts.
20
- console.error(error instanceof QueryError ? error.message : `Cannot read query. ${usage}`);
41
+ console.error(error instanceof QueryError || error instanceof analysis.AnalysisError ? error.message : `Cannot read query. ${usage}`);
21
42
  process.exitCode = 1;
22
43
  }
23
44
  }
24
45
  export class QueryError extends Error {}
46
+ /** `--name value` from args; the rest positional. */
47
+ export function flags(args, names) {
48
+ const out = { rest: [] };
49
+ for (let i = 0; i < args.length; i++) {
50
+ if (names.includes(args[i])) out[args[i].slice(2)] = args[++i];
51
+ else out.rest.push(args[i]);
52
+ }
53
+ return out;
54
+ }
25
55
  export function daily(project) {
26
56
  const index = loadIndex(layout());
27
57
  if (!index) throw new QueryError('No index. Run /evals extract first.');
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // A stratified sample of sessions to label by hand: ids and metadata only.
4
+ const usage = 'node sample.mjs N [--since ISO] [--seed INT]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--since', '--seed']);
7
+ if (f.rest.length !== 1 || !/^\d+$/.test(f.rest[0]) || (f.seed !== undefined && !/^\d+$/.test(f.seed))) throw new QueryError(usage);
8
+ return analysis.sample(layout(), Number(f.rest[0]), { since: f.since, seed: f.seed === undefined ? undefined : Number(f.seed) });
9
+ });
@@ -0,0 +1,8 @@
1
+ import { analysis, layout, QueryError, run, shape } from './query-lib.mjs';
2
+
3
+ // The ordered events the detectors see in one session, without message text.
4
+ const usage = 'node session-shape.mjs SESSION_ID';
5
+ run(usage, async args => {
6
+ if (args.length !== 1) throw new QueryError(usage);
7
+ return shape.sessionShape(analysis.sessionFile(layout(), args[0]));
8
+ });
@@ -5,7 +5,7 @@ description: Use when the user asks how their agents, skills or packages are doi
5
5
 
6
6
  # Analyze agent activity
7
7
 
8
- 1. Call `evals_query` with `view: "findings"` first. Check the dates and last extraction; default is the latest 30 UTC dates in the index. Use `since` or `project` when the question specifies a narrower scope.
8
+ 1. Run `node "$SCRIPTS/freshness.mjs"` (step 3 says how to find `SCRIPTS`); if it exits 1, say the numbers are stale and stop. Then call `evals_query` with `view: "findings"`. Check the dates and last extraction; default is the latest 30 UTC dates in the index. Use `since` or `project` when the question specifies a narrower scope.
9
9
  2. Follow **one** pointer that answers the question. For a weekly change in tool errors use `packages`; for a rule about editing use `process`; for what a piece of work cost, where it closed, where it stalled, or whether one way of working is cheaper, use `items`; for how far the code checks match the user's labels, or what the user corrected, use `labels`. Keep the same filters. Stop when the numbers answer the question.
10
10
  3. If one detail is still missing, run one script below. Set `SCRIPTS` to the absolute path on the `Scripts:` line or in `details.scriptsDir`. For a default npm install, the fallback is `SCRIPTS="$HOME/.pi/agent/npm/node_modules/pi-evals/scripts"`. Check `test -f "$SCRIPTS/query-lib.mjs"` before running a query; if it fails, stop rather than guessing another path. Use exact identifiers returned by the view; none of these commands reads a transcript.
11
11
 
@@ -13,6 +13,7 @@ description: Use when the user asks how their agents, skills or packages are doi
13
13
  node "$SCRIPTS/change-impact.mjs" UTC_TIMESTAMP_OR_SHA [PACKAGE_OR_KIND]
14
14
  node "$SCRIPTS/skill-days.mjs" SKILL [PROJECT]
15
15
  node "$SCRIPTS/package-errors.mjs" PACKAGE [PROJECT]
16
+ node "$SCRIPTS/by-version.mjs" DETECTOR [--pkg PACKAGE]
16
17
  ```
17
18
 
18
19
  The first reads the saved `reports/model.json`: check its extract time and project before using the comparison. For a different saved page, prefix the command with `PI_EVALS_REPORT_RANGE=14`, `90`, `all` or `custom`. If the file is missing or out of date, say so; `/evals report` rebuilds the preset pages.
@@ -26,8 +27,10 @@ Lead with what rose, fell or held steady, and give the counts behind the rates.
26
27
 
27
28
  ## When a number looks wrong
28
29
 
29
- 1. Check freshness first: the last extract time, and the `extractor` stamp on the summaries in `index/checkpoint.json` against the current version. A run stopped mid-way once left old summaries under a new checkpoint (check agreement read 11/20; a clean rebuild gave 23/24). If they disagree, say the number is stale and do not interpret it.
30
- 2. Before trusting a detector's rate, check it against the user's labels: the `labels` view, then the disagreeing sessions one by one, and which way they lean. All code=fail with human=pass means the detector undercounts (an anchor rate read 20% that was about 73%).
31
- 3. Error analysis: read the disagreeing sessions' structure (entry types, tool names, order; no transcript text into records), group the misses by cause, count each group, and fix the biggest first.
30
+ 1. Check freshness first (`freshness.mjs`): the last extract time, and the extractor version on the summaries against the current one. A run stopped mid-way once left old summaries under a new checkpoint (check agreement read 11/20; a clean rebuild gave 23/24). If they disagree, say the number is stale and do not interpret it.
31
+ 2. Before trusting a detector's rate, check it against the user's labels: the `labels` view, then `disagree.mjs RULE` for the disagreeing sessions one by one and which way they lean. All code=fail with human=pass means the detector undercounts (an anchor rate read 20% that was about 73%).
32
+ 3. Error analysis: read each disagreeing session's structure with `session-shape.mjs SESSION_ID` (events in order, no message text), group the misses by cause, count each group, and fix the biggest first.
32
33
  4. When loosening a detector, keep a guard set of real should-fail sessions that must stay fail. A rule ambiguity (an anchor stated after the first edit) is the user's decision: ask, record it as a `recheck` label, and do not settle it silently in code.
33
- 5. Have the user label about 30 sessions by hand before trusting any automated grader; human labels are the reference. Observational numbers are monitoring; whether skill X helped needs a controlled experiment, not this report.
34
+ 5. Have the user label about 30 sessions by hand before trusting any automated grader (`sample.mjs 30` picks them, `label-import.mjs ANSWER_FILE` records the answers); human labels are the reference. Observational numbers are monitoring; whether skill X helped needs a controlled experiment, not this report.
35
+
36
+ The user runs any of these as `/evals run <script> [args]`; `/evals run` alone lists them.
@@ -0,0 +1,275 @@
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.ts";
9
+ import { readChanges, versionAt } from "./changes.ts";
10
+ import { DETECTORS, ERA_START } from "./detectors.ts";
11
+ import { type Checkpoint, EXTRACTOR_VERSION, loadCheckpoint } from "./extract/run.ts";
12
+ import { appendLabel, cleanNote, FAILURE_TYPES, type FailureType, type LabelRow, readLabels, RULES } from "./labels.ts";
13
+ import { DETECTOR_META } from "./meta.ts";
14
+ import type { Layout } from "./paths.ts";
15
+ import { safeName } from "./schema.ts";
16
+ import { ANCHORLOOP } from "./work/join.ts";
17
+
18
+ export class AnalysisError extends Error {}
19
+ export interface Result { lines: string[]; status?: number }
20
+
21
+ const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
22
+ const pct = (num: number, den: number) => (den ? `${((100 * num) / den).toFixed(1)}%` : "n/a");
23
+
24
+ function checkpointOf(lay: Layout): Checkpoint {
25
+ if (!existsSync(lay.checkpoint)) throw new AnalysisError("No checkpoint. Run /evals extract first.");
26
+ return loadCheckpoint(lay.checkpoint);
27
+ }
28
+
29
+ function lastExtractOf(lay: Layout, cp: Checkpoint): string | undefined {
30
+ try {
31
+ return (JSON.parse(readFileSync(lay.status, "utf8")) as { lastExtract?: string }).lastExtract ?? cp.lastExtract;
32
+ } catch {
33
+ return cp.lastExtract;
34
+ }
35
+ }
36
+
37
+ /** Last extract, summaries per extractor version, and signs of a run stopped part-way; status 1 when versions are mixed. */
38
+ export function freshness(lay: Layout, now = Date.now()): Result {
39
+ const cp = checkpointOf(lay);
40
+ const last = lastExtractOf(lay, cp);
41
+ const by = new Map<string, number>();
42
+ for (const f of Object.values(cp.files)) {
43
+ const key = f.extractor === undefined ? "unstamped (0.6.0 or older)" : String(f.extractor);
44
+ by.set(key, (by.get(key) ?? 0) + 1);
45
+ }
46
+ 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}`];
47
+ for (const [version, n] of [...by].sort()) lines.push(`extractor ${version}: ${plural(n, "summary", "summaries")}`);
48
+ const saved = statSync(lay.checkpoint).mtimeMs;
49
+ if (last && saved > Date.parse(last) + 120_000) lines.push("The checkpoint was saved after the last finished extract: a run stopped part-way.");
50
+ if (existsSync(lay.days) && last) {
51
+ const built = (JSON.parse(readFileSync(lay.days, "utf8")) as { built?: string }).built;
52
+ if (built && built < last) lines.push(`The index (built ${built}) is older than the last extract: run /evals extract to rebuild it.`);
53
+ }
54
+ const mixed = [...by.keys()].some((v) => v !== String(EXTRACTOR_VERSION));
55
+ if (mixed) 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 lines.push("Fresh: every summary is from the current extractor.");
57
+ return { lines, status: mixed ? 1 : 0 };
58
+ }
59
+
60
+ const sourceOf = (r: LabelRow) => (r.source === "live" ? "live" : r.source === "live-prompt" ? "prompt" : "after");
61
+
62
+ /** Code verdicts and explanations by session id, with each session's start. */
63
+ function verdicts(cp: Checkpoint, rule: string): Map<string, { label: string; why: string; start: string }> {
64
+ const out = new Map<string, { label: string; why: string; start: string }>();
65
+ for (const f of Object.values(cp.files)) {
66
+ const r = f.summary.evals[rule as keyof typeof f.summary.evals];
67
+ if (r) out.set(f.summary.sessionId, { label: r.label, why: r.explanation, start: f.summary.start });
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** Per labelled session, the user's verdict in effect against the code's, and which way the disagreements lean. */
73
+ export function disagree(lay: Layout, rule: string, rangeDays?: number): Result {
74
+ if (!(DETECTORS as readonly string[]).includes(rule)) 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: string[] = [];
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)) continue;
84
+ if (r.label === "unclear") { unclear += 1; continue; }
85
+ if (!c || c.label === "na") { noCode += 1; continue; }
86
+ if (c.label === r.label) { agree += 1; continue; }
87
+ if (c.label === "fail") under += 1;
88
+ else over += 1;
89
+ listed.push(`${safeName(r.session_id)} human ${r.label}, code ${c.label} (${safeName(c.why)}), ${sourceOf(r)}`);
90
+ }
91
+ const lean = !listed.length ? "No disagreements." : under === over ? "The disagreements split evenly." : under > over
92
+ ? "Most disagreements are code fail / human pass: the detector undercounts; its rate is too low."
93
+ : "Most disagreements are code pass / human fail: the detector overcounts; its rate is too high.";
94
+ return {
95
+ lines: [
96
+ `${rule}${rangeDays !== undefined ? ` (sessions of the last ${rangeDays} days)` : ""}: ${agree + listed.length} labelled, ${agree} agree, ${listed.length} disagree; unclear ${unclear}; no code verdict ${noCode}`,
97
+ ...listed,
98
+ `code fail / human pass: ${under} (detector undercounts)`,
99
+ `code pass / human fail: ${over} (detector overcounts)`,
100
+ lean,
101
+ ],
102
+ };
103
+ }
104
+
105
+ const numeric = (v: string) => (/^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : undefined);
106
+ function byVersionOrder(a: string, b: string): number {
107
+ const x = numeric(a), y = numeric(b);
108
+ if (!x || !y) return x ? -1 : y ? 1 : a.localeCompare(b);
109
+ for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
110
+ return 0;
111
+ }
112
+
113
+ /** A detector's pass rate per version of a package at each session's start. */
114
+ export function byVersion(lay: Layout, detector: string, pkg?: string): Result {
115
+ if (!(DETECTORS as readonly string[]).includes(detector)) throw new AnalysisError(`Unknown detector. Detectors: ${DETECTORS.join(", ")}.`);
116
+ const names = pkg ? [pkg] : DETECTOR_META[detector]?.introducedIn ? [DETECTOR_META[detector].introducedIn!.package] : ANCHORLOOP;
117
+ const changes = readChanges(lay.changes);
118
+ const cells = new Map<string, { pass: number; n: number }>();
119
+ for (const r of loadRows(lay)) {
120
+ const v = r.ev[detector];
121
+ if (v === undefined) continue;
122
+ const version = versionAt(changes, names, r.s) ?? "unknown";
123
+ const cell = cells.get(version) ?? { pass: 0, n: 0 };
124
+ cell.pass += v;
125
+ cell.n += 1;
126
+ cells.set(version, cell);
127
+ }
128
+ if (!cells.size) return { lines: [`${detector} by ${names[0]} version: no judged sessions in the index.`] };
129
+ return {
130
+ lines: [
131
+ `${detector} by ${names[0]} version at session start (pass / judged):`,
132
+ ...[...cells].sort(([a], [b]) => byVersionOrder(a, b)).map(([v, c]) => `${v}: ${c.pass}/${c.n} ${pct(c.pass, c.n)}`),
133
+ "Versions differ in time as well as code: other changes landed in the same days.",
134
+ ],
135
+ };
136
+ }
137
+
138
+ /** Small seeded generator (mulberry32). */
139
+ function random(seed: number): () => number {
140
+ let a = seed >>> 0;
141
+ return () => {
142
+ a = (a + 0x6d2b79f5) >>> 0;
143
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
144
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
145
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
146
+ };
147
+ }
148
+ const sizeOf = (calls: number) => (calls < 20 ? "small" : calls < 100 ? "medium" : "large");
149
+
150
+ /** A stratified sample of judged sessions the user has not labelled yet, written to `<state>/labels/sample-<date>.json`. */
151
+ export function sample(lay: Layout, n: number, options: { since?: string; seed?: number; now?: Date } = {}): Result {
152
+ if (!Number.isSafeInteger(n) || n < 1 || n > 500) throw new AnalysisError("n must be 1 to 500.");
153
+ const since = options.since ?? ERA_START;
154
+ if (!Number.isFinite(Date.parse(since))) throw new AnalysisError("--since must be an ISO time.");
155
+ const now = options.now ?? new Date();
156
+ const seed = options.seed ?? Number(now.toISOString().slice(0, 10).replaceAll("-", ""));
157
+ const labelled = new Set(readLabels(lay.labels).filter((r) => r.annotator !== "agent").map((r) => r.session_id));
158
+ type Row = { session_id: string; project: string; kind: string; model: string; start: string; tool_calls: number; size: string };
159
+ const strata = new Map<string, Row[]>();
160
+ const seen = new Set<string>();
161
+ let judged = 0;
162
+ for (const f of Object.values(checkpointOf(lay).files)) {
163
+ const s = f.summary;
164
+ if (!s.sessionId || seen.has(s.sessionId) || labelled.has(s.sessionId) || s.start < since) continue;
165
+ seen.add(s.sessionId);
166
+ if (!Object.values(s.evals).some((r) => r && r.label !== "na")) continue;
167
+ judged += 1;
168
+ 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) };
169
+ const key = `${row.project}|${row.kind}|${row.model}|${row.size}`;
170
+ strata.set(key, [...(strata.get(key) ?? []), row]);
171
+ }
172
+ const next = random(seed);
173
+ const shuffle = <T>(list: T[]) => {
174
+ for (let i = list.length - 1; i > 0; i--) {
175
+ const j = Math.floor(next() * (i + 1));
176
+ [list[i], list[j]] = [list[j], list[i]];
177
+ }
178
+ return list;
179
+ };
180
+ const groups = shuffle([...strata.keys()].sort()).map((k) => shuffle([...strata.get(k)!].sort((a, b) => a.session_id.localeCompare(b.session_id))));
181
+ const chosen: (Row & { n: number })[] = [];
182
+ while (chosen.length < n && groups.some((g) => g.length)) {
183
+ for (const g of groups) if (g.length && chosen.length < n) chosen.push({ n: chosen.length + 1, ...g.pop()! });
184
+ }
185
+ const dir = join(lay.state, "labels");
186
+ mkdirSync(dir, { recursive: true });
187
+ const file = join(dir, `sample-${now.toISOString().slice(0, 10)}.json`);
188
+ writeFileSync(file, `${JSON.stringify(chosen, null, 1)}\n`);
189
+ const tally = (key: "kind" | "size" | "project") => [...new Set(chosen.map((c) => c[key]))].map((v) => `${v} ${chosen.filter((c) => c[key] === v).length}`).join(", ");
190
+ return {
191
+ lines: [
192
+ `${chosen.length} of ${judged} judged, unlabelled sessions since ${since} (${strata.size} strata by project, kind, model, size; seed ${seed}; labelled sessions left out)`,
193
+ `kind: ${tally("kind")}`,
194
+ `size: ${tally("size")}`,
195
+ `projects: ${new Set(chosen.map((c) => c.project)).size}`,
196
+ `sample: ${file}`,
197
+ ],
198
+ };
199
+ }
200
+
201
+ /** The newest `sample-*.json` under `<state>/labels`. */
202
+ function latestSample(lay: Layout): string {
203
+ const dir = join(lay.state, "labels");
204
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => /^sample-.*\.json$/.test(f)).sort() : [];
205
+ if (!files.length) throw new AnalysisError("No sample under <state>/labels; run the sample script or pass --sample.");
206
+ return join(dir, files.at(-1)!);
207
+ }
208
+
209
+ /**
210
+ * Form answers (`- <n>_<rule>: pass|fail|unclear`, `- <n>_type: <failure type>`, `- <n>_note: ...`) become after-the-fact
211
+ * human rows, appended to labels.jsonl; a later import of the same session and rule replaces the earlier in effect.
212
+ */
213
+ export function labelImport(lay: Layout, answerFile: string, sampleFile?: string, at = new Date().toISOString()): Result {
214
+ let answer: string;
215
+ let entries: { n?: number; session_id?: string }[];
216
+ try {
217
+ answer = readFileSync(answerFile, "utf8");
218
+ } catch {
219
+ throw new AnalysisError("Cannot read the answer file.");
220
+ }
221
+ try {
222
+ entries = JSON.parse(readFileSync(sampleFile ?? latestSample(lay), "utf8"));
223
+ } catch (error) {
224
+ throw error instanceof AnalysisError ? error : new AnalysisError("Cannot read the sample file.");
225
+ }
226
+ const sessionOf = (n: number) => entries.find((e) => e.n === n)?.session_id ?? (entries.some((e) => e.n !== undefined) ? undefined : entries[n - 1]?.session_id);
227
+ const fields = new Map<string, string>();
228
+ let current: string | undefined;
229
+ for (const line of answer.split("\n")) {
230
+ const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
231
+ if (m) fields.set((current = m[1]), m[2]);
232
+ else if (/^Other comments:/.test(line)) current = undefined;
233
+ else if (current !== undefined && line !== "") fields.set(current, `${fields.get(current)}\n${line}`);
234
+ }
235
+ const rules = RULES.filter((r) => r !== "other") as string[];
236
+ const rows: LabelRow[] = [];
237
+ const problems: string[] = [];
238
+ const noted = new Set<number>();
239
+ for (const [name, raw] of fields) {
240
+ const m = /^(\d+)_([a-z_]+)$/.exec(name);
241
+ if (!m || !rules.includes(m[2])) continue;
242
+ const n = Number(m[1]);
243
+ const session = sessionOf(n);
244
+ if (!session) { problems.push(`${name}: no session #${n} in the sample`); continue; }
245
+ const label = raw.trim();
246
+ if (!label) continue;
247
+ if (label !== "pass" && label !== "fail" && label !== "unclear") { problems.push(`${name}: unknown verdict`); continue; }
248
+ const row: LabelRow = { session_id: session, evaluation_name: m[2], label, at, annotator: "human", source: "batch" };
249
+ const type = fields.get(`${n}_type`)?.trim();
250
+ if (type && label === "fail") {
251
+ if ((FAILURE_TYPES as readonly string[]).includes(type)) row.type = type as FailureType;
252
+ else problems.push(`${n}_type: unknown failure type`);
253
+ }
254
+ const note = cleanNote(fields.get(`${n}_note`));
255
+ if (note && !noted.has(n)) { row.note = note; noted.add(n); }
256
+ rows.push(row);
257
+ }
258
+ for (const row of rows) appendLabel(lay.labels, row);
259
+ const per = new Map<string, number>();
260
+ for (const r of rows) per.set(r.evaluation_name, (per.get(r.evaluation_name) ?? 0) + 1);
261
+ return {
262
+ lines: [
263
+ `wrote ${plural(rows.length, "label", "labels")} (after the fact, human) to labels.jsonl${per.size ? `: ${[...per].map(([k, v]) => `${k} ${v}`).join(", ")}` : ""}`,
264
+ ...problems.map((p) => `warning: ${p}`),
265
+ "A later import of the same session and rule replaces this one; labels.jsonl keeps both.",
266
+ ],
267
+ status: rows.length ? 0 : 1,
268
+ };
269
+ }
270
+
271
+ /** The session file holding a session id, from the checkpoint. */
272
+ export function sessionFile(lay: Layout, id: string): string {
273
+ for (const [path, f] of Object.entries(checkpointOf(lay).files)) if (f.summary.sessionId === id) return path;
274
+ throw new AnalysisError("No such session in the index.");
275
+ }
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/detectors.ts CHANGED
@@ -56,7 +56,7 @@ function commandsOf(text: string, bare: boolean): string[] {
56
56
  const LABEL = String.raw`(?:reality anchor|anchor|checks?|gates?|verify|verification|done when|驗證|檢查|驗收)`;
57
57
  const LABELLED = new RegExp(String.raw`^[ \t>*_#-]*${LABEL}[*_]*\s*[::][*_]*\s*(.+)$`, "gim");
58
58
 
59
- function anchorLine(text: string): string | undefined {
59
+ export function anchorLine(text: string): string | undefined {
60
60
  return [...text.matchAll(LABELLED)].at(-1)?.[1];
61
61
  }
62
62
 
@@ -82,6 +82,8 @@ const DOTNET_SCRIPT = String.raw`\S*dotnet[\w-]*\.py\s+(?:build|test)\b`;
82
82
  const RUN_START = new RegExp(String.raw`^(?:(?:\S*/)?(?:${RUNNER.source})|${INTERPRETER}?(?:${CHECK_SCRIPT}|${DOTNET_SCRIPT}|\S*\btests?/\S+))`, "i");
83
83
  // A mention in prose, as in a brief: a runner or a check script anywhere in a line.
84
84
  const MENTION = new RegExp(String.raw`(?:^|[\s\x60("'>/])(?:${RUNNER.source}|${CHECK_SCRIPT})`, "im");
85
+ /** Whether a brief names a check: a labelled check line, or a runner or check script anywhere in it. */
86
+ export const namesCheck = (text: string) => anchorLine(text) !== undefined || MENTION.test(text);
85
87
  // Shell lead-ins stripped from each command segment before matching.
86
88
  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+)+/;
87
89