pi-evals 0.4.1 → 0.5.1

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/src/detectors.ts CHANGED
@@ -7,9 +7,13 @@
7
7
  * MIT, Copyright (c) 2026 Wei Hung, anchorloop 3.3.0 at 7614445): the last `Anchor:` line or todo anchor,
8
8
  * backticked commands (a todo's bare value is one command), a change is a successful `write` or `edit`,
9
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. Unlike the guard, an Anchor stated only in the
11
- * first user message (a subagent's brief) is reported as `anchor_only_in_brief`, still a fail: the rule asks the
12
- * agent to state 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.
13
17
  */
14
18
  import type { Label } from "./schema.ts";
15
19
 
@@ -48,11 +52,50 @@ function commandsOf(text: string, bare: boolean): string[] {
48
52
  return ticked.length || !bare ? ticked : [squeeze(text)].filter(Boolean);
49
53
  }
50
54
 
55
+ const LABEL = String.raw`(?:reality anchor|anchor|checks?|gates?|verify|verification|done when|驗證|檢查|驗收)`;
56
+ const LABELLED = new RegExp(String.raw`^[ \t>*_#-]*${LABEL}[*_]*\s*[::][*_]*\s*(.+)$`, "gim");
57
+
51
58
  function anchorLine(text: string): string | undefined {
52
- const lines = [...text.matchAll(/^[ \t>*_-]*(?:reality )?anchor[*_]*:[*_]*\s*(.+)$/gim)];
53
- return lines.at(-1)?.[1];
59
+ return [...text.matchAll(LABELLED)].at(-1)?.[1];
60
+ }
61
+
62
+ /** Tools and scripts whose run checks a change: tests, builds, linters, type checkers, and named check scripts. */
63
+ const RUNNER = new RegExp(
64
+ [
65
+ String.raw`(?:npm|pnpm|yarn|bun)(?:\s+--?[\w=.'"*/@-]+)*(?:\s+run)?(?:\s+-s)?(?:\s+--?[\w=.'"*/@-]+)*\s+(?:t|test|check|lint|build|typecheck|type-check|verify|e2e|gates?)(?:[:\w-]*)\b`,
66
+ String.raw`(?:(?:npx|bunx|pnpm\s+(?:exec|dlx)|yarn\s+dlx|uv\s+run(?:\s+--?[\w=-]+)*|poetry\s+run)\s+)?(?:vitest|jest|mocha|pytest|tsc|vue-tsc|eslint|ruff|mypy|pyright|biome|svelte-check|shellcheck|dprint\s+check|playwright\s+test|cypress\s+run|astro\s+check)\b`,
67
+ String.raw`node\s+(?:--[\w-]+\s+)*--test\b`,
68
+ String.raw`(?:deno|bun)\s+(?:test|check|lint)\b`,
69
+ String.raw`(?:go\s+(?:test|vet|build)|cargo\s+(?:test|check|build|clippy)|dotnet\s+(?:test|build)|swift\s+(?:test|build)|make\s+(?:test|check|lint)|mvn\s+(?:test|verify)|\S*gradlew?\s+(?:test|build|check))\b`,
70
+ String.raw`python3?(?:\s+-[A-Za-z]+)*\s+-m\s+(?:pytest|unittest|py_compile|mypy)\b`,
71
+ String.raw`ansible-playbook\b.*--(?:check|syntax-check)\b`,
72
+ ].join("|"),
73
+ "i",
74
+ );
75
+ /** A script whose name says it checks: scripts/check-links.mjs, gates.sh, measure.mjs, validate.py. */
76
+ const CHECK_SCRIPT = String.raw`(?:\S*/)?(?:[\w-]*[-_.])?(?:tests?|checks?|gates?|verify|validate|lint|measure)(?:[-_.][\w.-]*)?\.(?:py|sh|mjs|js|ts)\b`;
77
+ const INTERPRETER = String.raw`(?:(?:bash|sh|python3?|node|bun|uv\s+run(?:\s+--?[\w=-]+)*\s+python3?)(?:\s+-[A-Za-z]+)*\s+)`;
78
+ // A run: a runner, a check script, or any script under tests/ (python3 tests/overlay.py, tests/run.sh).
79
+ // A dotnet wrapper script that builds or tests: scripts/dev/dotnet-local.py test <project>.
80
+ const DOTNET_SCRIPT = String.raw`\S*dotnet[\w-]*\.py\s+(?:build|test)\b`;
81
+ const RUN_START = new RegExp(String.raw`^(?:(?:\S*/)?(?:${RUNNER.source})|${INTERPRETER}?(?:${CHECK_SCRIPT}|${DOTNET_SCRIPT}|\S*\btests?/\S+))`, "i");
82
+ // A mention in prose, as in a brief: a runner or a check script anywhere in a line.
83
+ const MENTION = new RegExp(String.raw`(?:^|[\s\x60("'>/])(?:${RUNNER.source}|${CHECK_SCRIPT})`, "im");
84
+ // Shell lead-ins stripped from each command segment before matching.
85
+ const LEAD = /^(?:[({!]\s*|(?:time|exec|command|nice|sudo\s+-n|timeout\s+\d+[smh]?|set\s+-\S+(?:\s+\S+)?)\s+|[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)+/;
86
+
87
+ /** Whether a shell command runs a check: one of its `&&`, `||`, `;`, `|` or line segments starts with a check runner. */
88
+ export function isCheckRun(command: string): boolean {
89
+ return command.split(/&&|\|\||[;|\n]/).some((part) => {
90
+ const segment = part.trim().replace(LEAD, "");
91
+ return segment.length > 0 && RUN_START.test(segment);
92
+ });
54
93
  }
55
94
 
95
+ // Prose a test run cannot check: a report, notes, a changelog. Writing one after the check does not undo the check.
96
+ const PROSE_FILE = /\.(?:md|markdown|txt|rst)$/i;
97
+ const TEST_FILE = /(?:^|\/)(?:tests?|__tests__|specs?)\/|[._-](?:test|spec)\.[A-Za-z]+$|_test\.(?:go|py|rb)$|(?:^|\/)test_[^/]+\.py$|Tests?\.cs$/;
98
+
56
99
  type Part = { type?: string; text?: string; id?: string; name?: string; arguments?: Record<string, unknown> };
57
100
  interface Task { status?: string; evidence?: unknown }
58
101
  type Entry = {
@@ -60,17 +103,22 @@ type Entry = {
60
103
  customType?: string;
61
104
  content?: unknown;
62
105
  data?: { v?: number; tasks?: Task[] };
106
+ details?: { monitorOutcome?: { monitorId?: unknown; exitCode?: unknown } };
63
107
  message?: { role?: string; content?: unknown; toolCallId?: string; isError?: boolean; structuredContent?: { exit_code?: unknown } };
64
108
  };
65
109
 
66
110
  export class ProcessTracker {
67
111
  private seq = 0;
68
- private calls = new Map<string, { name: string; command?: string }>();
112
+ private calls = new Map<string, { name: string; command?: string; path?: string; evidence?: boolean }>();
69
113
  private runs: { seq: number; command: string; ok: boolean }[] = [];
114
+ private monitors = new Map<string, string>();
115
+ private evidenceAt = -1;
70
116
  private anchor: string[] | undefined;
71
- private anchoredBeforeChange = false;
117
+ private ownAnchor = false;
118
+ private anchored: "anchor_first" | "anchor_in_brief" | "test_first" | undefined;
72
119
  private firstChange = -1;
73
120
  private lastChange = -1;
121
+ private lastNonProse = -1;
74
122
  private tasks: Task[] | undefined;
75
123
  private sawUser = false;
76
124
  private briefAnchor = false;
@@ -84,6 +132,12 @@ export class ProcessTracker {
84
132
  this.tasks = entry.data.tasks;
85
133
  return undefined;
86
134
  }
135
+ if (entry?.type === "custom_message" && entry.customType === "pi-loop-monitor") {
136
+ const outcome = entry.details?.monitorOutcome;
137
+ const command = outcome && this.monitors.get(String(outcome.monitorId));
138
+ if (command && typeof outcome.exitCode === "number") this.pushRun(seq, command, outcome.exitCode === 0);
139
+ return undefined;
140
+ }
87
141
  if (entry?.type === "custom_message" && entry.customType === NOTICE_TYPE) {
88
142
  const kind = noticeKind(entry.content);
89
143
  this.notices.set(kind, (this.notices.get(kind) ?? 0) + 1);
@@ -94,23 +148,32 @@ export class ProcessTracker {
94
148
  if (message.role === "user" && !this.sawUser) {
95
149
  this.sawUser = true;
96
150
  const text = Array.isArray(message.content) ? (message.content as Part[]).map((p) => (p?.type === "text" ? (p.text ?? "") : "")).join("\n") : String(message.content ?? "");
97
- this.briefAnchor = anchorLine(text) !== undefined;
151
+ const line = anchorLine(text);
152
+ // The brief's anchor is the worker's anchor (anchorloop: "Put the unit's Anchor: line in the brief").
153
+ if (line !== undefined) this.anchor = commandsOf(line, false);
154
+ this.briefAnchor = line !== undefined || MENTION.test(text);
98
155
  } else if (message.role === "assistant" && Array.isArray(message.content)) {
99
156
  for (const part of message.content as Part[]) {
100
157
  if (part?.type === "text" && typeof part.text === "string") {
101
158
  const line = anchorLine(part.text);
102
159
  if (line !== undefined) this.setAnchor(commandsOf(line, false));
103
160
  } else if (part?.type === "toolCall" && typeof part.id === "string") {
104
- const command = part.name === "bash" && typeof part.arguments?.command === "string" ? squeeze(part.arguments.command) : undefined;
105
- this.calls.set(part.id, { name: String(part.name), command });
106
- if (part.name === "todo" && part.arguments) {
107
- const batch = Array.isArray(part.arguments.tasks) ? part.arguments.tasks : [];
108
- for (const item of [part.arguments, ...batch] as Record<string, unknown>[]) {
109
- const meta = item?.metadata as Record<string, unknown> | undefined;
161
+ const args = part.arguments ?? {};
162
+ const command = (part.name === "bash" || part.name === "MonitorCreate") && typeof args.command === "string" ? squeeze(args.command) : undefined;
163
+ const path = typeof args.path === "string" ? args.path : undefined;
164
+ let evidence = false;
165
+ if (part.name === "todo") {
166
+ const batch = Array.isArray(args.tasks) ? args.tasks : [];
167
+ for (const item of [args, ...batch] as Record<string, unknown>[]) {
168
+ const meta = item?.metadata as { anchor?: unknown; sb?: { spec?: { check?: { run?: unknown } } } } | undefined;
110
169
  const value = [item?.anchor, meta?.anchor].find((v) => typeof v === "string" && v.trim()) as string | undefined;
170
+ const spec = meta?.sb?.spec?.check;
111
171
  if (value) this.setAnchor(commandsOf(value, true));
172
+ else if (spec) this.setAnchor(typeof spec.run === "string" && spec.run.trim() ? [squeeze(spec.run)] : []);
173
+ if (Array.isArray(item?.evidence) && item.evidence.some((e) => (e as { result?: unknown })?.result === "pass")) evidence = true;
112
174
  }
113
175
  }
176
+ this.calls.set(part.id, { name: String(part.name), command, path, evidence });
114
177
  }
115
178
  }
116
179
  } else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
@@ -122,12 +185,17 @@ export class ProcessTracker {
122
185
  if ((call.name === "write" || call.name === "edit") && ok) {
123
186
  if (this.firstChange < 0) {
124
187
  this.firstChange = seq;
125
- this.anchoredBeforeChange = this.anchor !== undefined;
188
+ this.anchored = this.ownAnchor ? "anchor_first" : this.briefAnchor ? "anchor_in_brief" : call.path && TEST_FILE.test(call.path) ? "test_first" : undefined;
126
189
  }
127
190
  this.lastChange = seq;
191
+ if (!call.path || !PROSE_FILE.test(call.path)) this.lastNonProse = seq;
128
192
  } else if (call.name === "bash" && call.command) {
129
- this.runs.push({ seq, command: call.command, ok });
130
- if (this.runs.length > MAX_RUNS) this.runs.splice(0, this.runs.length - MAX_RUNS);
193
+ this.pushRun(seq, call.command, ok);
194
+ } else if (call.name === "MonitorCreate" && call.command && ok) {
195
+ const id = /Monitor #(\d+) started/.exec(resultText(message.content))?.[1];
196
+ if (id) this.monitors.set(id, call.command);
197
+ } else if (call.name === "todo" && call.evidence && ok) {
198
+ this.evidenceAt = seq;
131
199
  }
132
200
  }
133
201
  return undefined;
@@ -135,6 +203,12 @@ export class ProcessTracker {
135
203
 
136
204
  private setAnchor(commands: string[]) {
137
205
  this.anchor = commands;
206
+ this.ownAnchor = true;
207
+ }
208
+
209
+ private pushRun(seq: number, command: string, ok: boolean) {
210
+ this.runs.push({ seq, command, ok });
211
+ if (this.runs.length > MAX_RUNS) this.runs.splice(0, this.runs.length - MAX_RUNS);
138
212
  }
139
213
 
140
214
  results(inScope: boolean): DetectorResult[] {
@@ -145,20 +219,26 @@ export class ProcessTracker {
145
219
  private anchorFirst(): DetectorResult {
146
220
  const name = "anchor_before_first_edit";
147
221
  if (this.firstChange < 0) return { name, label: "na", explanation: "no_edit" };
148
- if (this.anchoredBeforeChange) return { name, label: "pass", explanation: "anchor_first" };
149
- return { name, label: "fail", explanation: this.briefAnchor ? "anchor_only_in_brief" : "change_before_anchor" };
222
+ if (this.anchored) return { name, label: "pass", explanation: this.anchored };
223
+ return { name, label: "fail", explanation: "change_before_anchor" };
150
224
  }
151
225
 
152
226
  private checkAfter(): DetectorResult {
153
227
  const name = "check_after_last_edit";
154
228
  if (this.lastChange < 0) return { name, label: "na", explanation: "no_edit" };
155
- if (!this.anchor) return { name, label: "na", explanation: "no_anchor" };
156
- if (!this.anchor.length) return { name, label: "na", explanation: "anchor_without_command" };
157
- const green = this.anchor.every((command) => {
158
- const last = this.runs.findLast((run) => run.command.includes(command));
159
- return !!last && last.seq > this.lastChange && last.ok;
160
- });
161
- return green ? { name, label: "pass", explanation: "anchor_green" } : { name, label: "fail", explanation: "no_passing_run_after_change" };
229
+ const prose = this.lastNonProse < 0;
230
+ const last = prose ? this.lastChange : this.lastNonProse;
231
+ const commands = this.anchor ?? [];
232
+ const latest = commands.map((command) => this.runs.findLast((run) => run.command.includes(command)));
233
+ if (commands.length && latest.every((run) => !!run && run.seq > last && run.ok)) return { name, label: "pass", explanation: "anchor_green" };
234
+ if (this.evidenceAt > last) return { name, label: "pass", explanation: "evidence_after_change" };
235
+ // An anchor command that ran after the change and failed is a failing check, whatever else passed.
236
+ if (latest.some((run) => !!run && run.seq > last && !run.ok)) return { name, label: "fail", explanation: "no_passing_run_after_change" };
237
+ const check = this.runs.findLast((run) => run.seq > last && isCheckRun(run.command));
238
+ if (check) return check.ok ? { name, label: "pass", explanation: "check_run_after_change" } : { name, label: "fail", explanation: "no_passing_run_after_change" };
239
+ if (prose) return { name, label: "na", explanation: "prose_only" };
240
+ if (this.anchor && !commands.length) return { name, label: "na", explanation: "anchor_without_command" };
241
+ return { name, label: "fail", explanation: commands.length ? "no_passing_run_after_change" : "no_check_after_change" };
162
242
  }
163
243
 
164
244
  private todoEvidence(): DetectorResult {
@@ -180,3 +260,7 @@ export class ProcessTracker {
180
260
  }
181
261
 
182
262
  const DETECTORS_ALL: DetectorName[] = [...DETECTORS];
263
+
264
+ function resultText(content: unknown): string {
265
+ return Array.isArray(content) ? (content as Part[]).map((p) => (p?.type === "text" ? (p.text ?? "") : "")).join("\n") : String(content ?? "");
266
+ }
@@ -18,7 +18,7 @@ export interface FileEntry {
18
18
  }
19
19
 
20
20
  /** Bump when extraction changes what it derives; a checkpoint from another version re-reads every file. */
21
- export const EXTRACTOR_VERSION = 4;
21
+ export const EXTRACTOR_VERSION = 5;
22
22
 
23
23
  export interface Checkpoint {
24
24
  v: 1;
package/src/findings.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { correctionsFinding } from "./labels-query.ts";
2
3
  import type { ReportModel } from "./model.ts";
3
4
  import { overview, readings, value, verdict } from "./report/findings.ts";
4
5
  import { words } from "./report/format.ts";
@@ -38,6 +39,8 @@ export function findings(m: ReportModel) {
38
39
  lines.push(`Cleanup (all projects/dates): ${gate} → coverage`);
39
40
  const work = itemsFinding(m.work);
40
41
  if (work) lines.push(work);
42
+ const corrected = correctionsFinding(m);
43
+ if (corrected) lines.push(corrected);
41
44
  const w = m.weekly;
42
45
  if (!w) lines.push("Need two weeks in range for error trends → packages / monitors");
43
46
  else {
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * pi-evals: the live observer, the `/evals` command (status, extract, report, mark), and the `evals_query` tool.
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), 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";
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
8
8
  import { Type } from "typebox";
9
9
  import { scriptsDir } from "./findings.ts";
10
+ import { liveLabels } from "./live-labels.ts";
10
11
  import { observe } from "./observer.ts";
11
12
  import { context, mark, reportPath, runReport, statusText } from "./ops.ts";
12
13
  import { query, type View, VIEWS } from "./query.ts";
@@ -23,7 +24,7 @@ export function cliPath(): { cmd: string; args: string[] } | undefined {
23
24
  return found ? { cmd: process.execPath, args: [found] } : undefined;
24
25
  }
25
26
 
26
- const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark"];
27
+ const SUBCOMMANDS = ["status", "findings", "extract", "report", "mark", "label"];
27
28
 
28
29
  function parseFlags(args: string[]) {
29
30
  const out: { since?: string; days?: number; project?: string; rest: string[] } = { rest: [] };
@@ -41,7 +42,8 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
41
42
  const spawnFn = options.spawnExtract ?? spawn;
42
43
  return function evals(pi: ExtensionAPI): void {
43
44
  const ctx0 = context(env);
44
- observe(pi, { layout: ctx0.layout, home: ctx0.home, now: options.now });
45
+ const observed = observe(pi, { layout: ctx0.layout, home: ctx0.home, now: options.now });
46
+ const labels = liveLabels(pi, { env, now: options.now ?? Date.now, observed });
45
47
  let settingsWarned = false;
46
48
  pi.on("session_start", (_event, ctx) => {
47
49
  if (settingsWarned || !ctx0.settings.error) return;
@@ -96,7 +98,7 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
96
98
  };
97
99
 
98
100
  pi.registerCommand("evals", {
99
- description: "Usage and process records: /evals [status|findings|extract|report|mark <note>]",
101
+ description: "Usage and process records: /evals [status|findings|extract|report|mark <note>|label]",
100
102
  getArgumentCompletions: (prefix: string) => {
101
103
  const items = SUBCOMMANDS.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
102
104
  return items.length ? items : null;
@@ -135,6 +137,8 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
135
137
  }
136
138
  const change = mark(text, env);
137
139
  ctx.ui.notify(`pi-evals: marked ${change.at}: ${text}`, "info");
140
+ } else if (sub === "label") {
141
+ await labels.command(words.slice(1), ctx);
138
142
  } else {
139
143
  ctx.ui.notify(`Unknown subcommand "${sub}". Use: ${SUBCOMMANDS.join(", ")}.`, "warning");
140
144
  }
@@ -0,0 +1,36 @@
1
+ /** The `labels` view of `evals_query` and its line in `findings`: names and numbers, never a note. */
2
+ import { type ReportModel, SMALL_SAMPLE } from "./model.ts";
3
+
4
+ /** Corrections of one rule and failure type that make a findings line. */
5
+ export const CLUSTER = 3;
6
+
7
+ const list = (rows: { n: number }[], name: (r: never) => string, limit = 6) => rows.slice(0, limit).map((r) => `${name(r as never)} ${r.n}`).join(", ") || "none";
8
+ const ratio = (c: { agree: number; n: number }) => `${c.agree}/${c.n}`;
9
+
10
+ export function labelsView(m: ReportModel): string[] {
11
+ const l = m.labels;
12
+ if (l.needsIndex) return ["labels in this range need an index with session ids: the user can run /evals extract"];
13
+ const c = l.corrections;
14
+ const out = [
15
+ "human labels = your verdicts on a rule; after the fact (batch) or in the moment (/evals label)",
16
+ `human: after the fact ${l.bySource.batch} (${l.sessions.batch} sessions), in the moment ${l.bySource.live} (${l.sessions.live} sessions${l.fromWords ? `; ${l.fromWords} formatted by the agent from your words` : ""}); unclear ${l.unclear}; no code verdict ${l.noCode}; on other ${l.other}`,
17
+ "code vs human, agreed/compared (after the fact; in the moment):",
18
+ ];
19
+ for (const a of l.agreement) out.push(`${a.detector}: ${ratio(a)} (${ratio(a.bySource.batch)}; ${ratio(a.bySource.live)})`);
20
+ out.push(`corrections the agent logged (not all mistakes): ${c.n} in ${c.sessions} sessions${c.n && c.n < SMALL_SAMPLE ? `; small (<${SMALL_SAMPLE}), a hint not a trend` : ""}`);
21
+ if (c.n) {
22
+ out.push(`by rule: ${list(c.byRule, (r: { rule: string }) => r.rule)}`);
23
+ out.push(`by type: ${list(c.byType, (r: { type: string }) => r.type)}`);
24
+ out.push(`by rule/type: ${list(c.byRuleType, (r: { rule: string; type: string }) => `${r.rule}/${r.type}`, 4)}`);
25
+ out.push(`by skill loaded (one correction counts for each): ${list(c.bySkill, (r: { skill: string }) => r.skill || "(none)")}`);
26
+ out.push(`by anchorloop version: ${list(c.byVersion, (r: { version: string }) => r.version)}`);
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /** A findings line when corrections of one rule and type recur. */
32
+ export function correctionsFinding(m: ReportModel): string | undefined {
33
+ const c = m.labels.corrections, top = c.byRuleType[0];
34
+ if (!top || top.n < CLUSTER) return undefined;
35
+ return `Corrections logged: ${top.n} of ${c.n} are ${top.rule}/${top.type} (agent-logged, not all mistakes) → labels`;
36
+ }
package/src/labels.ts ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Labels (`labels.jsonl`, append-only): human verdicts on the process checks, given after the fact (`batch`, rows
3
+ * without a source) or in the moment (`live`, `/evals label`), and the corrections an agent logs when the user
4
+ * corrects how it worked (`correction`, the `evals_label` tool). Only a human note is free text; agent rows hold names.
5
+ */
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
7
+ import { dirname } from "node:path";
8
+ import { DETECTORS } from "./detectors.ts";
9
+ import { DETECTOR_META, type Text } from "./meta.ts";
10
+ import { safeName, traceId } from "./schema.ts";
11
+ import { liveItemKey } from "./work/track.ts";
12
+
13
+ export const RULES = [...DETECTORS, "other"] as const;
14
+ export type Rule = (typeof RULES)[number];
15
+ export const VERDICTS = ["pass", "fail", "unclear"] as const;
16
+ export type Verdict = (typeof VERDICTS)[number];
17
+ export const FAILURE_TYPES = ["no_check_stated", "no_check_run", "skipped_rule", "wrong_order", "unverified_claim", "ignored_instruction", "other"] as const;
18
+ export type FailureType = (typeof FAILURE_TYPES)[number];
19
+ /** `live-prompt`: the user's words after `/evals label`, which the agent turned into rows on the user's behalf. */
20
+ export type LabelSource = "batch" | "live" | "live-prompt" | "correction";
21
+ export const NOTE_MAX = 500;
22
+
23
+ const t = (en: string, zh: string): Text => ({ en, zh });
24
+ export const RULE_OTHER = t("Other", "其他");
25
+ export const VERDICT_META: Record<Verdict, Text> = { pass: t("Followed", "照做"), fail: t("Not followed", "沒照做"), unclear: t("Cannot tell", "看不出來") };
26
+ export const FAILURE_TYPE_META: Record<FailureType, Text> = {
27
+ no_check_stated: t("Did not say how to check", "沒先說怎麼驗證"),
28
+ no_check_run: t("Did not run the check", "沒跑檢查"),
29
+ skipped_rule: t("Skipped a rule", "跳過規則"),
30
+ wrong_order: t("Wrong order", "順序錯了"),
31
+ unverified_claim: t("Said done without proof", "沒驗證就說做好了"),
32
+ ignored_instruction: t("Ignored your instruction", "沒照你的指示"),
33
+ other: t("Other", "其他"),
34
+ };
35
+ export const ruleLabel = (rule: string, lang: "en" | "zh") => (rule === "other" ? RULE_OTHER[lang] : (DETECTOR_META[rule]?.label[lang] ?? rule));
36
+
37
+ export interface LabelRow {
38
+ session_id: string;
39
+ evaluation_name: string;
40
+ label: Verdict;
41
+ at: string;
42
+ annotator?: "human" | "agent";
43
+ /** Absent on rows written before 0.5.0: those were given after the fact. */
44
+ source?: LabelSource;
45
+ item?: string;
46
+ project?: string;
47
+ /** Skills loaded in the session before the label, for corrections. */
48
+ skills?: string[];
49
+ type?: FailureType;
50
+ note?: string;
51
+ /** A withdrawal of the session's latest live row in effect (`/evals label undo`); holds that row's `at`. */
52
+ undo?: string;
53
+ }
54
+
55
+ /** A human label given in the moment: typed, or formatted by the agent from the user's words. */
56
+ export const givenLive = (row: LabelRow) => row.source === "live" || row.source === "live-prompt";
57
+ const isLive = (row: LabelRow) => givenLive(row) && row.annotator === "human" && !row.undo;
58
+
59
+ function parse(file: string): LabelRow[] {
60
+ if (!existsSync(file)) return [];
61
+ return readFileSync(file, "utf8")
62
+ .split("\n")
63
+ .filter(Boolean)
64
+ .flatMap((line) => {
65
+ try {
66
+ const row = JSON.parse(line) as LabelRow;
67
+ return row && typeof row.session_id === "string" ? [row] : [];
68
+ } catch {
69
+ return [];
70
+ }
71
+ });
72
+ }
73
+
74
+ /** Rows in effect, in file order. A withdrawal cancels its session's latest live row still in effect before it. */
75
+ export function readLabels(file: string): LabelRow[] {
76
+ const rows = parse(file);
77
+ const gone = new Set<number>();
78
+ const live = new Map<string, number[]>();
79
+ rows.forEach((r, i) => {
80
+ if (r.undo) {
81
+ const last = live.get(r.session_id)?.pop();
82
+ if (last !== undefined) gone.add(last);
83
+ gone.add(i);
84
+ } else if (isLive(r)) live.set(r.session_id, [...(live.get(r.session_id) ?? []), i]);
85
+ });
86
+ return rows.filter((_, i) => !gone.has(i));
87
+ }
88
+
89
+ export function appendLabel(file: string, row: LabelRow): void {
90
+ mkdirSync(dirname(file), { recursive: true });
91
+ appendFileSync(file, `${JSON.stringify(row)}\n`);
92
+ }
93
+
94
+ /** Withdraws this session's last live label by appending a withdrawal; returns the withdrawn row. */
95
+ export function undoLast(file: string, session: string, at: string): LabelRow | undefined {
96
+ const last = readLabels(file).filter((r) => r.session_id === session && isLive(r)).at(-1);
97
+ if (last) appendLabel(file, { session_id: session, evaluation_name: last.evaluation_name, label: last.label, at, annotator: "human", source: "live", undo: last.at });
98
+ return last;
99
+ }
100
+
101
+ /** One line, at most NOTE_MAX characters; empty becomes none. */
102
+ export function cleanNote(text: string | undefined): string | undefined {
103
+ const one = (text ?? "").replace(/\s+/g, " ").trim();
104
+ return one ? Array.from(one).slice(0, NOTE_MAX).join("") : undefined;
105
+ }
106
+
107
+ type Entry = { type?: unknown; customType?: unknown; data?: unknown };
108
+
109
+ /** The work item in progress on the current branch: its 0.4.0 key (uid, else origin#id, else session#id). */
110
+ export function itemOnBranch(branch: readonly unknown[] | undefined, session: string): string | undefined {
111
+ if (!branch) return undefined;
112
+ for (let i = branch.length - 1; i >= 0; i--) {
113
+ const e = branch[i] as Entry;
114
+ if (e?.type !== "custom" || e.customType !== "todo/v1") continue;
115
+ const tasks = (e.data as { tasks?: unknown })?.tasks;
116
+ if (Array.isArray(tasks)) return liveItemKey(tasks, session);
117
+ }
118
+ return undefined;
119
+ }
120
+
121
+ /**
122
+ * `evals_label` arguments: known names only, nothing else; throws on any other field or value. Without `on_behalf`
123
+ * the row is the agent's own correction, a fail; `on_behalf: "user"` is accepted only while `speaking` (a
124
+ * `/evals label <words>` turn of this session is running), and then needs the user's verdict.
125
+ */
126
+ export function agentLabel(params: unknown, speaking: boolean): { rule: Rule; label: Verdict; type?: FailureType; onBehalf: boolean } {
127
+ const p = (params && typeof params === "object" ? params : {}) as Record<string, unknown>;
128
+ const extra = Object.keys(p).filter((k) => !["rule", "label", "type", "on_behalf"].includes(k));
129
+ if (extra.length) throw new Error(`evals_label takes only rule, label, type and on_behalf, not ${extra.map((k) => safeName(k)).join(", ")}.`);
130
+ if (!RULES.includes(p.rule as Rule)) throw new Error(`rule must be one of: ${RULES.join(", ")}.`);
131
+ if (p.type !== undefined && !FAILURE_TYPES.includes(p.type as FailureType)) throw new Error(`type must be one of: ${FAILURE_TYPES.join(", ")}.`);
132
+ if (p.on_behalf !== undefined && p.on_behalf !== "user") throw new Error('on_behalf can only be "user".');
133
+ const onBehalf = p.on_behalf === "user";
134
+ if (onBehalf && !speaking) throw new Error('on_behalf "user" is valid only during a /evals label turn the user started in this session; log your own correction without it.');
135
+ if (onBehalf ? !VERDICTS.includes(p.label as Verdict) : p.label !== undefined && p.label !== "fail") {
136
+ throw new Error(onBehalf ? "label must be the user's verdict: pass, fail or unclear." : "Your own correction is always a fail; a pass or unclear verdict is the user's, given through /evals label.");
137
+ }
138
+ const label = (p.label as Verdict | undefined) ?? "fail";
139
+ if (p.type !== undefined && label !== "fail") throw new Error("type names the kind of slip, so it goes only with a fail.");
140
+ return { rule: p.rule as Rule, label, type: p.type as FailureType | undefined, onBehalf };
141
+ }
142
+
143
+ export interface LabelScope {
144
+ since?: string;
145
+ until?: string;
146
+ project?: string;
147
+ /** Hashed ids (`traceId(id, "labels")`) of the sessions in range, and of every indexed session; absent: no scope. */
148
+ selected?: Set<string>;
149
+ indexed?: Set<string>;
150
+ }
151
+
152
+ const rate = (num: number, den: number) => ({ value: den > 0 ? num / den : null, n: den });
153
+ type Count = { n: number; agree: number };
154
+ const counted = <K extends string>(map: Map<K, number>) => [...map].sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])));
155
+ const bump = <K>(map: Map<K, number>, key: K) => map.set(key, (map.get(key) ?? 0) + 1);
156
+
157
+ /**
158
+ * Human labels against the code checks (agreement, by when they were given), and the corrections agents logged.
159
+ * A session in the index belongs to the range by its start; a label whose session is not indexed yet (given in the
160
+ * moment, before an extract) belongs by its own time and project.
161
+ */
162
+ export function labelsModel(labelsFile: string, evalsFile: string, scope: LabelScope, versionOf: (at: string) => string | undefined) {
163
+ const empty = { present: false, n: 0, unclear: 0, bySource: { batch: 0, live: 0 }, fromWords: 0, sessions: { batch: 0, live: 0 }, noCode: 0, other: 0, agreement: [] as Agreement[], corrections: corrections([], versionOf) };
164
+ if (!existsSync(labelsFile)) return empty;
165
+ const code = existsSync(evalsFile) ? (JSON.parse(readFileSync(evalsFile, "utf8")) as Record<string, Record<string, string>>) : {};
166
+ const inDates = (at: string) => (!scope.since || at.slice(0, 10) >= scope.since) && (!scope.until || at.slice(0, 10) <= scope.until);
167
+ const inScope = (r: LabelRow) => {
168
+ if (!scope.selected) return true;
169
+ const id = traceId(r.session_id, "labels");
170
+ if (scope.selected.has(id)) return true;
171
+ return r.source !== undefined && !scope.indexed?.has(id) && typeof r.at === "string" && inDates(r.at) && (!scope.project || r.project === scope.project);
172
+ };
173
+ const rows = readLabels(labelsFile).filter(inScope);
174
+ const human = rows.filter((r) => r.annotator !== "agent");
175
+ const by = new Map<string, { unclear: number; batch: Count; live: Count }>();
176
+ const sessions = { batch: new Set<string>(), live: new Set<string>() };
177
+ const out = { ...empty, present: true, n: human.length };
178
+ for (const row of human) {
179
+ const source = givenLive(row) ? "live" : "batch";
180
+ out.bySource[source] += 1;
181
+ if (row.source === "live-prompt") out.fromWords += 1;
182
+ sessions[source].add(row.session_id);
183
+ if (row.evaluation_name === "other") {
184
+ out.other += 1;
185
+ continue;
186
+ }
187
+ const t = by.get(row.evaluation_name) ?? { unclear: 0, batch: { n: 0, agree: 0 }, live: { n: 0, agree: 0 } };
188
+ by.set(row.evaluation_name, t);
189
+ // "Cannot tell" is the reader's honest answer, not a disagreement: count it apart from the agreement rate.
190
+ if (row.label === "unclear") {
191
+ out.unclear += 1;
192
+ t.unclear += 1;
193
+ continue;
194
+ }
195
+ const verdict = code[row.session_id]?.[row.evaluation_name];
196
+ if (!verdict || verdict === "na") {
197
+ out.noCode += 1;
198
+ continue;
199
+ }
200
+ t[source].n += 1;
201
+ if (verdict === row.label) t[source].agree += 1;
202
+ }
203
+ out.sessions = { batch: sessions.batch.size, live: sessions.live.size };
204
+ out.agreement = [...by].map(([detector, t]) => {
205
+ const n = t.batch.n + t.live.n, agree = t.batch.agree + t.live.agree;
206
+ return { detector, n, agree, rate: rate(agree, n), unclear: t.unclear, bySource: { batch: { ...t.batch, rate: rate(t.batch.agree, t.batch.n) }, live: { ...t.live, rate: rate(t.live.agree, t.live.n) } } };
207
+ });
208
+ out.corrections = corrections(rows.filter((r) => r.annotator === "agent" && r.source === "correction"), versionOf);
209
+ return out;
210
+ }
211
+
212
+ interface Agreement {
213
+ detector: string;
214
+ n: number;
215
+ agree: number;
216
+ rate: { value: number | null; n: number };
217
+ unclear: number;
218
+ bySource: Record<"batch" | "live", Count & { rate: { value: number | null; n: number } }>;
219
+ }
220
+
221
+ /** The corrections agents logged, by rule, failure type, the skills loaded in the session, and anchorloop version. */
222
+ function corrections(rows: LabelRow[], versionOf: (at: string) => string | undefined) {
223
+ const rule = new Map<string, number>(), type = new Map<string, number>(), pair = new Map<string, number>();
224
+ const skill = new Map<string, Set<string>>(), skillN = new Map<string, number>(), version = new Map<string, Set<string>>(), versionN = new Map<string, number>();
225
+ for (const r of rows) {
226
+ const kind = r.type && FAILURE_TYPES.includes(r.type) ? r.type : "other";
227
+ bump(rule, r.evaluation_name);
228
+ bump(type, kind);
229
+ bump(pair, `${r.evaluation_name}|${kind}`);
230
+ for (const s of r.skills?.length ? r.skills : [""]) {
231
+ bump(skillN, s);
232
+ skill.set(s, (skill.get(s) ?? new Set()).add(r.session_id));
233
+ }
234
+ const v = versionOf(r.at) ?? "unknown";
235
+ bump(versionN, v);
236
+ version.set(v, (version.get(v) ?? new Set()).add(r.session_id));
237
+ }
238
+ return {
239
+ n: rows.length,
240
+ sessions: new Set(rows.map((r) => r.session_id)).size,
241
+ byRule: counted(rule).map(([name, n]) => ({ rule: name, n })),
242
+ byType: counted(type).map(([name, n]) => ({ type: name, n })),
243
+ byRuleType: counted(pair).map(([key, n]) => ({ rule: key.split("|")[0], type: key.split("|")[1], n })),
244
+ /** `skill` "" = no skill loaded before the correction. */
245
+ bySkill: counted(skillN).map(([name, n]) => ({ skill: name, n, sessions: skill.get(name)?.size ?? 0 })),
246
+ byVersion: counted(versionN).map(([name, n]) => ({ version: name, n, sessions: version.get(name)?.size ?? 0 })),
247
+ };
248
+ }