pi-evals 0.6.1 → 0.7.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.
@@ -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/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
 
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), `/ask-ai`, and the `evals_query` and `evals_label` tools.
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label, run), `/ask-ai`, and the `evals_query` and `evals_label` tools.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
@@ -25,7 +25,32 @@ export function cliPath(): { cmd: string; args: string[] } | undefined {
25
25
  return found ? { cmd: process.execPath, args: [found] } : undefined;
26
26
  }
27
27
 
28
- const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label"];
28
+ const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label", "run"];
29
+
30
+ /** The shipped analysis scripts (`scripts/<name>.mjs`) `/evals run` offers, with what each is for. */
31
+ export const SCRIPTS: Record<string, string> = {
32
+ freshness: "索引是不是最新的:最後擷取時間、各擷取器版本的摘要數;版本混雜時數字不能看",
33
+ disagree: "某條規則上程式判定和你的標記哪裡不一致,逐段列出,看偏哪一邊(用法:disagree <規則> [--range 天數])",
34
+ "by-version": "某項檢查在各套件版本下的通過率(用法:by-version <檢查> [--pkg 套件])",
35
+ sample: "分層抽樣還沒標過的工作段,給你手動標記(只有 id 與屬性)(用法:sample <數量> [--since 時間] [--seed 數字])",
36
+ "label-import": "把填好的標記表單答案寫進 labels.jsonl(用法:label-import <答案檔> [--sample 樣本檔])",
37
+ "session-shape": "一段工作的結構軌跡:檢查看到的事件順序,不含訊息內容(用法:session-shape <session id>)",
38
+ "change-impact": "某次調整前後的數字(用法:change-impact <時間或 sha> [套件或種類])",
39
+ "skill-days": "某個 skill 每天被載入的工作段數(用法:skill-days <skill> [專案])",
40
+ "package-errors": "某個套件每天的工具出錯數(用法:package-errors <套件> [專案])",
41
+ };
42
+
43
+ /** Runs one shipped script with the session's environment; resolves with its exit code and output. */
44
+ function runScript(name: string, args: string[], env: Env): Promise<{ code: number | null; out: string }> {
45
+ return new Promise((resolve) => {
46
+ const child = spawn(process.execPath, [fileURLToPath(new URL(`../scripts/${name}.mjs`, import.meta.url)), ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
47
+ let out = "";
48
+ child.stdout?.on("data", (c: Buffer) => void (out += c.toString()));
49
+ child.stderr?.on("data", (c: Buffer) => void (out += c.toString()));
50
+ child.on("error", (error) => resolve({ code: -1, out: error.message }));
51
+ child.on("close", (code) => resolve({ code, out: out.trim() }));
52
+ });
53
+ }
29
54
 
30
55
  function parseFlags(args: string[]) {
31
56
  const out: { since?: string; days?: number; project?: string; rest: string[] } = { rest: [] };
@@ -100,8 +125,12 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
100
125
  };
101
126
 
102
127
  pi.registerCommand("evals", {
103
- description: "Usage and process records: /evals [status|findings|extract|report|mark <note>|label]",
128
+ description: "Usage and process records: /evals [status|findings|extract|report|mark <note>|label|run <script>]",
104
129
  getArgumentCompletions: (prefix: string) => {
130
+ if (prefix.startsWith("run ")) {
131
+ const names = Object.keys(SCRIPTS).filter((n) => n.startsWith(prefix.slice(4)));
132
+ return names.length ? names.map((n) => ({ value: `run ${n}`, label: n, description: SCRIPTS[n] })) : null;
133
+ }
105
134
  const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
106
135
  return items.length ? items : null;
107
136
  },
@@ -141,6 +170,18 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
141
170
  ctx.ui.notify(`pi-evals: marked ${change.at}: ${text}`, "info");
142
171
  } else if (sub === "label") {
143
172
  await labels.command(words.slice(1), ctx);
173
+ } else if (sub === "run") {
174
+ const name = words[1];
175
+ if (!name) {
176
+ ctx.ui.notify(`pi-evals scripts (/evals run <script> [args]):\n${Object.entries(SCRIPTS).map(([n, what]) => `${n} ${what}`).join("\n")}`, "info");
177
+ return;
178
+ }
179
+ if (!Object.hasOwn(SCRIPTS, name)) {
180
+ ctx.ui.notify(`Unknown script "${name}". /evals run lists them.`, "warning");
181
+ return;
182
+ }
183
+ const { code, out } = await runScript(name, words.slice(2), env);
184
+ ctx.ui.notify(out || `${name}: no output (exit ${code})`, code === 0 ? "info" : "warning");
144
185
  } else {
145
186
  ctx.ui.notify(`Unknown subcommand "${sub}". Use: ${SUBCOMMANDS.join(", ")}.`, "warning");
146
187
  }
package/src/plan-graph.ts CHANGED
@@ -44,6 +44,11 @@ function text(content: unknown): string {
44
44
  return Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "";
45
45
  }
46
46
 
47
+ /** A main's kind from the sb role prompt section, if it is a main's prompt. */
48
+ export function sbKindOf(section: string): string | undefined {
49
+ return STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1];
50
+ }
51
+
47
52
  export class PlanGraphTracker {
48
53
  private kind: string | undefined;
49
54
  private wasMain = false;
@@ -73,7 +78,7 @@ export class PlanGraphTracker {
73
78
  if (message.role === "system") {
74
79
  const section = obj(message.sections)["straw-boss"];
75
80
  if (typeof section !== "string") return;
76
- this.setKind(STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1]);
81
+ this.setKind(sbKindOf(section));
77
82
  } else if (message.role === "assistant" && Array.isArray(message.content)) {
78
83
  for (const raw of message.content) {
79
84
  const part = obj(raw);
package/src/shape.ts ADDED
@@ -0,0 +1,123 @@
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.ts";
9
+ import { graphOfTodo, sbKindOf } from "./plan-graph.ts";
10
+ import { safeName } from "./schema.ts";
11
+
12
+ type Obj = Record<string, unknown>;
13
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
14
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
15
+ const text = (content: unknown) => (typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "");
16
+
17
+ function counts(list: string[]): string {
18
+ const by = new Map<string, number>();
19
+ for (const k of list) by.set(k, (by.get(k) ?? 0) + 1);
20
+ return [...by].map(([k, n]) => `${n} ${k}`).join(", ");
21
+ }
22
+
23
+ /** Lines of the trace, then one line per detector result. */
24
+ export async function sessionShape(file: string): Promise<string[]> {
25
+ const out: string[] = [];
26
+ const tracker = new ProcessTracker();
27
+ const calls = new Map<string, { name: string; path?: string; check?: boolean; evidence?: string; action?: string; role?: string }>();
28
+ let start = "";
29
+ let seq = 0;
30
+ let firstUser = true;
31
+ let lastTodo = "";
32
+ const at = (ts: unknown) => {
33
+ const t = Date.parse(str(ts) ?? "");
34
+ if (!start || !Number.isFinite(t)) return "";
35
+ const s = Math.max(0, Math.round((t - Date.parse(start)) / 1000));
36
+ return ` +${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
37
+ };
38
+ const push = (entry: Obj, what: string) => out.push(`#${seq}${at(entry.timestamp)} ${what}`);
39
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Number.POSITIVE_INFINITY });
40
+ for await (const line of lines) {
41
+ if (!line || line.charCodeAt(0) !== 123) continue;
42
+ let entry: Obj;
43
+ try {
44
+ entry = JSON.parse(line) as Obj;
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)) start = str(entry.timestamp)!;
56
+ if (type === "compaction") push(entry, "compaction");
57
+ else if (type === "custom") {
58
+ const data = obj(entry.data);
59
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks)) {
60
+ const tasks = data.tasks.map(obj);
61
+ const ev = tasks.flatMap((t) => (Array.isArray(t.evidence) ? t.evidence.map((e) => `evidence ${obj(e).result === "pass" ? "pass" : "fail"}`) : []));
62
+ const graph = tasks.some((t) => graphOfTodo(t)) ? "; graph named" : "";
63
+ const now = `todo list: ${counts(tasks.map((t) => safeName(t.status)))}${ev.length ? `; ${counts(ev)}` : ""}${graph}`;
64
+ if (now !== lastTodo) push(entry, now);
65
+ lastTodo = now;
66
+ } else if (entry.customType === "straw-boss" && typeof data.duty === "string") push(entry, `sb kind ${safeName(data.duty)} (kind entry)`);
67
+ } else if (type === "custom_message") {
68
+ const details = obj(entry.details);
69
+ if (entry.customType === "anchorloop-close-guard") push(entry, `close-guard ${noticeKind(entry.content)}`);
70
+ else if (entry.customType === "pi-loop-monitor") {
71
+ const o = obj(details.monitorOutcome);
72
+ if (details.deliveryGroup === "monitor-terminal") push(entry, `monitor ${safeName(str(o.monitorId) ?? "?")} ended ${typeof o.exitCode === "number" ? `exit=${o.exitCode}` : safeName(o.status)}`);
73
+ } else if (entry.customType === "straw-boss" && details.briefed) {
74
+ const b = obj(details.briefed);
75
+ push(entry, `sb role ${safeName(b.name ?? b.role)} ${b.duty ? safeName(b.duty) : ""}`.trim());
76
+ } else if (entry.customType === "subagent_result") push(entry, "subagent result");
77
+ } else if (type === "message") {
78
+ const message = obj(entry.message);
79
+ if (message.role === "system") {
80
+ const section = obj(message.sections)["straw-boss"];
81
+ if (typeof section === "string") push(entry, `sb kind ${sbKindOf(section) ?? "none (not a main)"} (role prompt)`);
82
+ } else if (message.role === "user") {
83
+ const words = text(message.content);
84
+ push(entry, firstUser ? `user brief${namesCheck(words) ? " (names a check)" : ""}` : "user");
85
+ firstUser = false;
86
+ } else if (message.role === "assistant" && Array.isArray(message.content)) {
87
+ for (const raw of message.content) {
88
+ const part = obj(raw);
89
+ if (part.type === "text" && typeof part.text === "string" && anchorLine(part.text) !== undefined) push(entry, "anchor stated");
90
+ if (part.type !== "toolCall" || typeof part.id !== "string") continue;
91
+ const args = obj(part.arguments);
92
+ const name = safeName(part.name);
93
+ const command = str(args.command);
94
+ const items = [args, ...(Array.isArray(args.tasks) ? args.tasks.map(obj) : [])];
95
+ const evidence = items.flatMap((i) => (Array.isArray(i.evidence) ? i.evidence.map((e) => (obj(e).result === "pass" ? "pass" : "fail")) : []));
96
+ calls.set(part.id, {
97
+ name,
98
+ path: str(args.path),
99
+ check: command !== undefined && isCheckRun(command),
100
+ evidence: evidence.length ? counts(evidence.map((e) => `evidence ${e}`)) : undefined,
101
+ action: str(args.action) ? safeName(args.action) : undefined,
102
+ role: name === "subagent" ? safeName(str(args.agent) ?? "default") : undefined,
103
+ });
104
+ if (name === "todo" && items.some((i) => (typeof i.anchor === "string" && i.anchor.trim()) || obj(i.metadata).anchor)) push(entry, "todo anchor set");
105
+ }
106
+ } else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
107
+ const call = calls.get(message.toolCallId);
108
+ if (!call) continue;
109
+ calls.delete(message.toolCallId);
110
+ const code = obj(message.structuredContent).exit_code;
111
+ const ok = typeof code === "number" ? code === 0 : message.isError !== true;
112
+ const status = typeof code === "number" ? `exit=${code}` : ok ? "ok" : "error";
113
+ if (call.name === "edit" || call.name === "write") push(entry, `${call.name} ${call.path ? safeName(call.path) : "?"} ${ok ? "ok" : "error"}`);
114
+ else if (call.name === "bash" || call.name === "MonitorCreate") push(entry, `${call.name === "bash" ? "bash" : "monitor start"}${call.check ? " check" : ""} ${status}`);
115
+ else if (call.name === "todo") push(entry, `todo ${call.action ?? "?"} ${ok ? "ok" : "error"}${call.evidence ? `; ${call.evidence}` : ""}`);
116
+ else if (call.name === "subagent") push(entry, `subagent ${call.role} ${ok ? "launched" : "error"}`);
117
+ else push(entry, `${call.name} ${ok ? "ok" : "error"}`);
118
+ }
119
+ }
120
+ }
121
+ for (const r of tracker.results(start >= ERA_START)) out.push(`${r.name}: ${r.label} (${r.explanation})`);
122
+ return out;
123
+ }