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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ - The analysis scripts from labelling and error analysis ship in `scripts/`: `freshness` (is the index current; exits 1 when summaries come from mixed extractor versions), `disagree <rule>` (where the code and your labels disagree, session by session, and which way), `by-version <detector>` (pass rate per package version), `sample <n>` (a stratified, seeded sample of unlabelled sessions to label), `label-import <answers>` (a submitted label form into `labels.jsonl`), and `session-shape <id>` (the ordered events the detectors see, without message text). Output over 2,000 bytes goes to a file under `runs/` in the state dir.
6
+ - `/evals run` lists the scripts with what each is for; `/evals run <script> [args]` runs one and shows its output, with script names completed.
7
+ - The analyzing-evals skill names these scripts at the steps that use them: freshness first, disagree and session-shape when a number looks wrong, sample and label-import for hand labels.
8
+
9
+ ## 0.6.1
10
+
11
+ - An extract stopped part-way after an extractor upgrade no longer passes off old results as current. Each session file's summary now records the extractor version that wrote it, and any other version is read again. Before, the first 0.6.0 extract was killed by a timeout and saved the new version mark while most summaries were still old, so the next run skipped them: check agreement read 11/20 instead of 23/24 until a full rebuild. Every session is read once more (extractor version 6).
12
+ - New check 「排工作時說清楚怎麼分工」 (`plan_names_graph`): whether a Straw Boss coordinator or standing main names its plan's graph (`single-loop`, `fan-out/fan-in`, `orchestrator-worker`; the todo's `graph` field or an older `metadata.graph`) when it first creates open todos. It also passes when the next todo call adds the graph after sb's planning reminder (sb 0.101.0 and later). It fails when the main keeps planning without one. Unlike the anchorloop checks, it is judged in sessions of any age, since sb mains live for weeks.
13
+ - The process view and report also split this check by pi-straw-boss version at session start, before and from 0.101.0. The change strip always highlights the sb pin that brings 0.101.0, including one that skips it (0.100.2 → 0.102.0, captioned 「含 0.101.0」).
14
+ - The analyzing-evals skill gains 「When a number looks wrong」: check freshness first, validate a detector against your labels, group misses by cause, keep a guard set, and treat hand labels as the reference.
15
+
3
16
  ## 0.6.0
4
17
 
5
18
  - New command `/ask-ai <question>` has the agent answer you now instead of taking the question as a reproach and starting new work. The question goes in with a short instruction: answer first, in your language, change nothing, start no work, and end with at most one line of suggested next step. While that run lasts (until it ends or you send another message), `write`, `edit`, `subagent`, `boss_pair`, `MonitorCreate`, `LoopCreate`, `call_tower`, `todo` (except `list`/`get`) and `intercom` (`send`/`ask`/`handover`) are refused with a one-line reason; `bash`, `read` and other tools still run.
package/README.md CHANGED
@@ -11,7 +11,7 @@ Agents can read the same numbers through one tool, `evals_query`, and log a corr
11
11
  - **Ask-user**: questions asked, how long you took to answer, how many you dismissed, and whether the answer came from the terminal or a remote channel.
12
12
  - **Monitors**: background jobs by outcome and duration.
13
13
  - **Subagents**: launches by role and model, and their cost by role.
14
- - **Process**: four checks of the anchorloop rules per session, for sessions started after anchorloop 3.0.0 was pinned (2026-11-23T10:51:07Z); see [docs/design.md](docs/design.md#process-detectors).
14
+ - **Process**: four checks of the anchorloop rules per session, and one of the Straw Boss planning rule (a coordinator or standing main names its plan's graph), for sessions started after anchorloop 3.0.0 was pinned (2026-11-23T10:51:07Z); see [docs/design.md](docs/design.md#process-detectors).
15
15
  - **Cost**: model cost and tokens, and the cost of the sessions that loaded each skill.
16
16
  - **Work items**: each todo task from the moment it is switched to in progress until it is done or deleted: what it cost (subagents exactly, the main agent as an even share), where it closed (reviewer approval, a landed car, a wrap, evidence), where it stalled and on whom, and whether one way of working is cheaper than another of the same kind.
17
17
  - **Your labels and corrections**: your verdict on a process rule, given in the moment with `/evals label` or after the fact, and the corrections an agent logs when you correct how it worked.
@@ -48,13 +48,29 @@ The observer loads in every session, subagents included.
48
48
  | `/evals report [--since YYYY-MM-DD \| --days N] [--project <key>]` | Builds the linked date ranges, or one custom report when a start date or day count is given. |
49
49
  | `/evals mark <note>` | Adds a note to the change timeline, e.g. `/evals mark workers moved to gpt-6.2-astra`. |
50
50
  | `/evals label` | Labels the current session while the work is in front of you: pick a rule (or 「其他」), then 照做, 沒照做 or 看不出來, then an optional note in your own words. |
51
- | `/evals label <rule> pass\|fail\|unclear [note]` | The same in one line; `<rule>` is a check name (`anchor_before_first_edit`, `check_after_last_edit`, `todo_evidence`, `close_guard_quiet`) or `other`. |
51
+ | `/evals label <rule> pass\|fail\|unclear [note]` | The same in one line; `<rule>` is a check name (`anchor_before_first_edit`, `check_after_last_edit`, `todo_evidence`, `close_guard_quiet`, `plan_names_graph`) or `other`. |
52
52
  | `/evals label <your words>` | Anything else, e.g. `/evals label 剛剛沒先跑測試就說完成`: the agent turns your words into labels with `evals_label` and says in one line what it recorded. The verdict is yours and your words are kept as the note. |
53
53
  | `/evals label undo` | Withdraws the current session's last label given in the moment. |
54
+ | `/evals run` | Lists the shipped analysis scripts, each with what it is for. |
55
+ | `/evals run <script> [args]` | Runs one and shows its output; output over 2,000 bytes goes to a file under `runs/` in the state dir and the reply names it. |
54
56
 
55
57
  A label records the session, the time, and the key of the todo item in progress, if any (its `uid`, else `<session>#<id>`, as work items are keyed).
56
58
  It reaches the report and `evals_query` at their next read, without an extract.
57
59
 
60
+ ### Analysis scripts
61
+
62
+ Shipped in `scripts/`; run them with `/evals run`, or with `node <package>/scripts/<name>.mjs` (agents do, through the analyzing-evals skill). They read the index, checkpoint, labels and change timeline, never a transcript into their output; `session-shape` reads one session file to classify its events and prints no message text.
63
+
64
+ | Script | What it answers |
65
+ | --- | --- |
66
+ | `freshness` | Is the index current: last extract, summaries per extractor version, a run stopped part-way. Exits 1 when versions are mixed. |
67
+ | `disagree <rule> [--range DAYS]` | Each labelled session where the code and your verdict in effect disagree, with the code's reason and where the label came from, and which way they lean. |
68
+ | `by-version <detector> [--pkg PACKAGE]` | Pass rate and n per package version at session start (anchorloop by default; pi-straw-boss for `plan_names_graph`). |
69
+ | `sample <n> [--since ISO] [--seed N]` | A seeded sample of judged sessions you have not labelled, spread over project, kind, model and size, written to `labels/sample-<date>.json` (ids and metadata only). |
70
+ | `label-import <answer-file> [--sample FILE]` | Your submitted label form (`- <n>_<rule>: pass`, `- <n>_type: …`, `- <n>_note: …`) as after-the-fact labels in `labels.jsonl`. |
71
+ | `session-shape <session id>` | The events the detectors see, in order: tools, edit paths, check runs by exit code, todo statuses and evidence, close-guard reminders, the sb role; then each detector's verdict. |
72
+ | `change-impact`, `skill-days`, `package-errors` | A change's numbers before and after; a skill's sessions per day; a package's errors per day. |
73
+
58
74
  ### `/ask-ai`: get an answer before the agent acts
59
75
 
60
76
  | Command | What it does |
@@ -150,7 +166,7 @@ Use the section links for usage, process checks, cost and cleanup coverage, or r
150
166
  | --- | --- |
151
167
  | `events/<YYYY-MM-DD>.jsonl` | Live observer records. |
152
168
  | `index/records/<YYYY-MM>/<key>.jsonl` | Back-filled records, one file per session file. |
153
- | `index/checkpoint.json` | Size, modification time and summary per session file. |
169
+ | `index/checkpoint.json` | Size, modification time, summary and the extractor version that wrote it, per session file. |
154
170
  | `index/days.json` | Aggregates by day and project. |
155
171
  | `index/sessions.json` | A few numbers per session with its start time, for splitting sessions at a change's time. |
156
172
  | `index/session-evals.json` | Process check results per session, for joining your labels. |
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The analysis scripts' logic (scripts/*.mjs are thin wrappers): freshness, disagree, by-version, sample and
3
+ * label-import. Each reads the index, checkpoint, labels or change timeline and returns lines; none prints message
4
+ * text or a label's note.
5
+ */
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { loadRows } from "./build.js";
9
+ import { readChanges, versionAt } from "./changes.js";
10
+ import { DETECTORS, ERA_START } from "./detectors.js";
11
+ import { EXTRACTOR_VERSION, loadCheckpoint } from "./extract/run.js";
12
+ import { appendLabel, cleanNote, FAILURE_TYPES, readLabels, RULES } from "./labels.js";
13
+ import { DETECTOR_META } from "./meta.js";
14
+ import { safeName } from "./schema.js";
15
+ import { ANCHORLOOP } from "./work/join.js";
16
+ export class AnalysisError extends Error {
17
+ }
18
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
19
+ const pct = (num, den) => (den ? `${((100 * num) / den).toFixed(1)}%` : "n/a");
20
+ function checkpointOf(lay) {
21
+ if (!existsSync(lay.checkpoint))
22
+ throw new AnalysisError("No checkpoint. Run /evals extract first.");
23
+ return loadCheckpoint(lay.checkpoint);
24
+ }
25
+ function lastExtractOf(lay, cp) {
26
+ try {
27
+ return JSON.parse(readFileSync(lay.status, "utf8")).lastExtract ?? cp.lastExtract;
28
+ }
29
+ catch {
30
+ return cp.lastExtract;
31
+ }
32
+ }
33
+ /** Last extract, summaries per extractor version, and signs of a run stopped part-way; status 1 when versions are mixed. */
34
+ export function freshness(lay, now = Date.now()) {
35
+ const cp = checkpointOf(lay);
36
+ const last = lastExtractOf(lay, cp);
37
+ const by = new Map();
38
+ for (const f of Object.values(cp.files)) {
39
+ const key = f.extractor === undefined ? "unstamped (0.6.0 or older)" : String(f.extractor);
40
+ by.set(key, (by.get(key) ?? 0) + 1);
41
+ }
42
+ const lines = [`last extract ${last ?? "never"}${last ? ` (${((now - Date.parse(last)) / 3_600_000).toFixed(1)} h ago)` : ""}`, `this pi-evals writes extractor ${EXTRACTOR_VERSION}`];
43
+ for (const [version, n] of [...by].sort())
44
+ lines.push(`extractor ${version}: ${plural(n, "summary", "summaries")}`);
45
+ const saved = statSync(lay.checkpoint).mtimeMs;
46
+ if (last && saved > Date.parse(last) + 120_000)
47
+ lines.push("The checkpoint was saved after the last finished extract: a run stopped part-way.");
48
+ if (existsSync(lay.days) && last) {
49
+ const built = JSON.parse(readFileSync(lay.days, "utf8")).built;
50
+ if (built && built < last)
51
+ lines.push(`The index (built ${built}) is older than the last extract: run /evals extract to rebuild it.`);
52
+ }
53
+ const mixed = [...by.keys()].some((v) => v !== String(EXTRACTOR_VERSION));
54
+ if (mixed)
55
+ lines.push(`STALE: some summaries are from another extractor version. Run /evals extract to finish; do not read the numbers until this passes.`);
56
+ else
57
+ lines.push("Fresh: every summary is from the current extractor.");
58
+ return { lines, status: mixed ? 1 : 0 };
59
+ }
60
+ const sourceOf = (r) => (r.source === "live" ? "live" : r.source === "live-prompt" ? "prompt" : "after");
61
+ /** Code verdicts and explanations by session id, with each session's start. */
62
+ function verdicts(cp, rule) {
63
+ const out = new Map();
64
+ for (const f of Object.values(cp.files)) {
65
+ const r = f.summary.evals[rule];
66
+ if (r)
67
+ out.set(f.summary.sessionId, { label: r.label, why: r.explanation, start: f.summary.start });
68
+ }
69
+ return out;
70
+ }
71
+ /** Per labelled session, the user's verdict in effect against the code's, and which way the disagreements lean. */
72
+ export function disagree(lay, rule, rangeDays) {
73
+ if (!DETECTORS.includes(rule))
74
+ throw new AnalysisError(`Unknown rule. Rules: ${DETECTORS.join(", ")}.`);
75
+ const cp = checkpointOf(lay);
76
+ const code = verdicts(cp, rule);
77
+ const last = Date.parse(lastExtractOf(lay, cp) ?? new Date().toISOString());
78
+ const rows = readLabels(lay.labels).filter((r) => r.annotator !== "agent" && r.evaluation_name === rule && !r.undo);
79
+ let agree = 0, unclear = 0, noCode = 0, under = 0, over = 0;
80
+ const listed = [];
81
+ for (const r of rows) {
82
+ const c = code.get(r.session_id);
83
+ if (rangeDays !== undefined && (!c || Date.parse(c.start) < last - rangeDays * 86_400_000))
84
+ continue;
85
+ if (r.label === "unclear") {
86
+ unclear += 1;
87
+ continue;
88
+ }
89
+ if (!c || c.label === "na") {
90
+ noCode += 1;
91
+ continue;
92
+ }
93
+ if (c.label === r.label) {
94
+ agree += 1;
95
+ continue;
96
+ }
97
+ if (c.label === "fail")
98
+ under += 1;
99
+ else
100
+ over += 1;
101
+ listed.push(`${safeName(r.session_id)} human ${r.label}, code ${c.label} (${safeName(c.why)}), ${sourceOf(r)}`);
102
+ }
103
+ const lean = !listed.length ? "No disagreements." : under === over ? "The disagreements split evenly." : under > over
104
+ ? "Most disagreements are code fail / human pass: the detector undercounts; its rate is too low."
105
+ : "Most disagreements are code pass / human fail: the detector overcounts; its rate is too high.";
106
+ return {
107
+ lines: [
108
+ `${rule}${rangeDays !== undefined ? ` (sessions of the last ${rangeDays} days)` : ""}: ${agree + listed.length} labelled, ${agree} agree, ${listed.length} disagree; unclear ${unclear}; no code verdict ${noCode}`,
109
+ ...listed,
110
+ `code fail / human pass: ${under} (detector undercounts)`,
111
+ `code pass / human fail: ${over} (detector overcounts)`,
112
+ lean,
113
+ ],
114
+ };
115
+ }
116
+ const numeric = (v) => (/^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : undefined);
117
+ function byVersionOrder(a, b) {
118
+ const x = numeric(a), y = numeric(b);
119
+ if (!x || !y)
120
+ return x ? -1 : y ? 1 : a.localeCompare(b);
121
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
122
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
123
+ return (x[i] ?? 0) - (y[i] ?? 0);
124
+ return 0;
125
+ }
126
+ /** A detector's pass rate per version of a package at each session's start. */
127
+ export function byVersion(lay, detector, pkg) {
128
+ if (!DETECTORS.includes(detector))
129
+ throw new AnalysisError(`Unknown detector. Detectors: ${DETECTORS.join(", ")}.`);
130
+ const names = pkg ? [pkg] : DETECTOR_META[detector]?.introducedIn ? [DETECTOR_META[detector].introducedIn.package] : ANCHORLOOP;
131
+ const changes = readChanges(lay.changes);
132
+ const cells = new Map();
133
+ for (const r of loadRows(lay)) {
134
+ const v = r.ev[detector];
135
+ if (v === undefined)
136
+ continue;
137
+ const version = versionAt(changes, names, r.s) ?? "unknown";
138
+ const cell = cells.get(version) ?? { pass: 0, n: 0 };
139
+ cell.pass += v;
140
+ cell.n += 1;
141
+ cells.set(version, cell);
142
+ }
143
+ if (!cells.size)
144
+ return { lines: [`${detector} by ${names[0]} version: no judged sessions in the index.`] };
145
+ return {
146
+ lines: [
147
+ `${detector} by ${names[0]} version at session start (pass / judged):`,
148
+ ...[...cells].sort(([a], [b]) => byVersionOrder(a, b)).map(([v, c]) => `${v}: ${c.pass}/${c.n} ${pct(c.pass, c.n)}`),
149
+ "Versions differ in time as well as code: other changes landed in the same days.",
150
+ ],
151
+ };
152
+ }
153
+ /** Small seeded generator (mulberry32). */
154
+ function random(seed) {
155
+ let a = seed >>> 0;
156
+ return () => {
157
+ a = (a + 0x6d2b79f5) >>> 0;
158
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
159
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
160
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
161
+ };
162
+ }
163
+ const sizeOf = (calls) => (calls < 20 ? "small" : calls < 100 ? "medium" : "large");
164
+ /** A stratified sample of judged sessions the user has not labelled yet, written to `<state>/labels/sample-<date>.json`. */
165
+ export function sample(lay, n, options = {}) {
166
+ if (!Number.isSafeInteger(n) || n < 1 || n > 500)
167
+ throw new AnalysisError("n must be 1 to 500.");
168
+ const since = options.since ?? ERA_START;
169
+ if (!Number.isFinite(Date.parse(since)))
170
+ throw new AnalysisError("--since must be an ISO time.");
171
+ const now = options.now ?? new Date();
172
+ const seed = options.seed ?? Number(now.toISOString().slice(0, 10).replaceAll("-", ""));
173
+ const labelled = new Set(readLabels(lay.labels).filter((r) => r.annotator !== "agent").map((r) => r.session_id));
174
+ const strata = new Map();
175
+ const seen = new Set();
176
+ let judged = 0;
177
+ for (const f of Object.values(checkpointOf(lay).files)) {
178
+ const s = f.summary;
179
+ if (!s.sessionId || seen.has(s.sessionId) || labelled.has(s.sessionId) || s.start < since)
180
+ continue;
181
+ seen.add(s.sessionId);
182
+ if (!Object.values(s.evals).some((r) => r && r.label !== "na"))
183
+ continue;
184
+ judged += 1;
185
+ const row = { session_id: s.sessionId, project: s.project, kind: s.kind, model: safeName(s.model ?? "unknown"), start: s.start, tool_calls: s.toolCalls, size: sizeOf(s.toolCalls) };
186
+ const key = `${row.project}|${row.kind}|${row.model}|${row.size}`;
187
+ strata.set(key, [...(strata.get(key) ?? []), row]);
188
+ }
189
+ const next = random(seed);
190
+ const shuffle = (list) => {
191
+ for (let i = list.length - 1; i > 0; i--) {
192
+ const j = Math.floor(next() * (i + 1));
193
+ [list[i], list[j]] = [list[j], list[i]];
194
+ }
195
+ return list;
196
+ };
197
+ const groups = shuffle([...strata.keys()].sort()).map((k) => shuffle([...strata.get(k)].sort((a, b) => a.session_id.localeCompare(b.session_id))));
198
+ const chosen = [];
199
+ while (chosen.length < n && groups.some((g) => g.length)) {
200
+ for (const g of groups)
201
+ if (g.length && chosen.length < n)
202
+ chosen.push({ n: chosen.length + 1, ...g.pop() });
203
+ }
204
+ const dir = join(lay.state, "labels");
205
+ mkdirSync(dir, { recursive: true });
206
+ const file = join(dir, `sample-${now.toISOString().slice(0, 10)}.json`);
207
+ writeFileSync(file, `${JSON.stringify(chosen, null, 1)}\n`);
208
+ const tally = (key) => [...new Set(chosen.map((c) => c[key]))].map((v) => `${v} ${chosen.filter((c) => c[key] === v).length}`).join(", ");
209
+ return {
210
+ lines: [
211
+ `${chosen.length} of ${judged} judged, unlabelled sessions since ${since} (${strata.size} strata by project, kind, model, size; seed ${seed}; labelled sessions left out)`,
212
+ `kind: ${tally("kind")}`,
213
+ `size: ${tally("size")}`,
214
+ `projects: ${new Set(chosen.map((c) => c.project)).size}`,
215
+ `sample: ${file}`,
216
+ ],
217
+ };
218
+ }
219
+ /** The newest `sample-*.json` under `<state>/labels`. */
220
+ function latestSample(lay) {
221
+ const dir = join(lay.state, "labels");
222
+ const files = existsSync(dir) ? readdirSync(dir).filter((f) => /^sample-.*\.json$/.test(f)).sort() : [];
223
+ if (!files.length)
224
+ throw new AnalysisError("No sample under <state>/labels; run the sample script or pass --sample.");
225
+ return join(dir, files.at(-1));
226
+ }
227
+ /**
228
+ * Form answers (`- <n>_<rule>: pass|fail|unclear`, `- <n>_type: <failure type>`, `- <n>_note: ...`) become after-the-fact
229
+ * human rows, appended to labels.jsonl; a later import of the same session and rule replaces the earlier in effect.
230
+ */
231
+ export function labelImport(lay, answerFile, sampleFile, at = new Date().toISOString()) {
232
+ let answer;
233
+ let entries;
234
+ try {
235
+ answer = readFileSync(answerFile, "utf8");
236
+ }
237
+ catch {
238
+ throw new AnalysisError("Cannot read the answer file.");
239
+ }
240
+ try {
241
+ entries = JSON.parse(readFileSync(sampleFile ?? latestSample(lay), "utf8"));
242
+ }
243
+ catch (error) {
244
+ throw error instanceof AnalysisError ? error : new AnalysisError("Cannot read the sample file.");
245
+ }
246
+ const sessionOf = (n) => entries.find((e) => e.n === n)?.session_id ?? (entries.some((e) => e.n !== undefined) ? undefined : entries[n - 1]?.session_id);
247
+ const fields = new Map();
248
+ let current;
249
+ for (const line of answer.split("\n")) {
250
+ const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
251
+ if (m)
252
+ fields.set((current = m[1]), m[2]);
253
+ else if (/^Other comments:/.test(line))
254
+ current = undefined;
255
+ else if (current !== undefined && line !== "")
256
+ fields.set(current, `${fields.get(current)}\n${line}`);
257
+ }
258
+ const rules = RULES.filter((r) => r !== "other");
259
+ const rows = [];
260
+ const problems = [];
261
+ const noted = new Set();
262
+ for (const [name, raw] of fields) {
263
+ const m = /^(\d+)_([a-z_]+)$/.exec(name);
264
+ if (!m || !rules.includes(m[2]))
265
+ continue;
266
+ const n = Number(m[1]);
267
+ const session = sessionOf(n);
268
+ if (!session) {
269
+ problems.push(`${name}: no session #${n} in the sample`);
270
+ continue;
271
+ }
272
+ const label = raw.trim();
273
+ if (!label)
274
+ continue;
275
+ if (label !== "pass" && label !== "fail" && label !== "unclear") {
276
+ problems.push(`${name}: unknown verdict`);
277
+ continue;
278
+ }
279
+ const row = { session_id: session, evaluation_name: m[2], label, at, annotator: "human", source: "batch" };
280
+ const type = fields.get(`${n}_type`)?.trim();
281
+ if (type && label === "fail") {
282
+ if (FAILURE_TYPES.includes(type))
283
+ row.type = type;
284
+ else
285
+ problems.push(`${n}_type: unknown failure type`);
286
+ }
287
+ const note = cleanNote(fields.get(`${n}_note`));
288
+ if (note && !noted.has(n)) {
289
+ row.note = note;
290
+ noted.add(n);
291
+ }
292
+ rows.push(row);
293
+ }
294
+ for (const row of rows)
295
+ appendLabel(lay.labels, row);
296
+ const per = new Map();
297
+ for (const r of rows)
298
+ per.set(r.evaluation_name, (per.get(r.evaluation_name) ?? 0) + 1);
299
+ return {
300
+ lines: [
301
+ `wrote ${plural(rows.length, "label", "labels")} (after the fact, human) to labels.jsonl${per.size ? `: ${[...per].map(([k, v]) => `${k} ${v}`).join(", ")}` : ""}`,
302
+ ...problems.map((p) => `warning: ${p}`),
303
+ "A later import of the same session and rule replaces this one; labels.jsonl keeps both.",
304
+ ],
305
+ status: rows.length ? 0 : 1,
306
+ };
307
+ }
308
+ /** The session file holding a session id, from the checkpoint. */
309
+ export function sessionFile(lay, id) {
310
+ for (const [path, f] of Object.entries(checkpointOf(lay).files))
311
+ if (f.summary.sessionId === id)
312
+ return path;
313
+ throw new AnalysisError("No such session in the index.");
314
+ }
package/dist/changes.js CHANGED
@@ -168,3 +168,18 @@ export function versionAt(changes, pkg, at) {
168
168
  }
169
169
  return version;
170
170
  }
171
+ /** Whether a dotted version is at or after `min`, by numeric parts; a version that is not dotted numbers (a git sha) is undefined. */
172
+ export function atLeast(version, min) {
173
+ const parts = (v) => (v && /^\d+(\.\d+)*$/.test(v) ? v.split(".").map(Number) : undefined);
174
+ const a = parts(version), b = parts(min);
175
+ if (!a || !b)
176
+ return undefined;
177
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
178
+ if ((a[i] ?? 0) !== (b[i] ?? 0))
179
+ return (a[i] ?? 0) > (b[i] ?? 0);
180
+ return true;
181
+ }
182
+ /** Whether a pin change brings `pkg` to `version` or past it, from a version before it (or none): a version it skipped counts. */
183
+ export function crosses(c, pkg, version) {
184
+ return c.kind === "pin" && c.package === pkg && atLeast(c.to, version) === true && atLeast(c.from, version) !== true;
185
+ }
package/dist/detectors.js CHANGED
@@ -1,9 +1,27 @@
1
+ /**
2
+ * Process detectors over one session, fed entries in file order. Each yields a session-scoped
3
+ * `gen_ai.evaluation.result` (annotator CODE). Commands and text are held in memory only while the
4
+ * session is read; results carry fixed reason codes, never text.
5
+ *
6
+ * Anchor and change reading is ported from pi-anchorloop's close guard (`pi/close-guard.ts` `read()`,
7
+ * MIT, Copyright (c) 2026 Wei Hung, anchorloop 3.3.0 at 7614445): the last `Anchor:` line or todo anchor,
8
+ * backticked commands (a todo's bare value is one command), a change is a successful `write` or `edit`,
9
+ * a bash run passes on exit code 0 (else on `isError` false), and a run matches an anchor command when it contains it.
10
+ * Like the guard, an edit made through bash is not seen as a change.
11
+ *
12
+ * Unlike the guard, these read the other shapes agents state and run a check in (0.5.1, from human labels): an anchor
13
+ * in the brief (`Anchor:`, `Gates:`, `Checks:`, or a check command it names), a labelled check line in the agent's
14
+ * words (`驗證:`, `Verify:`), a todo's sb check spec, or a first change to a test file (red first); and a check run
15
+ * in a monitor (by its exit code), passing evidence recorded after the last change, or, when no anchor command ran,
16
+ * a test, build, lint or type-check run after it.
17
+ */
18
+ import { PlanGraphTracker } from "./plan-graph.js";
1
19
  /**
2
20
  * anchorloop 3.0.0 (one anchor rule and the close guard) reached this setup when weihung-basic-agent pinned it
3
21
  * (commit 9f72366, 2026-11-23T10:51:07Z). Sessions that started earlier are out of scope.
4
22
  */
5
23
  export const ERA_START = "2026-11-23T10:51:07.000Z";
6
- export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet"];
24
+ export const DETECTORS = ["anchor_before_first_edit", "check_after_last_edit", "todo_evidence", "close_guard_quiet", "plan_names_graph"];
7
25
  const NOTICE_TYPE = "anchorloop-close-guard";
8
26
  const MAX_RUNS = 5000;
9
27
  export function noticeKind(text) {
@@ -24,7 +42,7 @@ function commandsOf(text, bare) {
24
42
  }
25
43
  const LABEL = String.raw `(?:reality anchor|anchor|checks?|gates?|verify|verification|done when|驗證|檢查|驗收)`;
26
44
  const LABELLED = new RegExp(String.raw `^[ \t>*_#-]*${LABEL}[*_]*\s*[::][*_]*\s*(.+)$`, "gim");
27
- function anchorLine(text) {
45
+ export function anchorLine(text) {
28
46
  return [...text.matchAll(LABELLED)].at(-1)?.[1];
29
47
  }
30
48
  /** Tools and scripts whose run checks a change: tests, builds, linters, type checkers, and named check scripts. */
@@ -46,6 +64,8 @@ const DOTNET_SCRIPT = String.raw `\S*dotnet[\w-]*\.py\s+(?:build|test)\b`;
46
64
  const RUN_START = new RegExp(String.raw `^(?:(?:\S*/)?(?:${RUNNER.source})|${INTERPRETER}?(?:${CHECK_SCRIPT}|${DOTNET_SCRIPT}|\S*\btests?/\S+))`, "i");
47
65
  // A mention in prose, as in a brief: a runner or a check script anywhere in a line.
48
66
  const MENTION = new RegExp(String.raw `(?:^|[\s\x60("'>/])(?:${RUNNER.source}|${CHECK_SCRIPT})`, "im");
67
+ /** Whether a brief names a check: a labelled check line, or a runner or check script anywhere in it. */
68
+ export const namesCheck = (text) => anchorLine(text) !== undefined || MENTION.test(text);
49
69
  // Shell lead-ins stripped from each command segment before matching.
50
70
  const LEAD = /^(?:[({!]\s*|(?:time|exec|command|nice|sudo\s+-n|timeout\s+\d+[smh]?|set\s+-\S+(?:\s+\S+)?)\s+|[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+/;
51
71
  /** Whether a shell command runs a check: one of its `&&`, `||`, `;`, `|` or line segments starts with a check runner. */
@@ -74,10 +94,13 @@ export class ProcessTracker {
74
94
  sawUser = false;
75
95
  briefAnchor = false;
76
96
  notices = new Map();
97
+ plan = new PlanGraphTracker();
77
98
  /** Notice kinds seen so far, for `anchorloop.close_guard.notice` records. */
78
99
  feed(raw) {
79
100
  const entry = raw;
80
101
  const seq = ++this.seq;
102
+ if (entry && typeof entry === "object")
103
+ this.plan.feed(entry);
81
104
  if (entry?.type === "custom" && entry.customType === "todo/v1" && entry.data?.v === 1 && Array.isArray(entry.data.tasks)) {
82
105
  this.tasks = entry.data.tasks;
83
106
  return undefined;
@@ -176,9 +199,10 @@ export class ProcessTracker {
176
199
  this.runs.splice(0, this.runs.length - MAX_RUNS);
177
200
  }
178
201
  results(inScope) {
202
+ // The anchorloop era bounds the anchorloop rules only; the sb planning rule is judged in every session (long-lived mains started earlier).
179
203
  if (!inScope)
180
- return DETECTORS_ALL.map((name) => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" }));
181
- return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet()];
204
+ return [...DETECTORS_ALL.filter((name) => name !== "plan_names_graph").map((name) => ({ name, label: "na", explanation: "out_of_scope_pre_3.0" })), this.plan.results()];
205
+ return [this.anchorFirst(), this.checkAfter(), this.todoEvidence(), this.quiet(), this.plan.results()];
182
206
  }
183
207
  anchorFirst() {
184
208
  const name = "anchor_before_first_edit";
@@ -6,8 +6,8 @@ import { dirname, join } from "node:path";
6
6
  import { Worker } from "node:worker_threads";
7
7
  import { fileKey } from "../schema.js";
8
8
  import { extractFile } from "./file.js";
9
- /** Bump when extraction changes what it derives; a checkpoint from another version re-reads every file. */
10
- export const EXTRACTOR_VERSION = 5;
9
+ /** Bump when extraction changes what it derives; every summary written by another version is read again. */
10
+ export const EXTRACTOR_VERSION = 6;
11
11
  export function loadCheckpoint(file) {
12
12
  if (!existsSync(file))
13
13
  return { v: 1, extractor: EXTRACTOR_VERSION, files: {}, catalogs: {} };
@@ -93,13 +93,11 @@ export async function extract(options) {
93
93
  const started = Date.now();
94
94
  const checkpoint = loadCheckpoint(options.layout.checkpoint);
95
95
  const files = listSessionFiles(options.roots);
96
- const rereadAll = checkpoint.extractor !== EXTRACTOR_VERSION;
96
+ // The checkpoint-wide field only says which version last ran; staleness is per entry (an interrupted run saves both kinds).
97
97
  checkpoint.extractor = EXTRACTOR_VERSION;
98
98
  const changed = files.filter((f) => {
99
99
  const known = checkpoint.files[f.path];
100
- if (rereadAll)
101
- return true;
102
- return !known || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
100
+ return !known || known.extractor !== EXTRACTOR_VERSION || known.size !== f.size || known.mtimeMs !== f.mtimeMs;
103
101
  });
104
102
  const stats = { files: files.length, changed: changed.length, failed: 0, bytes: 0, records: 0, ms: 0, errors: [] };
105
103
  const byPath = new Map(changed.map((f) => [f.path, f]));
@@ -127,7 +125,7 @@ export async function extract(options) {
127
125
  else {
128
126
  stats.records += result.records;
129
127
  const key = fileKey(file.path);
130
- checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary };
128
+ checkpoint.files[file.path] = { size: file.size, mtimeMs: file.mtimeMs, key, month: monthOf(file.path), summary: result.summary, extractor: EXTRACTOR_VERSION };
131
129
  if (result.catalog?.length) {
132
130
  const hash = createHash("sha1").update(result.catalog.join("\n")).digest("hex").slice(0, 16);
133
131
  result.summary.catalog = hash;
@@ -405,7 +405,7 @@ export class SessionReader {
405
405
  const evals = {};
406
406
  for (const result of this.tracker.results(inScope)) {
407
407
  evals[result.name] = { label: result.label, value: result.value, explanation: result.explanation };
408
- if (inScope) {
408
+ if (result.explanation !== "out_of_scope_pre_3.0") {
409
409
  const t = (startDay.detectors[result.name] ??= { pass: 0, fail: 0, na: 0 });
410
410
  t[result.label] += 1;
411
411
  }
package/dist/index.js 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";
@@ -20,7 +20,30 @@ export function cliPath() {
20
20
  const found = candidates.find((p) => existsSync(p));
21
21
  return found ? { cmd: process.execPath, args: [found] } : undefined;
22
22
  }
23
- const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label"];
23
+ const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label", "run"];
24
+ /** The shipped analysis scripts (`scripts/<name>.mjs`) `/evals run` offers, with what each is for. */
25
+ export const SCRIPTS = {
26
+ freshness: "索引是不是最新的:最後擷取時間、各擷取器版本的摘要數;版本混雜時數字不能看",
27
+ disagree: "某條規則上程式判定和你的標記哪裡不一致,逐段列出,看偏哪一邊(用法:disagree <規則> [--range 天數])",
28
+ "by-version": "某項檢查在各套件版本下的通過率(用法:by-version <檢查> [--pkg 套件])",
29
+ sample: "分層抽樣還沒標過的工作段,給你手動標記(只有 id 與屬性)(用法:sample <數量> [--since 時間] [--seed 數字])",
30
+ "label-import": "把填好的標記表單答案寫進 labels.jsonl(用法:label-import <答案檔> [--sample 樣本檔])",
31
+ "session-shape": "一段工作的結構軌跡:檢查看到的事件順序,不含訊息內容(用法:session-shape <session id>)",
32
+ "change-impact": "某次調整前後的數字(用法:change-impact <時間或 sha> [套件或種類])",
33
+ "skill-days": "某個 skill 每天被載入的工作段數(用法:skill-days <skill> [專案])",
34
+ "package-errors": "某個套件每天的工具出錯數(用法:package-errors <套件> [專案])",
35
+ };
36
+ /** Runs one shipped script with the session's environment; resolves with its exit code and output. */
37
+ function runScript(name, args, env) {
38
+ return new Promise((resolve) => {
39
+ const child = spawn(process.execPath, [fileURLToPath(new URL(`../scripts/${name}.mjs`, import.meta.url)), ...args], { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] });
40
+ let out = "";
41
+ child.stdout?.on("data", (c) => void (out += c.toString()));
42
+ child.stderr?.on("data", (c) => void (out += c.toString()));
43
+ child.on("error", (error) => resolve({ code: -1, out: error.message }));
44
+ child.on("close", (code) => resolve({ code, out: out.trim() }));
45
+ });
46
+ }
24
47
  function parseFlags(args) {
25
48
  const out = { rest: [] };
26
49
  for (let i = 0; i < args.length; i++) {
@@ -102,8 +125,12 @@ export function createEvals(options = {}) {
102
125
  });
103
126
  };
104
127
  pi.registerCommand("evals", {
105
- 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>]",
106
129
  getArgumentCompletions: (prefix) => {
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
+ }
107
134
  const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
108
135
  return items.length ? items : null;
109
136
  },
@@ -149,6 +176,19 @@ export function createEvals(options = {}) {
149
176
  else if (sub === "label") {
150
177
  await labels.command(words.slice(1), ctx);
151
178
  }
179
+ else if (sub === "run") {
180
+ const name = words[1];
181
+ if (!name) {
182
+ ctx.ui.notify(`pi-evals scripts (/evals run <script> [args]):\n${Object.entries(SCRIPTS).map(([n, what]) => `${n} ${what}`).join("\n")}`, "info");
183
+ return;
184
+ }
185
+ if (!Object.hasOwn(SCRIPTS, name)) {
186
+ ctx.ui.notify(`Unknown script "${name}". /evals run lists them.`, "warning");
187
+ return;
188
+ }
189
+ const { code, out } = await runScript(name, words.slice(2), env);
190
+ ctx.ui.notify(out || `${name}: no output (exit ${code})`, code === 0 ? "info" : "warning");
191
+ }
152
192
  else {
153
193
  ctx.ui.notify(`Unknown subcommand "${sub}". Use: ${SUBCOMMANDS.join(", ")}.`, "warning");
154
194
  }
package/dist/meta.js CHANGED
@@ -258,6 +258,17 @@ export const DETECTOR_META = {
258
258
  fail: t("Edits and ends; the guard adds 'no passing run of `npm test`'.", "改檔就結束,收尾檢查加上「沒有 `npm test` 的通過紀錄」。"),
259
259
  },
260
260
  },
261
+ plan_names_graph: {
262
+ introducedIn: { package: "pi-straw-boss", version: "0.101.0" },
263
+ label: t("Plan says how the work splits", "排工作時說清楚怎麼分工"),
264
+ meaning: t("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.", "Straw Boss 的主代理(協調或常駐)把計畫寫成待辦時,有說明這份計畫的分工方式:自己一路做完、分給幾個人平行做再合併,或由主代理派工給工作者。"),
265
+ goodDirection: "higher",
266
+ howComputed: t("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.", "主代理第一次建立待辦後,還沒完成的待辦有標分工方式(待辦的 graph 欄位,或舊版的 metadata.graph)即通過;第一次沒標、但下一次動待辦時補上的也算通過(sb 0.101.0 起會在那次建立待辦時提醒)。沒標就繼續排工作的不通過。不是這類主代理、或從沒排過工作的不算。"),
267
+ example: {
268
+ pass: t("Creates three todos with graph 'fan-out/fan-in', then dispatches them.", "建立三項待辦並標上「fan-out/fan-in」,再派出去。"),
269
+ fail: t("Creates three todos with no graph, gets sb's reminder, and adds a fourth without one.", "建立三項待辦沒標分工方式,收到 sb 提醒後又加了第四項,仍然沒標。"),
270
+ },
271
+ },
261
272
  };
262
273
  export const NOTICE_META = {
263
274
  no_anchor: t("Files changed but no Anchor was stated", "改了檔案但沒說要怎麼驗證"),