pi-evals 0.6.0 → 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.
@@ -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.
@@ -23,3 +24,13 @@ Reading `labels`: agreement counts the user's verdicts only, split into after th
23
24
  Reading `items`: an item is one todo task from `in_progress` to done or deleted. Subagent cost is exact; main cost is an estimate, split evenly among items in progress at the same moment, so say which part you quote. Compare only like with like (the view already separates work handed to subagents from work the main did itself); when it says "too few items to tell", say that in those words rather than reading the medians. A stall says what woke the main (`human`, `peer`, `child`, `timer`, `ci`, `device`), not why it waited; `on` names the subagent, peer session or sb wait (`W12`, `L340`, `T5`) when known.
24
25
 
25
26
  Lead with what rose, fell or held steady, and give the counts behind the rates. Say “too early to tell” when a side is short or too small; when other changes landed nearby, say “we cannot tell which change mattered.” Even a clear difference is not proof of cause. More sessions or skill loads measure activity, not better work.
27
+
28
+ ## When a number looks wrong
29
+
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.
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.
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/changes.ts CHANGED
@@ -176,3 +176,17 @@ export function versionAt(changes: Change[], pkg: string | string[], at: string)
176
176
  }
177
177
  return version;
178
178
  }
179
+
180
+ /** Whether a dotted version is at or after `min`, by numeric parts; a version that is not dotted numbers (a git sha) is undefined. */
181
+ export function atLeast(version: string | undefined, min: string): boolean | undefined {
182
+ const parts = (v: string | undefined) => (v && /^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : undefined);
183
+ const a = parts(version), b = parts(min);
184
+ if (!a || !b) return undefined;
185
+ for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
186
+ return true;
187
+ }
188
+
189
+ /** Whether a pin change brings `pkg` to `version` or past it, from a version before it (or none): a version it skipped counts. */
190
+ export function crosses(c: Pick<Change, "kind" | "package" | "from" | "to">, pkg: string, version: string): boolean {
191
+ return c.kind === "pin" && c.package === pkg && atLeast(c.to, version) === true && atLeast(c.from, version) !== true;
192
+ }
package/src/detectors.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  * in a monitor (by its exit code), passing evidence recorded after the last change, or, when no anchor command ran,
16
16
  * a test, build, lint or type-check run after it.
17
17
  */
18
+ import { PlanGraphTracker } from "./plan-graph.ts";
18
19
  import type { Label } from "./schema.ts";
19
20
 
20
21
  /**
@@ -22,7 +23,7 @@ import type { Label } from "./schema.ts";
22
23
  * (commit 9f72366, 2026-11-23T10:51:07Z). Sessions that started earlier are out of scope.
23
24
  */
24
25
  export const ERA_START = "2026-11-23T10:51:07.000Z";
25
- export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet"] as const;
26
+ export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet", "plan_names_graph"] as const;
26
27
  export type DetectorName = (typeof DETECTORS)[number];
27
28
  export interface DetectorResult {
28
29
  name: DetectorName;
@@ -55,7 +56,7 @@ function commandsOf(text: string, bare: boolean): string[] {
55
56
  const LABEL = String.raw`(?:reality anchor|anchor|checks?|gates?|verify|verification|done when|驗證|檢查|驗收)`;
56
57
  const LABELLED = new RegExp(String.raw`^[ \t>*_#-]*${LABEL}[*_]*\s*[::][*_]*\s*(.+)$`, "gim");
57
58
 
58
- function anchorLine(text: string): string | undefined {
59
+ export function anchorLine(text: string): string | undefined {
59
60
  return [...text.matchAll(LABELLED)].at(-1)?.[1];
60
61
  }
61
62
 
@@ -81,6 +82,8 @@ const DOTNET_SCRIPT = String.raw`\S*dotnet[\w-]*\.py\s+(?:build|test)\b`;
81
82
  const RUN_START = new RegExp(String.raw`^(?:(?:\S*/)?(?:${RUNNER.source})|${INTERPRETER}?(?:${CHECK_SCRIPT}|${DOTNET_SCRIPT}|\S*\btests?/\S+))`, "i");
82
83
  // A mention in prose, as in a brief: a runner or a check script anywhere in a line.
83
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);
84
87
  // Shell lead-ins stripped from each command segment before matching.
85
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+)+/;
86
89
 
@@ -123,11 +126,13 @@ export class ProcessTracker {
123
126
  private sawUser = false;
124
127
  private briefAnchor = false;
125
128
  private notices = new Map<NoticeKind, number>();
129
+ private plan = new PlanGraphTracker();
126
130
 
127
131
  /** Notice kinds seen so far, for `anchorloop.close_guard.notice` records. */
128
132
  feed(raw: unknown): NoticeKind | undefined {
129
133
  const entry = raw as Entry;
130
134
  const seq = ++this.seq;
135
+ if (entry && typeof entry === "object") this.plan.feed(entry as Record<string, unknown>);
131
136
  if (entry?.type === "custom" && entry.customType === "todo/v1" && entry.data?.v === 1 && Array.isArray(entry.data.tasks)) {
132
137
  this.tasks = entry.data.tasks;
133
138
  return undefined;
@@ -212,8 +217,9 @@ export class ProcessTracker {
212
217
  }
213
218
 
214
219
  results(inScope: boolean): DetectorResult[] {
215
- if (!inScope) return DETECTORS_ALL.map((name) => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" }));
216
- return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet()];
220
+ // The anchorloop era bounds the anchorloop rules only; the sb planning rule is judged in every session (long-lived mains started earlier).
221
+ if (!inScope) return [...DETECTORS_ALL.filter((name) => name !== "plan_names_graph").map((name): DetectorResult => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" })), this.plan.results()];
222
+ return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet(), this.plan.results()];
217
223
  }
218
224
 
219
225
  private anchorFirst(): DetectorResult {
@@ -15,10 +15,16 @@ export interface FileEntry {
15
15
  key: string;
16
16
  month: string;
17
17
  summary: SessionSummary;
18
+ /**
19
+ * The extractor version that wrote this summary. A summary is current only when it equals EXTRACTOR_VERSION, so an
20
+ * extract stopped after a version bump leaves the files it did not reach stale for the next run. Entries from 0.6.0
21
+ * and before carry none and are read again.
22
+ */
23
+ extractor?: number;
18
24
  }
19
25
 
20
- /** Bump when extraction changes what it derives; a checkpoint from another version re-reads every file. */
21
- export const EXTRACTOR_VERSION = 5;
26
+ /** Bump when extraction changes what it derives; every summary written by another version is read again. */
27
+ export const EXTRACTOR_VERSION = 6;
22
28
 
23
29
  export interface Checkpoint {
24
30
  v: 1;
@@ -141,12 +147,11 @@ export async function extract(options: {
141
147
  const started = Date.now();
142
148
  const checkpoint = loadCheckpoint(options.layout.checkpoint);
143
149
  const files = listSessionFiles(options.roots);
144
- const rereadAll = checkpoint.extractor !== EXTRACTOR_VERSION;
150
+ // The checkpoint-wide field only says which version last ran; staleness is per entry (an interrupted run saves both kinds).
145
151
  checkpoint.extractor = EXTRACTOR_VERSION;
146
152
  const changed = files.filter((f) => {
147
153
  const known = checkpoint.files[f.path];
148
- if (rereadAll) return true;
149
- return !known || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
154
+ return !known || known.extractor !== EXTRACTOR_VERSION || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
150
155
  });
151
156
  const stats: ExtractStats = { files: files.length, changed: changed.length, failed: 0, bytes: 0, records: 0, ms: 0, errors: [] };
152
157
  const byPath = new Map(changed.map((f) => [f.path, f]));
@@ -175,7 +180,7 @@ export async function extract(options: {
175
180
  } else {
176
181
  stats.records += result.records;
177
182
  const key = fileKey(file.path);
178
- checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary };
183
+ checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary, extractor: EXTRACTOR_VERSION };
179
184
  if (result.catalog?.length) {
180
185
  const hash = createHash("sha1").update(result.catalog.join("\n")).digest("hex").slice(0, 16);
181
186
  result.summary.catalog = hash;
@@ -396,7 +396,7 @@ export class SessionReader {
396
396
  const evals: SessionSummary["evals"] = {};
397
397
  for (const result of this.tracker.results(inScope)) {
398
398
  evals[result.name] = { label: result.label, value: result.value, explanation: result.explanation };
399
- if (inScope) {
399
+ if (result.explanation !== "out_of_scope_pre_3.0") {
400
400
  const t = (startDay.detectors[result.name] ??= { pass: 0, fail: 0, na: 0 });
401
401
  t[result.label] += 1;
402
402
  }
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/meta.ts CHANGED
@@ -18,6 +18,8 @@ export interface MetricMeta {
18
18
 
19
19
  export interface DetectorMeta extends MetricMeta {
20
20
  example: { pass: Text; fail: Text };
21
+ /** The package version whose arrival this detector measures: its results are also split by that package's version, and the pin change that brings it is highlighted. */
22
+ introducedIn?: { package: string; version: string };
21
23
  }
22
24
 
23
25
  const t = (en: string, zh: string): Text => ({ en, zh });
@@ -290,6 +292,23 @@ export const DETECTOR_META: Record<string, DetectorMeta> = {
290
292
  fail: t("Edits and ends; the guard adds 'no passing run of `npm test`'.", "改檔就結束,收尾檢查加上「沒有 `npm test` 的通過紀錄」。"),
291
293
  },
292
294
  },
295
+ plan_names_graph: {
296
+ introducedIn: { package: "pi-straw-boss", version: "0.101.0" },
297
+ label: t("Plan says how the work splits", "排工作時說清楚怎麼分工"),
298
+ meaning: t(
299
+ "When a Straw Boss main (coordinator or standing) writes its plan as todos, it names the plan's shape: one loop it runs itself, parallel workers it merges, or an orchestrator handing work out.",
300
+ "Straw Boss 的主代理(協調或常駐)把計畫寫成待辦時,有說明這份計畫的分工方式:自己一路做完、分給幾個人平行做再合併,或由主代理派工給工作者。",
301
+ ),
302
+ goodDirection: "higher",
303
+ howComputed: t(
304
+ "Passes when the open todos left by the main's first todo create carry a graph (the todo's graph field, or an older metadata.graph), or when its next todo call adds one, as sb 0.101.0 and later ask on that create. Fails when it went on planning without one. Sessions that are not such a main, or never planned, do not count.",
305
+ "主代理第一次建立待辦後,還沒完成的待辦有標分工方式(待辦的 graph 欄位,或舊版的 metadata.graph)即通過;第一次沒標、但下一次動待辦時補上的也算通過(sb 0.101.0 起會在那次建立待辦時提醒)。沒標就繼續排工作的不通過。不是這類主代理、或從沒排過工作的不算。",
306
+ ),
307
+ example: {
308
+ pass: t("Creates three todos with graph 'fan-out/fan-in', then dispatches them.", "建立三項待辦並標上「fan-out/fan-in」,再派出去。"),
309
+ fail: t("Creates three todos with no graph, gets sb's reminder, and adds a fourth without one.", "建立三項待辦沒標分工方式,收到 sb 提醒後又加了第四項,仍然沒標。"),
310
+ },
311
+ },
293
312
  };
294
313
 
295
314
  export const NOTICE_META: Record<string, Text> = {
package/src/model.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { existsSync } from "node:fs";
6
6
  import { ASK_BUCKETS, type DayAgg, emptyDay, mergeDay, type SessionRow } from "./aggregate.ts";
7
7
  import type { DaysIndex } from "./build.ts";
8
- import { type Change, versionAt } from "./changes.ts";
8
+ import { atLeast, type Change, versionAt } from "./changes.ts";
9
9
  import type { Coverage } from "./coverage.ts";
10
10
  import { DETECTORS, ERA_START } from "./detectors.ts";
11
11
  import { CHANGE_KIND_META, CLOSE_KIND_META, DETECTOR_META, METRICS, NOTICE_META, STALL_KIND_META } from "./meta.ts";
@@ -126,6 +126,38 @@ export function impactMetrics(rows: SessionRow[], ownerOf: (tool: string) => str
126
126
  anchor_before_first_edit: d("anchor_before_first_edit"),
127
127
  check_after_last_edit: d("check_after_last_edit"),
128
128
  todo_evidence: d("todo_evidence"),
129
+ plan_names_graph: d("plan_names_graph"),
130
+ };
131
+ }
132
+
133
+ /** Dotted versions in numeric order; anything else (unknown, a sha) after them. */
134
+ const byVersion = (a: string, b: string) => {
135
+ const pa = /^\d+(\.\d+)*$/.test(a) ? a.split(".").map(Number) : undefined, pb = /^\d+(\.\d+)*$/.test(b) ? b.split(".").map(Number) : undefined;
136
+ if (!pa || !pb) return pa ? -1 : pb ? 1 : a.localeCompare(b);
137
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);
138
+ return 0;
139
+ };
140
+
141
+ /** A detector's results by the version of the package it measures, at each session's start, and before and from the version that brought it. */
142
+ export function packageSplit(rows: SessionRow[], changes: Change[], detector: string, since: { package: string; version: string }) {
143
+ const versions = new Map<string, { pass: number; fail: number }>();
144
+ const sides = { before: { pass: 0, fail: 0 }, after: { pass: 0, fail: 0 } };
145
+ for (const r of rows) {
146
+ const v = r.ev[detector];
147
+ if (v === undefined) continue;
148
+ const version = versionAt(changes, since.package, r.s) ?? "unknown";
149
+ const cell = versions.get(version) ?? { pass: 0, fail: 0 };
150
+ cell[v ? "pass" : "fail"] += 1;
151
+ versions.set(version, cell);
152
+ const later = atLeast(version, since.version);
153
+ if (later !== undefined) sides[later ? "after" : "before"][v ? "pass" : "fail"] += 1;
154
+ }
155
+ const withRate = (x: { pass: number; fail: number }) => ({ ...x, passRate: rate(x.pass, x.pass + x.fail) });
156
+ return {
157
+ ...since,
158
+ versions: [...versions].sort(([a], [b]) => byVersion(a, b)).map(([version, x]) => ({ version, ...withRate(x) })),
159
+ before: withRate(sides.before),
160
+ after: withRate(sides.after),
129
161
  };
130
162
  }
131
163
 
@@ -309,6 +341,7 @@ export function buildModel(options: {
309
341
  return { day, pass: x.pass, fail: x.fail };
310
342
  }),
311
343
  byVersion: (versions.get(d.name) ?? []).map((v) => ({ ...v, passRate: rate(v.pass, v.pass + v.fail) })),
344
+ byPackage: DETECTOR_META[d.name]?.introducedIn ? packageSplit(selected, sortedChanges, d.name, DETECTOR_META[d.name].introducedIn!) : null,
312
345
  })),
313
346
  notices: total.notices,
314
347
  },