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.
@@ -0,0 +1,122 @@
1
+ /**
2
+ * `plan_names_graph`: whether a Straw Boss main of kind coordinator or standing names its plan's graph when it plans.
3
+ *
4
+ * The graph is a todo's own `graph` (pi-todo-ledger 0.4.0: `single-loop`, `fan-out/fan-in`, `orchestrator-worker`), else a
5
+ * legacy `metadata.graph`, read as pi-straw-boss reads it (`items.ts` `todosOf`, `duty.ts` `graphOf`, MIT, Copyright (c) 2026
6
+ * Wei Hung, sb 0.103.0). From sb 0.101.0 a main whose `todo` create leaves open todos with no graph gets planning.md §1-§2
7
+ * on that result (`planhint.ts`); the next todo call shows whether the main took it. A train's steps (`metadata.sb`) are not
8
+ * the plan. The main's kind comes from its role prompt (system section or a role steer) and its kind entries.
9
+ */
10
+ import type { DetectorResult } from "./detectors.ts";
11
+
12
+ /** The planning-rule block's first line (sb `planhint.ts` OPENING). */
13
+ const RULE_OPENING = "sb: your open todos name no graph.";
14
+ const GRAPHS = new Set(["single-loop", "fan-out/fan-in", "orchestrator-worker"]);
15
+ const JUDGED = new Set(["coordinator", "standing"]);
16
+ const MAIN_PROMPT = /You are the main agent of Herdr tab .*?,? of kind ([a-z]+)/;
17
+ const STANDING_PROMPT = /You are the standing main of Herdr tab /;
18
+
19
+ type Obj = Record<string, unknown>;
20
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
21
+
22
+ /** A legacy `metadata.graph` as mains wrote it, normalised like sb's `graphOf`. */
23
+ export function legacyGraph(v: unknown): string | undefined {
24
+ if (v === "orchestrator-worker") return v;
25
+ if (v === "fan-out/fan-in" || v === "fan-out") return "fan-out/fan-in";
26
+ if (v === "single" || (typeof v === "string" && v.startsWith("single-loop"))) return "single-loop";
27
+ return undefined;
28
+ }
29
+
30
+ /** A todo's graph: its own field when it is a graph name, else its legacy metadata. */
31
+ export function graphOfTodo(todo: unknown): string | undefined {
32
+ const t = obj(todo);
33
+ if (typeof t.graph === "string" && GRAPHS.has(t.graph)) return t.graph;
34
+ return legacyGraph(obj(t.metadata).graph);
35
+ }
36
+
37
+ /** The plan's open todos: not completed or deleted, and not a train's step. */
38
+ function openOf(tasks: unknown[]): Obj[] {
39
+ return tasks.map(obj).filter((t) => t.status !== "completed" && t.status !== "deleted" && !obj(t.metadata).sb);
40
+ }
41
+
42
+ function text(content: unknown): string {
43
+ if (typeof content === "string") return content;
44
+ return Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "";
45
+ }
46
+
47
+ /** A main's kind from the sb role prompt section, if it is a main's prompt. */
48
+ export function sbKindOf(section: string): string | undefined {
49
+ return STANDING_PROMPT.test(section) ? "standing" : MAIN_PROMPT.exec(section)?.[1];
50
+ }
51
+
52
+ export class PlanGraphTracker {
53
+ private kind: string | undefined;
54
+ private wasMain = false;
55
+ private tasks: unknown[] | undefined;
56
+ private calls = new Map<string, boolean>();
57
+ /** The first plan (a create leaving open todos) named no graph; `rule`: sb's block came with it. */
58
+ private missed: { rule: boolean } | undefined;
59
+ private result: DetectorResult | undefined;
60
+
61
+ feed(entry: Obj): void {
62
+ if (this.result) return;
63
+ const type = entry.type;
64
+ if (type === "custom") {
65
+ const data = obj(entry.data);
66
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks)) this.tasks = data.tasks;
67
+ else if (entry.customType === "straw-boss" && typeof data.duty === "string" && this.kind) this.setKind(data.duty);
68
+ return;
69
+ }
70
+ if (type === "custom_message" && entry.customType === "straw-boss") {
71
+ const briefed = obj(obj(entry.details).briefed);
72
+ const role = briefed.name ?? briefed.role;
73
+ if (typeof role === "string") this.setKind(role === "main" && typeof briefed.duty === "string" ? briefed.duty : undefined);
74
+ return;
75
+ }
76
+ if (type !== "message") return;
77
+ const message = obj(entry.message);
78
+ if (message.role === "system") {
79
+ const section = obj(message.sections)["straw-boss"];
80
+ if (typeof section !== "string") return;
81
+ this.setKind(sbKindOf(section));
82
+ } else if (message.role === "assistant" && Array.isArray(message.content)) {
83
+ for (const raw of message.content) {
84
+ const part = obj(raw);
85
+ if (part.type === "toolCall" && part.name === "todo" && typeof part.id === "string") this.calls.set(part.id, obj(part.arguments).action === "create");
86
+ }
87
+ } else if (message.role === "toolResult" && typeof message.toolCallId === "string" && this.calls.has(message.toolCallId)) {
88
+ const create = this.calls.get(message.toolCallId)!;
89
+ this.calls.delete(message.toolCallId);
90
+ if (message.isError === true || !this.kind || !JUDGED.has(this.kind)) return;
91
+ const listed = obj(message.details).tasks;
92
+ this.todoResult(create, Array.isArray(listed) ? listed : (this.tasks ?? []), text(message.content).includes(RULE_OPENING));
93
+ }
94
+ }
95
+
96
+ private setKind(kind: string | undefined) {
97
+ this.kind = kind;
98
+ if (kind && JUDGED.has(kind)) this.wasMain = true;
99
+ }
100
+
101
+ private todoResult(create: boolean, tasks: unknown[], rule: boolean) {
102
+ const name = "plan_names_graph";
103
+ const open = openOf(tasks);
104
+ const named = open.some((t) => graphOfTodo(t));
105
+ if (!this.missed) {
106
+ if (!create || !open.length) return;
107
+ if (named) this.result = { name, label: "pass", explanation: "graph_at_first_create" };
108
+ else this.missed = { rule };
109
+ return;
110
+ }
111
+ this.result = named
112
+ ? { name, label: "pass", explanation: this.missed.rule ? "graph_after_rule" : "graph_next_todo_call" }
113
+ : { name, label: "fail", explanation: "kept_planning_without_graph" };
114
+ }
115
+
116
+ results(): DetectorResult {
117
+ const name = "plan_names_graph";
118
+ if (this.result) return this.result;
119
+ if (this.missed) return { name, label: "fail", explanation: "plan_without_graph" };
120
+ return { name, label: "na", explanation: this.wasMain ? "no_plan" : "not_sb_main" };
121
+ }
122
+ }
package/src/query.ts CHANGED
@@ -81,6 +81,11 @@ export function query(view: View, options: { since?: string; days?: number; proj
81
81
  body.push(`${d.name} (${label}): ${pct(d.passRate)}, not applicable ${d.na}`);
82
82
  const versions = d.byVersion.filter((v) => v.pass + v.fail > 0).map((v) => `${v.version} ${pct(v.passRate)}`);
83
83
  if (versions.length) body.push(` by anchorloop version: ${versions.slice(-4).join("; ")}`);
84
+ const p = d.byPackage;
85
+ if (p) {
86
+ const byV = p.versions.filter((v) => v.pass + v.fail > 0).map((v) => `${v.version} ${pct(v.passRate)}`);
87
+ 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)}`);
88
+ }
84
89
  }
85
90
  body.push(`close-guard reminders: ${Object.entries(m.process.notices).map(([k, v]) => `${k} ${v}`).join(", ") || "none"}`);
86
91
  } else if (view === "cost") {
@@ -1,7 +1,16 @@
1
+ import { crosses } from "../changes.ts";
1
2
  import type { Rate, ReportModel } from "../model.ts";
2
3
  import { type Change, type Lang, num, pct, usd, type Words, words } from "./format.ts";
3
4
 
4
- type Key = "anchor_before_first_edit" | "check_after_last_edit" | "package_error_rate" | "tool_error_rate" | "cost_per_session";
5
+ type Key = "anchor_before_first_edit" | "check_after_last_edit" | "plan_names_graph" | "package_error_rate" | "tool_error_rate" | "cost_per_session";
6
+
7
+ /** The detector whose package version this pin change brings in (or skips past), with that version. */
8
+ export function introduced(c: Pick<Change, "kind" | "package" | "from" | "to">, m: Pick<ReportModel, "meta">): { detector: Key; version: string } | undefined {
9
+ for (const [name, md] of Object.entries(m.meta.detectors)) {
10
+ if (md.introducedIn && crosses(c, md.introducedIn.package, md.introducedIn.version)) return { detector: name as Key, version: md.introducedIn.version };
11
+ }
12
+ return undefined;
13
+ }
5
14
  export interface Reading {
6
15
  key: Key;
7
16
  label: string;
@@ -14,7 +23,10 @@ export function readings(c: Change, m: ReportModel, lang: Lang): Reading[] {
14
23
  const L = words(lang), i = c.impact;
15
24
  const has = (k: Key) => i?.before[k]?.value != null && i.after[k]?.value != null;
16
25
  const process = c.package === "pi-anchorloop" && has("anchor_before_first_edit");
17
- const keys: Key[] = process
26
+ const brings = introduced(c, m);
27
+ const keys: Key[] = brings
28
+ ? [brings.detector, "cost_per_session"]
29
+ : process
18
30
  ? ["anchor_before_first_edit", "check_after_last_edit"]
19
31
  : [has("package_error_rate") ? "package_error_rate" : "tool_error_rate", "cost_per_session"];
20
32
  return keys.map((key) => {
@@ -64,7 +76,8 @@ export function select(m: ReportModel) {
64
76
  const rest = candidates.filter((c) => c !== lead && c.at <= lead.at && (!lead.sha || c.sha !== lead.sha));
65
77
  const second = rest.find((c) => c.impact?.smallSample && c.impact.before.sessions && c.impact.after.sessions) ??
66
78
  rest.find((c) => (c.kind === "pin" || c.kind === "model-routing") && c.impact && !c.impact.incomplete) ?? rest[0];
67
- const highlighted = all.filter((c) => c === lead || c === second);
79
+ // A pin change that brings a detector's package version is always shown: it is what that detector measures.
80
+ const highlighted = all.filter((c) => c === lead || c === second || !!introduced(c, m));
68
81
  return { all, lead, highlighted, folded: all.filter((c) => !highlighted.includes(c)) };
69
82
  }
70
83
  /** Editorial choices shared by the HTML timeline and the compact query. */
@@ -113,7 +113,11 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
113
113
  more(
114
114
  L("By day and version", "查看每日與各版本的通過數"),
115
115
  T([L("Day", "日期"), L("Pass", "通過"), L("Fail", "未通過")], d.perDay.map((r) => [r.day, r.pass, r.fail])) +
116
- T([L("Version", "版本"), L("Pass", "通過"), L("Fail", "未通過")], d.byVersion.map((r) => [r.version, r.pass, r.fail])),
116
+ T([L("Version", "版本"), L("Pass", "通過"), L("Fail", "未通過")], d.byVersion.map((r) => [r.version, r.pass, r.fail])) +
117
+ (d.byPackage
118
+ ? `<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>` +
119
+ T([L(`${d.byPackage.package} version`, `${d.byPackage.package} 版本`), L("Pass", "通過"), L("Fail", "未通過")], d.byPackage.versions.map((r) => [r.version, r.pass, r.fail]))
120
+ : ""),
117
121
  )
118
122
  }</article>`;
119
123
  }).join("")
@@ -1,5 +1,6 @@
1
1
  import type { ReportModel } from "../model.ts";
2
2
  import type { Preset } from "../ranges.ts";
3
+ import { introduced } from "./findings.ts";
3
4
  import { type Change, esc, type Lang, num, words } from "./format.ts";
4
5
 
5
6
  const KINDS = ["pin", "model-routing", "rule", "agent-role", "skill", "manual"] as const;
@@ -32,7 +33,8 @@ export function changeStrip(m: ReportModel, all: Change[], picks: Change[], ids:
32
33
  if (cells.length > 5) marks.push(`<text class="slot-count" x="${left + 14}" y="28" text-anchor="middle">×${cells.length}</text>`);
33
34
  }
34
35
  const links = picks.map((c,i) => {
35
- 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", " ")}`;
36
+ 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})`) : "",
37
+ caption = c.package ? `${c.package} ${c.to ?? ""}${skipped}` : `${label(c.kind)} · ${c.at.slice(5,16).replace("T", " ")}`;
36
38
  const y = 87 + i * 23;
37
39
  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>`;
38
40
  }).join("");
package/src/shape.ts ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * A session's structural trace, the events the detectors read, in file order, for error analysis (`session-shape`).
3
+ * It names tools, edit paths (safe names only), check runs by exit code, todo statuses and evidence results, close-guard
4
+ * notice kinds and the sb role; message text, commands and arguments are read only to classify and never printed.
5
+ */
6
+ import { createReadStream } from "node:fs";
7
+ import { createInterface } from "node:readline";
8
+ import { anchorLine, ERA_START, isCheckRun, namesCheck, noticeKind, ProcessTracker } from "./detectors.ts";
9
+ import { graphOfTodo, sbKindOf } from "./plan-graph.ts";
10
+ import { safeName } from "./schema.ts";
11
+
12
+ type Obj = Record<string, unknown>;
13
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
14
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
15
+ const text = (content: unknown) => (typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (obj(p).type === "text" ? String(obj(p).text ?? "") : "")).join("\n") : "");
16
+
17
+ function counts(list: string[]): string {
18
+ const by = new Map<string, number>();
19
+ for (const k of list) by.set(k, (by.get(k) ?? 0) + 1);
20
+ return [...by].map(([k, n]) => `${n} ${k}`).join(", ");
21
+ }
22
+
23
+ /** Lines of the trace, then one line per detector result. */
24
+ export async function sessionShape(file: string): Promise<string[]> {
25
+ const out: string[] = [];
26
+ const tracker = new ProcessTracker();
27
+ const calls = new Map<string, { name: string; path?: string; check?: boolean; evidence?: string; action?: string; role?: string }>();
28
+ let start = "";
29
+ let seq = 0;
30
+ let firstUser = true;
31
+ let lastTodo = "";
32
+ const at = (ts: unknown) => {
33
+ const t = Date.parse(str(ts) ?? "");
34
+ if (!start || !Number.isFinite(t)) return "";
35
+ const s = Math.max(0, Math.round((t - Date.parse(start)) / 1000));
36
+ return ` +${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
37
+ };
38
+ const push = (entry: Obj, what: string) => out.push(`#${seq}${at(entry.timestamp)} ${what}`);
39
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Number.POSITIVE_INFINITY });
40
+ for await (const line of lines) {
41
+ if (!line || line.charCodeAt(0) !== 123) continue;
42
+ let entry: Obj;
43
+ try {
44
+ entry = JSON.parse(line) as Obj;
45
+ } catch {
46
+ continue;
47
+ }
48
+ seq += 1;
49
+ tracker.feed(entry);
50
+ const type = entry.type;
51
+ if (type === "session") {
52
+ start = str(entry.timestamp) ?? "";
53
+ continue;
54
+ }
55
+ if (!start && str(entry.timestamp)) start = str(entry.timestamp)!;
56
+ if (type === "compaction") push(entry, "compaction");
57
+ else if (type === "custom") {
58
+ const data = obj(entry.data);
59
+ if (entry.customType === "todo/v1" && Array.isArray(data.tasks)) {
60
+ const tasks = data.tasks.map(obj);
61
+ const ev = tasks.flatMap((t) => (Array.isArray(t.evidence) ? t.evidence.map((e) => `evidence ${obj(e).result === "pass" ? "pass" : "fail"}`) : []));
62
+ const graph = tasks.some((t) => graphOfTodo(t)) ? "; graph named" : "";
63
+ const now = `todo list: ${counts(tasks.map((t) => safeName(t.status)))}${ev.length ? `; ${counts(ev)}` : ""}${graph}`;
64
+ if (now !== lastTodo) push(entry, now);
65
+ lastTodo = now;
66
+ } else if (entry.customType === "straw-boss" && typeof data.duty === "string") push(entry, `sb kind ${safeName(data.duty)} (kind entry)`);
67
+ } else if (type === "custom_message") {
68
+ const details = obj(entry.details);
69
+ if (entry.customType === "anchorloop-close-guard") push(entry, `close-guard ${noticeKind(entry.content)}`);
70
+ else if (entry.customType === "pi-loop-monitor") {
71
+ const o = obj(details.monitorOutcome);
72
+ if (details.deliveryGroup === "monitor-terminal") push(entry, `monitor ${safeName(str(o.monitorId) ?? "?")} ended ${typeof o.exitCode === "number" ? `exit=${o.exitCode}` : safeName(o.status)}`);
73
+ } else if (entry.customType === "straw-boss" && details.briefed) {
74
+ const b = obj(details.briefed);
75
+ push(entry, `sb role ${safeName(b.name ?? b.role)} ${b.duty ? safeName(b.duty) : ""}`.trim());
76
+ } else if (entry.customType === "subagent_result") push(entry, "subagent result");
77
+ } else if (type === "message") {
78
+ const message = obj(entry.message);
79
+ if (message.role === "system") {
80
+ const section = obj(message.sections)["straw-boss"];
81
+ if (typeof section === "string") push(entry, `sb kind ${sbKindOf(section) ?? "none (not a main)"} (role prompt)`);
82
+ } else if (message.role === "user") {
83
+ const words = text(message.content);
84
+ push(entry, firstUser ? `user brief${namesCheck(words) ? " (names a check)" : ""}` : "user");
85
+ firstUser = false;
86
+ } else if (message.role === "assistant" && Array.isArray(message.content)) {
87
+ for (const raw of message.content) {
88
+ const part = obj(raw);
89
+ if (part.type === "text" && typeof part.text === "string" && anchorLine(part.text) !== undefined) push(entry, "anchor stated");
90
+ if (part.type !== "toolCall" || typeof part.id !== "string") continue;
91
+ const args = obj(part.arguments);
92
+ const name = safeName(part.name);
93
+ const command = str(args.command);
94
+ const items = [args, ...(Array.isArray(args.tasks) ? args.tasks.map(obj) : [])];
95
+ const evidence = items.flatMap((i) => (Array.isArray(i.evidence) ? i.evidence.map((e) => (obj(e).result === "pass" ? "pass" : "fail")) : []));
96
+ calls.set(part.id, {
97
+ name,
98
+ path: str(args.path),
99
+ check: command !== undefined && isCheckRun(command),
100
+ evidence: evidence.length ? counts(evidence.map((e) => `evidence ${e}`)) : undefined,
101
+ action: str(args.action) ? safeName(args.action) : undefined,
102
+ role: name === "subagent" ? safeName(str(args.agent) ?? "default") : undefined,
103
+ });
104
+ if (name === "todo" && items.some((i) => (typeof i.anchor === "string" && i.anchor.trim()) || obj(i.metadata).anchor)) push(entry, "todo anchor set");
105
+ }
106
+ } else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
107
+ const call = calls.get(message.toolCallId);
108
+ if (!call) continue;
109
+ calls.delete(message.toolCallId);
110
+ const code = obj(message.structuredContent).exit_code;
111
+ const ok = typeof code === "number" ? code === 0 : message.isError !== true;
112
+ const status = typeof code === "number" ? `exit=${code}` : ok ? "ok" : "error";
113
+ if (call.name === "edit" || call.name === "write") push(entry, `${call.name} ${call.path ? safeName(call.path) : "?"} ${ok ? "ok" : "error"}`);
114
+ else if (call.name === "bash" || call.name === "MonitorCreate") push(entry, `${call.name === "bash" ? "bash" : "monitor start"}${call.check ? " check" : ""} ${status}`);
115
+ else if (call.name === "todo") push(entry, `todo ${call.action ?? "?"} ${ok ? "ok" : "error"}${call.evidence ? `; ${call.evidence}` : ""}`);
116
+ else if (call.name === "subagent") push(entry, `subagent ${call.role} ${ok ? "launched" : "error"}`);
117
+ else push(entry, `${call.name} ${ok ? "ok" : "error"}`);
118
+ }
119
+ }
120
+ }
121
+ for (const r of tracker.results(start >= ERA_START)) out.push(`${r.name}: ${r.label} (${r.explanation})`);
122
+ return out;
123
+ }