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/dist/model.js CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { existsSync } from "node:fs";
6
6
  import { ASK_BUCKETS, emptyDay, mergeDay } from "./aggregate.js";
7
- import { versionAt } from "./changes.js";
7
+ import { atLeast, versionAt } from "./changes.js";
8
8
  import { DETECTORS, ERA_START } from "./detectors.js";
9
9
  import { CHANGE_KIND_META, CLOSE_KIND_META, DETECTOR_META, METRICS, NOTICE_META, STALL_KIND_META } from "./meta.js";
10
10
  import { staticOwner } from "./owners.js";
@@ -108,6 +108,41 @@ export function impactMetrics(rows, ownerOf, pkg) {
108
108
  anchor_before_first_edit: d("anchor_before_first_edit"),
109
109
  check_after_last_edit: d("check_after_last_edit"),
110
110
  todo_evidence: d("todo_evidence"),
111
+ plan_names_graph: d("plan_names_graph"),
112
+ };
113
+ }
114
+ /** Dotted versions in numeric order; anything else (unknown, a sha) after them. */
115
+ const byVersion = (a, b) => {
116
+ const pa = /^\d+(\.\d+)*$/.test(a) ? a.split(".").map(Number) : undefined, pb = /^\d+(\.\d+)*$/.test(b) ? b.split(".").map(Number) : undefined;
117
+ if (!pa || !pb)
118
+ return pa ? -1 : pb ? 1 : a.localeCompare(b);
119
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++)
120
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0))
121
+ return (pa[i] ?? 0) - (pb[i] ?? 0);
122
+ return 0;
123
+ };
124
+ /** 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. */
125
+ export function packageSplit(rows, changes, detector, since) {
126
+ const versions = new Map();
127
+ const sides = { before: { pass: 0, fail: 0 }, after: { pass: 0, fail: 0 } };
128
+ for (const r of rows) {
129
+ const v = r.ev[detector];
130
+ if (v === undefined)
131
+ continue;
132
+ const version = versionAt(changes, since.package, r.s) ?? "unknown";
133
+ const cell = versions.get(version) ?? { pass: 0, fail: 0 };
134
+ cell[v ? "pass" : "fail"] += 1;
135
+ versions.set(version, cell);
136
+ const later = atLeast(version, since.version);
137
+ if (later !== undefined)
138
+ sides[later ? "after" : "before"][v ? "pass" : "fail"] += 1;
139
+ }
140
+ const withRate = (x) => ({ ...x, passRate: rate(x.pass, x.pass + x.fail) });
141
+ return {
142
+ ...since,
143
+ versions: [...versions].sort(([a], [b]) => byVersion(a, b)).map(([version, x]) => ({ version, ...withRate(x) })),
144
+ before: withRate(sides.before),
145
+ after: withRate(sides.after),
111
146
  };
112
147
  }
113
148
  /** Changes from one commit (or one mark) count once. */
@@ -278,6 +313,7 @@ export function buildModel(options) {
278
313
  return { day, pass: x.pass, fail: x.fail };
279
314
  }),
280
315
  byVersion: (versions.get(d.name) ?? []).map((v) => ({ ...v, passRate: rate(v.pass, v.pass + v.fail) })),
316
+ byPackage: DETECTOR_META[d.name]?.introducedIn ? packageSplit(selected, sortedChanges, d.name, DETECTOR_META[d.name].introducedIn) : null,
281
317
  })),
282
318
  notices: total.notices,
283
319
  },
@@ -0,0 +1,120 @@
1
+ /** The planning-rule block's first line (sb `planhint.ts` OPENING). */
2
+ const RULE_OPENING = "sb: your open todos name no graph.";
3
+ const GRAPHS = new Set(["single-loop", "fan-out/fan-in", "orchestrator-worker"]);
4
+ const JUDGED = new Set(["coordinator", "standing"]);
5
+ const MAIN_PROMPT = /You are the main agent of Herdr tab .*?,? of kind ([a-z]+)/;
6
+ const STANDING_PROMPT = /You are the standing main of Herdr tab /;
7
+ const obj = (v) => (v && typeof v === "object" ? v : {});
8
+ /** A legacy `metadata.graph` as mains wrote it, normalised like sb's `graphOf`. */
9
+ export function legacyGraph(v) {
10
+ if (v === "orchestrator-worker")
11
+ return v;
12
+ if (v === "fan-out/fan-in" || v === "fan-out")
13
+ return "fan-out/fan-in";
14
+ if (v === "single" || (typeof v === "string" && v.startsWith("single-loop")))
15
+ return "single-loop";
16
+ return undefined;
17
+ }
18
+ /** A todo's graph: its own field when it is a graph name, else its legacy metadata. */
19
+ export function graphOfTodo(todo) {
20
+ const t = obj(todo);
21
+ if (typeof t.graph === "string" && GRAPHS.has(t.graph))
22
+ return t.graph;
23
+ return legacyGraph(obj(t.metadata).graph);
24
+ }
25
+ /** The plan's open todos: not completed or deleted, and not a train's step. */
26
+ function openOf(tasks) {
27
+ return tasks.map(obj).filter((t) => t.status !== "completed" && t.status !== "deleted" && !obj(t.metadata).sb);
28
+ }
29
+ function text(content) {
30
+ if (typeof content === "string")
31
+ return content;
32
+ return Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "";
33
+ }
34
+ /** A main's kind from the sb role prompt section, if it is a main's prompt. */
35
+ export function sbKindOf(section) {
36
+ return STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1];
37
+ }
38
+ export class PlanGraphTracker {
39
+ kind;
40
+ wasMain = false;
41
+ tasks;
42
+ calls = new Map();
43
+ /** The first plan (a create leaving open todos) named no graph; `rule`: sb's block came with it. */
44
+ missed;
45
+ result;
46
+ feed(entry) {
47
+ if (this.result)
48
+ return;
49
+ const type = entry.type;
50
+ if (type === "custom") {
51
+ const data = obj(entry.data);
52
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks))
53
+ this.tasks = data.tasks;
54
+ else if (entry.customType === "straw-boss" && typeof data.duty === "string" && this.kind)
55
+ this.setKind(data.duty);
56
+ return;
57
+ }
58
+ if (type === "custom_message" && entry.customType === "straw-boss") {
59
+ const briefed = obj(obj(entry.details).briefed);
60
+ const role = briefed.name ?? briefed.role;
61
+ if (typeof role === "string")
62
+ this.setKind(role === "main" && typeof briefed.duty === "string" ? briefed.duty : undefined);
63
+ return;
64
+ }
65
+ if (type !== "message")
66
+ return;
67
+ const message = obj(entry.message);
68
+ if (message.role === "system") {
69
+ const section = obj(message.sections)["straw-boss"];
70
+ if (typeof section !== "string")
71
+ return;
72
+ this.setKind(sbKindOf(section));
73
+ }
74
+ else if (message.role === "assistant" && Array.isArray(message.content)) {
75
+ for (const raw of message.content) {
76
+ const part = obj(raw);
77
+ if (part.type === "toolCall" && part.name === "todo" && typeof part.id === "string")
78
+ this.calls.set(part.id, obj(part.arguments).action === "create");
79
+ }
80
+ }
81
+ else if (message.role === "toolResult" && typeof message.toolCallId === "string" && this.calls.has(message.toolCallId)) {
82
+ const create = this.calls.get(message.toolCallId);
83
+ this.calls.delete(message.toolCallId);
84
+ if (message.isError === true || !this.kind || !JUDGED.has(this.kind))
85
+ return;
86
+ const listed = obj(message.details).tasks;
87
+ this.todoResult(create, Array.isArray(listed) ? listed : (this.tasks ?? []), text(message.content).includes(RULE_OPENING));
88
+ }
89
+ }
90
+ setKind(kind) {
91
+ this.kind = kind;
92
+ if (kind && JUDGED.has(kind))
93
+ this.wasMain = true;
94
+ }
95
+ todoResult(create, tasks, rule) {
96
+ const name = "plan_names_graph";
97
+ const open = openOf(tasks);
98
+ const named = open.some((t) => graphOfTodo(t));
99
+ if (!this.missed) {
100
+ if (!create || !open.length)
101
+ return;
102
+ if (named)
103
+ this.result = { name, label: "pass", explanation: "graph_at_first_create" };
104
+ else
105
+ this.missed = { rule };
106
+ return;
107
+ }
108
+ this.result = named
109
+ ? { name, label: "pass", explanation: this.missed.rule ? "graph_after_rule" : "graph_next_todo_call" }
110
+ : { name, label: "fail", explanation: "kept_planning_without_graph" };
111
+ }
112
+ results() {
113
+ const name = "plan_names_graph";
114
+ if (this.result)
115
+ return this.result;
116
+ if (this.missed)
117
+ return { name, label: "fail", explanation: "plan_without_graph" };
118
+ return { name, label: "na", explanation: this.wasMain ? "no_plan" : "not_sb_main" };
119
+ }
120
+ }
package/dist/query.js CHANGED
@@ -88,6 +88,11 @@ export function query(view, options = {}) {
88
88
  const versions = d.byVersion.filter((v) => v.pass + v.fail > 0).map((v) => `${v.version} ${pct(v.passRate)}`);
89
89
  if (versions.length)
90
90
  body.push(` by anchorloop version: ${versions.slice(-4).join("; ")}`);
91
+ const p = d.byPackage;
92
+ if (p) {
93
+ const byV = p.versions.filter((v) => v.pass + v.fail > 0).map((v) => `${v.version} ${pct(v.passRate)}`);
94
+ body.push(` by ${p.package} version: ${byV.slice(-6).join("; ") || "n/a"}; before ${p.version} ${pct(p.before.passRate)}, from ${p.version} ${pct(p.after.passRate)}`);
95
+ }
91
96
  }
92
97
  body.push(`close-guard reminders: ${Object.entries(m.process.notices).map(([k, v]) => `${k} ${v}`).join(", ") || "none"}`);
93
98
  }
@@ -1,11 +1,23 @@
1
+ import { crosses } from "../changes.js";
1
2
  import { num, pct, usd, words } from "./format.js";
3
+ /** The detector whose package version this pin change brings in (or skips past), with that version. */
4
+ export function introduced(c, m) {
5
+ for (const [name, md] of Object.entries(m.meta.detectors)) {
6
+ if (md.introducedIn && crosses(c, md.introducedIn.package, md.introducedIn.version))
7
+ return { detector: name, version: md.introducedIn.version };
8
+ }
9
+ return undefined;
10
+ }
2
11
  export function readings(c, m, lang) {
3
12
  const L = words(lang), i = c.impact;
4
13
  const has = (k) => i?.before[k]?.value != null && i.after[k]?.value != null;
5
14
  const process = c.package === "pi-anchorloop" && has("anchor_before_first_edit");
6
- const keys = process
7
- ? ["anchor_before_first_edit", "check_after_last_edit"]
8
- : [has("package_error_rate") ? "package_error_rate" : "tool_error_rate", "cost_per_session"];
15
+ const brings = introduced(c, m);
16
+ const keys = brings
17
+ ? [brings.detector, "cost_per_session"]
18
+ : process
19
+ ? ["anchor_before_first_edit", "check_after_last_edit"]
20
+ : [has("package_error_rate") ? "package_error_rate" : "tool_error_rate", "cost_per_session"];
9
21
  return keys.map((key) => {
10
22
  const meta = m.meta.detectors[key] ?? m.meta.metrics[key === "package_error_rate" ? "tool_error_rate" : key];
11
23
  return {
@@ -54,7 +66,8 @@ export function select(m) {
54
66
  const rest = candidates.filter((c) => c !== lead && c.at <= lead.at && (!lead.sha || c.sha !== lead.sha));
55
67
  const second = rest.find((c) => c.impact?.smallSample && c.impact.before.sessions && c.impact.after.sessions) ??
56
68
  rest.find((c) => (c.kind === "pin" || c.kind === "model-routing") && c.impact && !c.impact.incomplete) ?? rest[0];
57
- const highlighted = all.filter((c) => c === lead || c === second);
69
+ // A pin change that brings a detector's package version is always shown: it is what that detector measures.
70
+ const highlighted = all.filter((c) => c === lead || c === second || !!introduced(c, m));
58
71
  return { all, lead, highlighted, folded: all.filter((c) => !highlighted.includes(c)) };
59
72
  }
60
73
  /** Editorial choices shared by the HTML timeline and the compact query. */
@@ -36,7 +36,11 @@ export function sections(m, lang, cards) {
36
36
  const process = section("process", L("Did the agent follow the steps?", "工作有沒有照說好的步驟走?"), L(`Only sessions starting from ${m.process.eraStart} are judged. Earlier work is not a failure.`, `只檢查 ${m.process.eraStart} 起的工作;更早的工作不算失敗。`), lesson(cards.check, L) + `<div class="pair checks">${m.process.detectors.map((d) => {
37
37
  const md = m.meta.detectors[d.name];
38
38
  return `<article class="panel"><p class="eyebrow">${L("Code check", "程式檢查")} / ${L("higher is better", "越高越好")}</p><h3>${esc(md.label[lang])}</h3><p class="big">${pct(d.passRate)} <small>${num(d.pass)} / ${num(d.passRate.n)} ${L("sessions", "段")}</small></p><p>${esc(md.howComputed[lang])}</p><p><b>${L("Pass", "通過")}</b> ${esc(md.example.pass[lang])}<br><b>${L("Fail", "未通過")}</b> ${esc(md.example.fail[lang])}</p>${more(L("By day and version", "查看每日與各版本的通過數"), T([L("Day", "日期"), L("Pass", "通過"), L("Fail", "未通過")], d.perDay.map((r) => [r.day, r.pass, r.fail])) +
39
- T([L("Version", "版本"), L("Pass", "通過"), L("Fail", "未通過")], d.byVersion.map((r) => [r.version, r.pass, r.fail])))}</article>`;
39
+ T([L("Version", "版本"), L("Pass", "通過"), L("Fail", "未通過")], d.byVersion.map((r) => [r.version, r.pass, r.fail])) +
40
+ (d.byPackage
41
+ ? `<p>${esc(L(`By ${d.byPackage.package} version: before ${d.byPackage.version} ${pct(d.byPackage.before.passRate)}, from ${d.byPackage.version} ${pct(d.byPackage.after.passRate)}.`, `依 ${d.byPackage.package} 版本:${d.byPackage.version} 之前 ${pct(d.byPackage.before.passRate)},${d.byPackage.version} 起 ${pct(d.byPackage.after.passRate)}。`))}</p>` +
42
+ T([L(`${d.byPackage.package} version`, `${d.byPackage.package} 版本`), L("Pass", "通過"), L("Fail", "未通過")], d.byPackage.versions.map((r) => [r.version, r.pass, r.fail]))
43
+ : ""))}</article>`;
40
44
  }).join("")}</div>` +
41
45
  more(L("Close-guard reminders", "收尾提醒"), T([L("Kind", "種類"), L("Count", "次數")], entries(m.process.notices).map(([k, n]) => [m.meta.notices[k]?.[lang] ?? k, n]))));
42
46
  const cost = section("cost", L("What the work cost", "工作花了多少錢"), meta.cost.meaning[lang], `<p class="big">${usd(m.cost.total)} <small>USD</small></p><p>${label("cost_per_session")} ${usd(m.cost.perSession.value)}(${num(m.cost.perSession.n)} ${L("sessions", "段")})</p><p>${esc(meta.skill_cost.meaning[lang])}</p>` +
@@ -1,3 +1,4 @@
1
+ import { introduced } from "./findings.js";
1
2
  import { esc, num, words } from "./format.js";
2
3
  const KINDS = ["pin", "model-routing", "rule", "agent-role", "skill", "manual"];
3
4
  /** Dense time slots get a count; every change still has its own mark and title. */
@@ -34,7 +35,7 @@ export function changeStrip(m, all, picks, ids, lang, range) {
34
35
  marks.push(`<text class="slot-count" x="${left + 14}" y="28" text-anchor="middle">×${cells.length}</text>`);
35
36
  }
36
37
  const links = picks.map((c, i) => {
37
- const { px, py, dot } = labeled.get(c), end = px > 700, caption = c.package ? `${c.package} ${c.to ?? ""}` : `${label(c.kind)} · ${c.at.slice(5, 16).replace("T", " ")}`;
38
+ const { px, py, dot } = labeled.get(c), end = px > 700, brings = introduced(c, m), skipped = brings && brings.version !== c.to ? L(` (includes ${brings.version})`, `(含 ${brings.version})`) : "", caption = c.package ? `${c.package} ${c.to ?? ""}${skipped}` : `${label(c.kind)} · ${c.at.slice(5, 16).replace("T", " ")}`;
38
39
  const y = 87 + i * 23;
39
40
  return `<a href="#${ids.get(c)}"><title>${esc(caption)}</title><path class="guide" d="M${px} ${py}V${y - 6}h${end ? -7 : 7}"/>${dot}<text x="${px + (end ? -10 : 10)}" y="${y}" text-anchor="${end ? "end" : "start"}">${esc(Array.from(caption).length > 48 ? Array.from(caption).slice(0, 47).join("") + "…" : caption)}</text></a>`;
40
41
  }).join("");
package/dist/shape.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * A session's structural trace, the events the detectors read, in file order, for error analysis (`session-shape`).
3
+ * It names tools, edit paths (safe names only), check runs by exit code, todo statuses and evidence results, close-guard
4
+ * notice kinds and the sb role; message text, commands and arguments are read only to classify and never printed.
5
+ */
6
+ import { createReadStream } from "node:fs";
7
+ import { createInterface } from "node:readline";
8
+ import { anchorLine, ERA_START, isCheckRun, namesCheck, noticeKind, ProcessTracker } from "./detectors.js";
9
+ import { graphOfTodo, sbKindOf } from "./plan-graph.js";
10
+ import { safeName } from "./schema.js";
11
+ const obj = (v) => (v && typeof v === "object" ? v : {});
12
+ const str = (v) => (typeof v === "string" ? v : undefined);
13
+ const text = (content) => (typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "");
14
+ function counts(list) {
15
+ const by = new Map();
16
+ for (const k of list)
17
+ by.set(k, (by.get(k) ?? 0) + 1);
18
+ return [...by].map(([k, n]) => `${n} ${k}`).join(", ");
19
+ }
20
+ /** Lines of the trace, then one line per detector result. */
21
+ export async function sessionShape(file) {
22
+ const out = [];
23
+ const tracker = new ProcessTracker();
24
+ const calls = new Map();
25
+ let start = "";
26
+ let seq = 0;
27
+ let firstUser = true;
28
+ let lastTodo = "";
29
+ const at = (ts) => {
30
+ const t = Date.parse(str(ts) ?? "");
31
+ if (!start || !Number.isFinite(t))
32
+ return "";
33
+ const s = Math.max(0, Math.round((t - Date.parse(start)) / 1000));
34
+ return ` +${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
35
+ };
36
+ const push = (entry, what) => out.push(`#${seq}${at(entry.timestamp)} ${what}`);
37
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Number.POSITIVE_INFINITY });
38
+ for await (const line of lines) {
39
+ if (!line || line.charCodeAt(0) !== 123)
40
+ continue;
41
+ let entry;
42
+ try {
43
+ entry = JSON.parse(line);
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ seq += 1;
49
+ tracker.feed(entry);
50
+ const type = entry.type;
51
+ if (type === "session") {
52
+ start = str(entry.timestamp) ?? "";
53
+ continue;
54
+ }
55
+ if (!start && str(entry.timestamp))
56
+ start = str(entry.timestamp);
57
+ if (type === "compaction")
58
+ push(entry, "compaction");
59
+ else if (type === "custom") {
60
+ const data = obj(entry.data);
61
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks)) {
62
+ const tasks = data.tasks.map(obj);
63
+ const ev = tasks.flatMap((t) => (Array.isArray(t.evidence) ? t.evidence.map((e) => `evidence ${obj(e).result === "pass" ? "pass" : "fail"}`) : []));
64
+ const graph = tasks.some((t) => graphOfTodo(t)) ? "; graph named" : "";
65
+ const now = `todo list: ${counts(tasks.map((t) => safeName(t.status)))}${ev.length ? `; ${counts(ev)}` : ""}${graph}`;
66
+ if (now !== lastTodo)
67
+ push(entry, now);
68
+ lastTodo = now;
69
+ }
70
+ else if (entry.customType === "straw-boss" && typeof data.duty === "string")
71
+ push(entry, `sb kind ${safeName(data.duty)} (kind entry)`);
72
+ }
73
+ else if (type === "custom_message") {
74
+ const details = obj(entry.details);
75
+ if (entry.customType === "anchorloop-close-guard")
76
+ push(entry, `close-guard ${noticeKind(entry.content)}`);
77
+ else if (entry.customType === "pi-loop-monitor") {
78
+ const o = obj(details.monitorOutcome);
79
+ if (details.deliveryGroup === "monitor-terminal")
80
+ push(entry, `monitor ${safeName(str(o.monitorId) ?? "?")} ended ${typeof o.exitCode === "number" ? `exit=${o.exitCode}` : safeName(o.status)}`);
81
+ }
82
+ else if (entry.customType === "straw-boss" && details.briefed) {
83
+ const b = obj(details.briefed);
84
+ push(entry, `sb role ${safeName(b.name ?? b.role)} ${b.duty ? safeName(b.duty) : ""}`.trim());
85
+ }
86
+ else if (entry.customType === "subagent_result")
87
+ push(entry, "subagent result");
88
+ }
89
+ else if (type === "message") {
90
+ const message = obj(entry.message);
91
+ if (message.role === "system") {
92
+ const section = obj(message.sections)["straw-boss"];
93
+ if (typeof section === "string")
94
+ push(entry, `sb kind ${sbKindOf(section) ?? "none (not a main)"} (role prompt)`);
95
+ }
96
+ else if (message.role === "user") {
97
+ const words = text(message.content);
98
+ push(entry, firstUser ? `user brief${namesCheck(words) ? " (names a check)" : ""}` : "user");
99
+ firstUser = false;
100
+ }
101
+ else if (message.role === "assistant" && Array.isArray(message.content)) {
102
+ for (const raw of message.content) {
103
+ const part = obj(raw);
104
+ if (part.type === "text" && typeof part.text === "string" && anchorLine(part.text) !== undefined)
105
+ push(entry, "anchor stated");
106
+ if (part.type !== "toolCall" || typeof part.id !== "string")
107
+ continue;
108
+ const args = obj(part.arguments);
109
+ const name = safeName(part.name);
110
+ const command = str(args.command);
111
+ const items = [args, ...(Array.isArray(args.tasks) ? args.tasks.map(obj) : [])];
112
+ const evidence = items.flatMap((i) => (Array.isArray(i.evidence) ? i.evidence.map((e) => (obj(e).result === "pass" ? "pass" : "fail")) : []));
113
+ calls.set(part.id, {
114
+ name,
115
+ path: str(args.path),
116
+ check: command !== undefined && isCheckRun(command),
117
+ evidence: evidence.length ? counts(evidence.map((e) => `evidence ${e}`)) : undefined,
118
+ action: str(args.action) ? safeName(args.action) : undefined,
119
+ role: name === "subagent" ? safeName(str(args.agent) ?? "default") : undefined,
120
+ });
121
+ if (name === "todo" && items.some((i) => (typeof i.anchor === "string" && i.anchor.trim()) || obj(i.metadata).anchor))
122
+ push(entry, "todo anchor set");
123
+ }
124
+ }
125
+ else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
126
+ const call = calls.get(message.toolCallId);
127
+ if (!call)
128
+ continue;
129
+ calls.delete(message.toolCallId);
130
+ const code = obj(message.structuredContent).exit_code;
131
+ const ok = typeof code === "number" ? code === 0 : message.isError !== true;
132
+ const status = typeof code === "number" ? `exit=${code}` : ok ? "ok" : "error";
133
+ if (call.name === "edit" || call.name === "write")
134
+ push(entry, `${call.name} ${call.path ? safeName(call.path) : "?"} ${ok ? "ok" : "error"}`);
135
+ else if (call.name === "bash" || call.name === "MonitorCreate")
136
+ push(entry, `${call.name === "bash" ? "bash" : "monitor start"}${call.check ? " check" : ""} ${status}`);
137
+ else if (call.name === "todo")
138
+ push(entry, `todo ${call.action ?? "?"} ${ok ? "ok" : "error"}${call.evidence ? `; ${call.evidence}` : ""}`);
139
+ else if (call.name === "subagent")
140
+ push(entry, `subagent ${call.role} ${ok ? "launched" : "error"}`);
141
+ else
142
+ push(entry, `${call.name} ${ok ? "ok" : "error"}`);
143
+ }
144
+ }
145
+ }
146
+ for (const r of tracker.results(start >= ERA_START))
147
+ out.push(`${r.name}: ${r.label} (${r.explanation})`);
148
+ return out;
149
+ }
package/docs/design.md CHANGED
@@ -45,7 +45,7 @@ The privacy test was written first and failed on exactly that: a secret placed i
45
45
 
46
46
  The session files hold almost everything (instrumentation §5): tool calls with `durationMs` (from October on; older calls use the time between call and result), the ask-user results in both the current and the retired `pi-ask-user` shapes, the skill catalog pi offered (the system message's `skills` section), monitor endings delivered as `pi-loop-monitor` messages, and close-guard notices.
47
47
  Extraction streams each file line by line on a pool of worker threads and writes one record file per session file atomically.
48
- It is incremental by path, size and modification time, so a later extract reads only active sessions; an extractor version in the checkpoint forces a full re-read when extraction changes.
48
+ It is incremental by path, size and modification time, so a later extract reads only active sessions; each file's summary carries the extractor version that wrote it, and a summary from another version is read again. The stamp is per file because an extract stopped after a version bump (0.6.0's first run was killed by a 900 s timeout) saved a checkpoint marked with the new version while most summaries were still old, and the next run skipped them.
49
49
  A subagent session is linked to its parent three ways: the parent's `subagent` result (`details.id`, the child's logical id), `~/.pi/agent/dispatch-ledger/<parent>.json`, and the artifacts path in the child's brief.
50
50
  Live records and back-fill meet by session id: back-fill counts win, and live adds monitor lifecycles and answer sources.
51
51
 
@@ -56,18 +56,20 @@ It appends to the state dir, never to the session file, and a failed write warns
56
56
 
57
57
  ### Process detectors
58
58
 
59
- Four session-scoped checks, each a `gen_ai.evaluation.result` with `annotator_kind` CODE.
59
+ Five session-scoped checks, each a `gen_ai.evaluation.result` with `annotator_kind` CODE.
60
60
  Anchor and change reading is ported from anchorloop's close guard (`pi/close-guard.ts` `read()`, 3.3.0), whose repository rules keep the guard small, so the evals live outside it (inventory §1).
61
61
 
62
62
  - `anchor_before_first_edit`: before the first successful `write` or `edit`, the agent states the check (`anchor_first`: an `Anchor:` line, a labelled `Gates:`, `Checks:`, `Verify:` or `驗證:` line, a todo anchor, or a todo's sb check spec), its brief does (`anchor_in_brief`: such a line, or a check command it names), or the first change is a test file (`test_first`, red first). The brief counts because anchorloop has the coordinator put the unit's anchor there. 0.5.0 read only the `Anchor:` line and todo anchor and failed a brief's anchor as `anchor_only_in_brief`; 30 human labels (2026-11-26) passed all of these shapes.
63
63
  - `check_after_last_edit`: after the last change, every command of the anchor has a passing run (bash, or a monitor by its exit code; `anchor_green`), the agent recorded passing todo evidence (`evidence_after_change`), or, when no anchor command ran and failed, the latest test, build, lint or type-check run passed (`check_run_after_change`). A check run is a segment of the command that starts with a known runner (`npm test`, `vitest`, `tsc`, `pytest`, `dotnet test` and the like) or a script named for checking (`check-*.py`, `gates.sh`, `measure.mjs`, `tests/*.py`); a command that only mentions tests (`rg test`, `git commit`) is not one. Edits to Markdown or text files do not move the last change, so a report or changelog written after the check does not undo it; a session that changed only such files is `prose_only` unless a check ran. With no anchor and no check it fails as `no_check_after_change`.
64
64
  - `todo_evidence`: completed tasks in the final todo list carry evidence; the value is the share that do.
65
65
  - `close_guard_quiet`: an editing session got no close-guard reminder about a missing or failing check (an evidence hand-off reminder does not count).
66
+ - `plan_names_graph`: a Straw Boss main of kind coordinator or standing names its plan's graph when it plans. The kind comes from the sb role prompt (system section `straw-boss`: "of kind <kind>", or "the standing main"), role steers (`details.briefed`), and kind entries (`data.duty`); an integrator, a member or a session with no sb role is `not_sb_main`. The plan is the open todos (not completed or deleted, not a train's `metadata.sb` step) a `todo` result lists. It passes when the first create that leaves open todos has one with a graph (the todo's `graph`, a name of pi-todo-ledger 0.4.0's three, else a legacy `metadata.graph` normalised as sb's `graphOf`; `graph_at_first_create`), or when the next todo call's open todos have one (`graph_after_rule` when sb's planning-rule block came on the create, sb 0.101.0 and later, else `graph_next_todo_call`). It fails when the next todo call still names none (`kept_planning_without_graph`) or there is none (`plan_without_graph`).
66
67
 
67
- Only sessions that started after anchorloop 3.0.0 reached this setup are judged: the pin commit in weihung-basic-agent, 2026-11-23T10:51:07Z. Older sessions are out of scope rather than failing (inventory, Gotchas), and they are left out of the "not applicable" counts.
68
+ Only sessions that started after anchorloop 3.0.0 reached this setup are judged by the four anchorloop checks (`plan_names_graph` is judged in every session: sb mains live for weeks): the pin commit in weihung-basic-agent, 2026-11-23T10:51:07Z. Older sessions are out of scope rather than failing (inventory, Gotchas), and they are left out of the "not applicable" counts.
68
69
  Like the guard, an edit made through bash is not seen as a change.
69
70
  These are process checks on observable events, which suits a process skill whose path is the product (research §1); they say how often the rules were followed, not whether the work was right.
70
71
  A session's anchorloop version is the newest pin in the change timeline at or before the session's start, so a pin at 16:46 splits that day's sessions at 16:46.
72
+ A detector that measures a package version's arrival names it in its metadata (`introducedIn`; `plan_names_graph`: pi-straw-boss 0.101.0). The process view and the report then also split its results by that package's version at each session's start, and before and from that version; the pin change that brings the version, or skips past it (0.100.2 → 0.102.0), is always highlighted on the change strip and captioned with the version it includes. A session picks up a new package version only after `/reload` or a restart, and it is split by its start, so a long-lived main reloaded after the pin still counts on the earlier side; read the "from" side as fresh sessions only.
71
73
 
72
74
  ### Change impact
73
75
 
package/docs/schema.md CHANGED
@@ -49,8 +49,9 @@ Back-fill rebuilds each session's items from its `todo/v1` snapshots, diffed alo
49
49
  | `check_after_last_edit` | `anchor_green`, `evidence_after_change`, `check_run_after_change` | `no_passing_run_after_change`, `no_check_after_change` | `no_edit`, `prose_only`, `anchor_without_command` |
50
50
  | `todo_evidence` | `all_evidenced` | `completed_without_evidence` (value = share with evidence) | `no_completed_task` |
51
51
  | `close_guard_quiet` | `no_notice` | the commonest notice kind | `no_edit` |
52
+ | `plan_names_graph` | `graph_at_first_create`, `graph_after_rule`, `graph_next_todo_call` | `kept_planning_without_graph`, `plan_without_graph` | `not_sb_main`, `no_plan` |
52
53
 
53
- Sessions that started before 2026-11-23T10:51:07Z (the anchorloop 3.0.0 pin) get `na` with `out_of_scope_pre_3.0` for all four.
54
+ Sessions that started before 2026-11-23T10:51:07Z (the anchorloop 3.0.0 pin) get `na` with `out_of_scope_pre_3.0` for the four anchorloop checks; `plan_names_graph` is judged in every session, since sb mains live for weeks.
54
55
 
55
56
  ## Labels
56
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-evals",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Usage and process records for pi: how skills, packages, ask-user, monitors and subagents are used, back-filled from past sessions, with a static report and an evals_query tool",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // A detector's pass rate per package version at session start.
4
+ const usage = 'node by-version.mjs DETECTOR [--pkg PACKAGE]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--pkg']);
7
+ if (f.rest.length !== 1) throw new QueryError(usage);
8
+ return analysis.byVersion(layout(), f.rest[0], f.pkg);
9
+ });
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // Where the code and the user's labels disagree on one rule, session by session.
4
+ const usage = 'node disagree.mjs RULE [--range DAYS]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--range']);
7
+ if (f.rest.length !== 1 || (f.range !== undefined && !/^\d+$/.test(f.range))) throw new QueryError(usage);
8
+ return analysis.disagree(layout(), f.rest[0], f.range === undefined ? undefined : Number(f.range));
9
+ });
@@ -0,0 +1,7 @@
1
+ import { analysis, layout, run } from './query-lib.mjs';
2
+
3
+ // Is the index current? Exit 1 when summaries come from more than one extractor version.
4
+ const usage = 'node freshness.mjs';
5
+ const check = args => { if (args.length) throw new Error(usage); return analysis.freshness(layout()); };
6
+ check.noArgs = true;
7
+ run(usage, check);
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // Submitted label-form answers into labels.jsonl, as after-the-fact human labels.
4
+ const usage = 'node label-import.mjs ANSWER_FILE [--sample SAMPLE_FILE]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--sample']);
7
+ if (f.rest.length !== 1) throw new QueryError(usage);
8
+ return analysis.labelImport(layout(), f.rest[0], f.sample);
9
+ });
@@ -1,27 +1,57 @@
1
- import { readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
3
  // Node strips types in checkouts but forbids it under node_modules. npm ships dist there.
4
4
  const installed = new URL(import.meta.url).pathname.split('/').includes('node_modules');
5
5
  const load = name => import(installed ? `../dist/${name}.js` : `../src/${name}.ts`);
6
- const [{ layout }, { loadIndex }, { recentDays, packageCounts }, { safeName }] = await Promise.all(
7
- ['paths', 'build', 'trends', 'schema'].map(load),
6
+ const [{ layout }, { loadIndex }, { recentDays, packageCounts }, { safeName }, analysis, shape] = await Promise.all(
7
+ ['paths', 'build', 'trends', 'schema', 'analysis', 'shape'].map(load),
8
8
  );
9
- export { packageCounts, safeName };
9
+ export { analysis, packageCounts, safeName, shape, layout };
10
10
 
11
- export function run(usage, fn) {
11
+ /** Bytes a script prints before it writes the whole output to a file under `<state>/runs` and prints the start and the path. */
12
+ const max = () => Number(process.env.PI_EVALS_SCRIPT_MAX) > 0 ? Number(process.env.PI_EVALS_SCRIPT_MAX) : 2000;
13
+
14
+ function emit(lines) {
15
+ const text = lines.join('\n') + '\n';
16
+ if (Buffer.byteLength(text) <= max()) return process.stdout.write(text);
17
+ const dir = join(layout().state, 'runs');
18
+ mkdirSync(dir, { recursive: true });
19
+ const file = join(dir, `${basename(process.argv[1], '.mjs')}-${new Date().toISOString().replace(/[:.]/g, '-')}.txt`);
20
+ writeFileSync(file, text);
21
+ const tail = `… ${lines.length} lines; full output: ${file}\n`;
22
+ let head = '';
23
+ for (const line of lines) {
24
+ if (Buffer.byteLength(head + line + '\n' + tail) > max()) break;
25
+ head += line + '\n';
26
+ }
27
+ process.stdout.write(head + tail);
28
+ }
29
+
30
+ /** `fn(args)` returns lines, or `{ lines, status }`; it may be async. */
31
+ export async function run(usage, fn) {
12
32
  try {
13
33
  const args = process.argv.slice(2);
14
- if (!args.length || args.some(x => !x || safeName(x) !== x)) throw new Error(usage);
15
- const text = fn(args).join('\n') + '\n';
16
- if (Buffer.byteLength(text) > 2000) throw new Error('Result exceeds the output limit.');
17
- process.stdout.write(text);
34
+ if (!args.length && fn.length && !fn.noArgs || args.some(x => !x || safeName(x) !== x)) throw new QueryError(usage);
35
+ const out = await fn(args);
36
+ const { lines, status } = Array.isArray(out) ? { lines: out, status: 0 } : out;
37
+ emit(lines);
38
+ process.exitCode = status ?? 0;
18
39
  } catch (error) {
19
40
  // Never echo unknown arguments, local paths or JSON parse excerpts.
20
- console.error(error instanceof QueryError ? error.message : `Cannot read query. ${usage}`);
41
+ console.error(error instanceof QueryError || error instanceof analysis.AnalysisError ? error.message : `Cannot read query. ${usage}`);
21
42
  process.exitCode = 1;
22
43
  }
23
44
  }
24
45
  export class QueryError extends Error {}
46
+ /** `--name value` from args; the rest positional. */
47
+ export function flags(args, names) {
48
+ const out = { rest: [] };
49
+ for (let i = 0; i < args.length; i++) {
50
+ if (names.includes(args[i])) out[args[i].slice(2)] = args[++i];
51
+ else out.rest.push(args[i]);
52
+ }
53
+ return out;
54
+ }
25
55
  export function daily(project) {
26
56
  const index = loadIndex(layout());
27
57
  if (!index) throw new QueryError('No index. Run /evals extract first.');
@@ -0,0 +1,9 @@
1
+ import { analysis, flags, layout, QueryError, run } from './query-lib.mjs';
2
+
3
+ // A stratified sample of sessions to label by hand: ids and metadata only.
4
+ const usage = 'node sample.mjs N [--since ISO] [--seed INT]';
5
+ run(usage, args => {
6
+ const f = flags(args, ['--since', '--seed']);
7
+ if (f.rest.length !== 1 || !/^\d+$/.test(f.rest[0]) || (f.seed !== undefined && !/^\d+$/.test(f.seed))) throw new QueryError(usage);
8
+ return analysis.sample(layout(), Number(f.rest[0]), { since: f.since, seed: f.seed === undefined ? undefined : Number(f.seed) });
9
+ });
@@ -0,0 +1,8 @@
1
+ import { analysis, layout, QueryError, run, shape } from './query-lib.mjs';
2
+
3
+ // The ordered events the detectors see in one session, without message text.
4
+ const usage = 'node session-shape.mjs SESSION_ID';
5
+ run(usage, async args => {
6
+ if (args.length !== 1) throw new QueryError(usage);
7
+ return shape.sessionShape(analysis.sessionFile(layout(), args[0]));
8
+ });