pi-evals 0.4.1 → 0.5.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/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
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Labels given in the moment: `/evals label` for the user (a verdict on a process rule, with an optional note in
3
+ * their own words, or just their words for the agent to format) and the `evals_label` tool for the agent (a
4
+ * correction it was given, or the user's words as rows; names only).
5
+ */
6
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import { agentLabel, appendLabel, cleanNote, FAILURE_TYPES, type FailureType, itemOnBranch, type LabelRow, type Rule, RULES, ruleLabel, undoLast, VERDICT_META, VERDICTS, type Verdict } from "./labels.ts";
9
+ import type { Observed } from "./observer.ts";
10
+ import { context } from "./ops.ts";
11
+ import { projectKey } from "./project.ts";
12
+
13
+ type Env = Record<string, string | undefined>;
14
+ type Ctx = Pick<ExtensionCommandContext, "cwd" | "sessionManager">;
15
+
16
+ const VERDICT_WORDS = new Map<string, Verdict>(VERDICTS.flatMap((v) => [[v, v], [VERDICT_META[v].zh, v]] as [string, Verdict][]));
17
+ const USAGE = `pi-evals 用法:/evals label(一步步選)、/evals label <規則> pass|fail|unclear [說明],或 /evals label <你的話>(交給代理人整理成標記);規則:${RULES.join("、")};/evals label undo 撤銷這段工作上一筆當下標記。`;
18
+
19
+ /** The turn that formats the user's words: the instruction to the agent, with the words last and verbatim. */
20
+ export function promptFor(words: string): string {
21
+ return [
22
+ "[/evals label] Below, in the user's own words, is the user's verdict on how this session's work followed the process rules.",
23
+ `Record it with evals_label, once per rule the words judge: on_behalf "user", rule (one of ${RULES.join(", ")}), label as the user judged it (pass, fail or unclear), and type when it is a fail.`,
24
+ "Record only what the user said, add no judgement of your own, then confirm in one line, in plain words and the user's language, what you recorded.",
25
+ "",
26
+ `User's words: ${words}`,
27
+ ].join("\n");
28
+ }
29
+
30
+ export function liveLabels(pi: ExtensionAPI, options: { env: Env; now: () => number; observed: Observed }) {
31
+ const { env, now, observed } = options;
32
+ /** The user's words waiting for their turn to start, and the turn that may speak for the user. */
33
+ let waiting: { session: string; prompt: string; note?: string } | undefined;
34
+ let speaking: { session: string; prompt: string; note?: string } | undefined;
35
+ const textOf = (content: unknown) =>
36
+ typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof (p as { text?: unknown }).text === "string" ? (p as { text: string }).text : "")).join("") : "";
37
+ const start = (text: string | undefined) => {
38
+ if (waiting && text === waiting.prompt) {
39
+ speaking = { ...waiting };
40
+ waiting = undefined;
41
+ }
42
+ };
43
+ pi.on("before_agent_start", (event) => start((event as { prompt?: string }).prompt));
44
+ // A prompt queued behind a running turn starts its own run without before_agent_start: its user message opens it.
45
+ pi.on("message_end", (event) => {
46
+ const message = (event as { message?: { role?: string; content?: unknown } }).message;
47
+ if (message?.role !== "user") return;
48
+ const text = textOf(message.content);
49
+ // Another message from the user in the same run is not part of the words the agent is formatting.
50
+ if (speaking && text !== speaking.prompt) speaking = undefined;
51
+ start(text);
52
+ });
53
+ pi.on("agent_end", () => {
54
+ speaking = undefined;
55
+ });
56
+ pi.on("session_start", () => {
57
+ waiting = speaking = undefined;
58
+ });
59
+ const where = (ctx: Ctx) => {
60
+ const c = context(env);
61
+ const session = ctx.sessionManager.getSessionId();
62
+ let branch: unknown[] | undefined;
63
+ try {
64
+ branch = ctx.sessionManager.getBranch?.();
65
+ } catch {}
66
+ return { file: c.layout.labels, session, item: itemOnBranch(branch, session), project: projectKey(ctx.cwd, c.home), at: new Date(now()).toISOString() };
67
+ };
68
+
69
+ async function command(words: string[], ctx: ExtensionCommandContext): Promise<void> {
70
+ const say = (text: string, level: "info" | "warning" = "info") => ctx.ui.notify(text, level);
71
+ const w = where(ctx);
72
+ if (words[0] === "undo") {
73
+ const last = undoLast(w.file, w.session, w.at);
74
+ say(last ? `pi-evals:已撤銷這段工作上一筆當下標記「${ruleLabel(last.evaluation_name, "zh")}」${VERDICT_META[last.label].zh}。` : "pi-evals:這段工作沒有可撤銷的當下標記。");
75
+ return;
76
+ }
77
+ let rule: Rule | undefined;
78
+ let verdict: Verdict | undefined;
79
+ let note: string | undefined;
80
+ if (words.length) {
81
+ rule = RULES.find((r) => r === words[0]);
82
+ verdict = VERDICT_WORDS.get(words[1] ?? "");
83
+ note = words.slice(2).join(" ");
84
+ if (!rule || !verdict) {
85
+ const text = cleanNote(words.join(" "))!;
86
+ waiting = { session: w.session, prompt: promptFor(text), note: text };
87
+ pi.sendUserMessage(waiting.prompt, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
88
+ return say(`pi-evals:已把你的話交給代理人,請它整理成標記${ctx.isIdle() ? "" : "(等目前的工作告一段落)"};它會回報記了什麼,不對就用 /evals label undo 撤銷。`);
89
+ }
90
+ } else {
91
+ if (!ctx.hasUI) return say(USAGE, "warning");
92
+ const cancelled = () => say("pi-evals:已取消,沒有記下標記。");
93
+ const names = RULES.map((r) => ruleLabel(r, "zh"));
94
+ const picked = await ctx.ui.select("要標記哪一條規則?", names);
95
+ rule = RULES[names.indexOf(picked ?? "")];
96
+ if (!rule) return cancelled();
97
+ const verdicts = VERDICTS.map((v) => VERDICT_META[v].zh);
98
+ verdict = VERDICTS[verdicts.indexOf((await ctx.ui.select(`這段工作有照做「${ruleLabel(rule, "zh")}」嗎?`, verdicts)) ?? "")];
99
+ if (!verdict) return cancelled();
100
+ const typed = await ctx.ui.input("補充說明(用你自己的話,可留空,直接按 Enter)", "");
101
+ if (typed === undefined) return cancelled();
102
+ note = typed;
103
+ }
104
+ const row: LabelRow = { session_id: w.session, evaluation_name: rule, label: verdict, at: w.at, annotator: "human", source: "live", item: w.item, project: w.project, note: cleanNote(note) };
105
+ appendLabel(w.file, row);
106
+ say(`pi-evals:已記下「${ruleLabel(rule, "zh")}」${VERDICT_META[verdict].zh}${row.item ? `,進行中的待辦 ${row.item}` : ""}${row.note ? ",附說明" : ""};/evals label undo 可撤銷。`);
107
+ }
108
+
109
+ pi.registerTool({
110
+ name: "evals_label",
111
+ label: "Evals Label",
112
+ description: "Log a user's correction of how you worked: rule broken (or other), type of slip; on_behalf user only in a /evals label turn.",
113
+ promptSnippet: "When the user corrects how you worked (skipped a check, wrong order, ignored a rule), log it once",
114
+ parameters: Type.Object(
115
+ {
116
+ rule: Type.Unsafe<Rule>({ type: "string", enum: [...RULES] }),
117
+ label: Type.Optional(Type.Unsafe<Verdict>({ type: "string", enum: [...VERDICTS] })),
118
+ type: Type.Optional(Type.Unsafe<FailureType>({ type: "string", enum: [...FAILURE_TYPES] })),
119
+ on_behalf: Type.Optional(Type.Unsafe<"user">({ type: "string", enum: ["user"] })),
120
+ },
121
+ { additionalProperties: false },
122
+ ),
123
+ async execute(_id, params, _signal, _onUpdate, ctx) {
124
+ const session = ctx.sessionManager.getSessionId();
125
+ const voice = speaking?.session === session ? speaking : undefined;
126
+ const { rule, label, type, onBehalf } = agentLabel(params, !!voice);
127
+ const w = where(ctx);
128
+ if (onBehalf) {
129
+ // The user's judgement, the agent only formatted it: the note is the user's words, never the agent's.
130
+ appendLabel(w.file, { session_id: w.session, evaluation_name: rule, label, at: w.at, annotator: "human", source: "live-prompt", type, item: w.item, project: w.project, note: voice?.note });
131
+ return { content: [{ type: "text", text: `logged the user's label: ${rule} ${label}${type ? ` (${type})` : ""}` }], details: { rule, label, type, onBehalf } };
132
+ }
133
+ const skills = observed.skills();
134
+ appendLabel(w.file, { session_id: w.session, evaluation_name: rule, label: "fail", at: w.at, annotator: "agent", source: "correction", type, item: w.item, project: w.project, skills: skills.length ? skills : undefined });
135
+ return { content: [{ type: "text", text: `logged correction: ${rule}${type ? ` (${type})` : ""}` }], details: { rule, label, type, onBehalf } };
136
+ },
137
+ });
138
+
139
+ return { command };
140
+ }
package/src/model.ts CHANGED
@@ -2,17 +2,17 @@
2
2
  * The ReportModel: every number the report can show, each with its n and window, plus the plain-language
3
3
  * metadata to explain it. The renderer reads only this; `evals_query` reads parts of it.
4
4
  */
5
- import { existsSync, readFileSync } from "node:fs";
5
+ import { existsSync } from "node:fs";
6
6
  import { ASK_BUCKETS, type DayAgg, emptyDay, mergeDay, type SessionRow } from "./aggregate.ts";
7
7
  import type { DaysIndex } from "./build.ts";
8
- import type { Change } from "./changes.ts";
8
+ import { type Change, versionAt } from "./changes.ts";
9
9
  import type { Coverage } from "./coverage.ts";
10
10
  import { DETECTORS, ERA_START } from "./detectors.ts";
11
11
  import { CHANGE_KIND_META, CLOSE_KIND_META, DETECTOR_META, METRICS, NOTICE_META, STALL_KIND_META } from "./meta.ts";
12
12
  import { staticOwner } from "./owners.ts";
13
13
  import { weeklyRises } from "./trends.ts";
14
- import { traceId } from "./schema.ts";
15
- import type { ItemsFile } from "./work/join.ts";
14
+ import { labelsModel } from "./labels.ts";
15
+ import { ANCHORLOOP, type ItemsFile } from "./work/join.ts";
16
16
  import { workModel } from "./work/model.ts";
17
17
 
18
18
  export const SMALL_SAMPLE = 20;
@@ -171,48 +171,6 @@ export function impactFromRows(rows: SessionRow[], change: Change, all: Change[]
171
171
  };
172
172
  }
173
173
 
174
- interface LabelRow {
175
- session_id: string;
176
- evaluation_name: string;
177
- label: string;
178
- }
179
-
180
- function labelsJoin(labelsFile: string, evalsFile: string, sessionIds?: Set<string>) {
181
- if (!existsSync(labelsFile)) return { present: false, n: 0, unclear: 0, agreement: [] as { detector: string; n: number; agree: number; rate: Rate; unclear: number }[] };
182
- const codeLabels = existsSync(evalsFile) ? (JSON.parse(readFileSync(evalsFile, "utf8")) as Record<string, Record<string, string>>) : {};
183
- const rows: LabelRow[] = readFileSync(labelsFile, "utf8")
184
- .split("\n")
185
- .filter(Boolean)
186
- .flatMap((line) => {
187
- try {
188
- return [JSON.parse(line) as LabelRow];
189
- } catch {
190
- return [];
191
- }
192
- });
193
- const by = new Map<string, { n: number; agree: number; unclear: number }>();
194
- let n = 0;
195
- let unclear = 0;
196
- for (const row of rows) {
197
- if (sessionIds && !sessionIds.has(traceId(row.session_id, "labels"))) continue;
198
- n++;
199
- const t = by.get(row.evaluation_name) ?? { n: 0, agree: 0, unclear: 0 };
200
- // "Cannot tell" is the reader's honest answer, not a disagreement: count it apart from the agreement rate.
201
- if (row.label === "unclear") {
202
- unclear += 1;
203
- t.unclear += 1;
204
- by.set(row.evaluation_name, t);
205
- continue;
206
- }
207
- const code = codeLabels[row.session_id]?.[row.evaluation_name];
208
- if (!code || code === "na") continue;
209
- t.n += 1;
210
- if (code === row.label) t.agree += 1;
211
- by.set(row.evaluation_name, t);
212
- }
213
- return { present: true, n, unclear, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n), unclear: t.unclear })) };
214
- }
215
-
216
174
  export function buildModel(options: {
217
175
  index: DaysIndex;
218
176
  rows: SessionRow[];
@@ -226,6 +184,8 @@ export function buildModel(options: {
226
184
  coverage?: Coverage;
227
185
  /** Joined work items (`index/items.json`), when built. */
228
186
  work?: ItemsFile;
187
+ /** The user gave no end date: labels of sessions not indexed yet are not cut at `filter.until`. */
188
+ openEnd?: boolean;
229
189
  now?: Date;
230
190
  }) {
231
191
  const { index, filter } = options;
@@ -256,6 +216,7 @@ export function buildModel(options: {
256
216
  const scoped = Boolean(filter.since || filter.until || filter.project);
257
217
  const hasSessionIds = selected.every(r => r.id !== undefined);
258
218
  const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
219
+ const indexedIds = labelIds && new Set(options.rows.flatMap(r => r.id ? [r.id] : []));
259
220
  const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
260
221
  const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
261
222
  const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
@@ -362,7 +323,10 @@ export function buildModel(options: {
362
323
  changes: options.comparisons?.filter(c => inRange(c.at)) ?? sortedChanges
363
324
  .filter((c) => inRange(c.at))
364
325
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
365
- labels: { ...labelsJoin(options.labelsFile, options.sessionEvalsFile, labelIds), needsIndex: !!labelIds && !hasSessionIds },
326
+ labels: {
327
+ ...labelsModel(options.labelsFile, options.sessionEvalsFile, { ...filter, until: options.openEnd ? undefined : filter.until, selected: labelIds, indexed: indexedIds }, (at) => versionAt(sortedChanges, ANCHORLOOP, at)),
328
+ needsIndex: !!labelIds && !hasSessionIds,
329
+ },
366
330
  coverage: options.coverage ?? null,
367
331
  work: workModel(options.work, filter),
368
332
  };
package/src/observer.ts CHANGED
@@ -8,7 +8,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
8
8
  import type { Layout } from "./paths.ts";
9
9
  import { ownerOf } from "./owners.ts";
10
10
  import { projectKey } from "./project.ts";
11
- import { type Attrs, type EvalRecord, NAMES, record, type SkillTrigger, spanId, traceId } from "./schema.ts";
11
+ import { type Attrs, type EvalRecord, NAMES, record, safeName, type SkillTrigger, spanId, traceId } from "./schema.ts";
12
12
  import { skillFromPath, skillsFromBlocks, skillsFromCommand } from "./skills.ts";
13
13
  import { liveWriter } from "./store.ts";
14
14
  import { logicalIdOf } from "./extract/session.ts";
@@ -30,7 +30,12 @@ export interface ObserverOptions {
30
30
  now?: () => number;
31
31
  }
32
32
 
33
- export function observe(pi: ExtensionAPI, options: ObserverOptions): void {
33
+ /** What the session has done so far that a label needs: the skills it loaded. */
34
+ export interface Observed {
35
+ skills(): string[];
36
+ }
37
+
38
+ export function observe(pi: ExtensionAPI, options: ObserverOptions): Observed {
34
39
  const now = options.now ?? Date.now;
35
40
  let sessionId = "";
36
41
  let project = "unknown";
@@ -44,13 +49,16 @@ export function observe(pi: ExtensionAPI, options: ObserverOptions): void {
44
49
  let unsubscribe: (() => void)[] = [];
45
50
  let write: (r: EvalRecord | EvalRecord[]) => void = () => {};
46
51
  let hasUI = false;
52
+ let loaded = new Set<string>();
47
53
 
48
54
  const iso = (t: number) => new Date(t).toISOString();
49
55
  const base = (): Attrs => ({ "session.id": sessionId, "pi.project": project });
50
56
  const emit = (fields: Parameters<typeof record>[0]) => write(record(fields));
51
57
 
52
- const skillLoad = (skill: string, trigger: SkillTrigger, callId?: string) =>
58
+ const skillLoad = (skill: string, trigger: SkillTrigger, callId?: string) => {
59
+ loaded.add(skill);
53
60
  emit({ name: NAMES.skill, kind: "event", ts: iso(now()), source: "live", trace_id: trace, attrs: { ...base(), "gen_ai.skill.name": skill, "pi.skill.trigger": trigger, "gen_ai.tool.call.id": callId } });
61
+ };
54
62
 
55
63
  const snapshot = () => {
56
64
  if (snapshotTaken) return;
@@ -113,6 +121,7 @@ export function observe(pi: ExtensionAPI, options: ObserverOptions): void {
113
121
  remoteAnswers = new Set();
114
122
  monitorStarts = new Map();
115
123
  monitorsDone = new Set();
124
+ loaded = new Set();
116
125
  let file: string | undefined;
117
126
  try {
118
127
  file = ctx.sessionManager.getSessionFile?.();
@@ -252,4 +261,5 @@ export function observe(pi: ExtensionAPI, options: ObserverOptions): void {
252
261
  attrs,
253
262
  });
254
263
  });
264
+ return { skills: () => [...new Set([...loaded].map((name) => safeName(name)))].filter((n) => n !== "redacted").sort() };
255
265
  }
package/src/ops.ts CHANGED
@@ -78,7 +78,8 @@ function snapshot(env?: Env, withCoverage = true) {
78
78
  const cov = withCoverage ? coverageReader(ctx, now) : undefined;
79
79
  return { index, build(input: RangeInput, preset: Preset, comparisons?: ReportModel["changes"]) {
80
80
  const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
81
- return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
81
+ // A range ends at the last extract unless the user ends it; a label given since then has no session in the index yet.
82
+ return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays, openEnd: input.until === undefined,
82
83
  labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
83
84
  } };
84
85
  }
package/src/query.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /** `evals_query`: bounded plain-text summaries of the index for an agent (names and numbers only, under 2 KB). */
2
2
  import { coverageInRange, indexedModel, reportPath } from "./ops.ts";
3
3
  import { findings } from "./findings.ts";
4
+ import { labelsView } from "./labels-query.ts";
4
5
  import { select } from "./report/findings.ts";
5
6
  import type { Rate } from "./model.ts";
6
7
  import { itemsView } from "./work/query.ts";
7
8
 
8
- export const VIEWS = ["findings", "items", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
9
+ export const VIEWS = ["findings", "items", "labels", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
9
10
  export type View = (typeof VIEWS)[number];
10
11
  export const MAX_BYTES = 1900;
11
12
 
@@ -88,6 +89,8 @@ export function query(view: View, options: { since?: string; days?: number; proj
88
89
  for (const s of m.cost.bySkill.slice(0, 10)) body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
89
90
  } else if (view === "items") {
90
91
  body.push(...itemsView(m.work));
92
+ } else if (view === "labels") {
93
+ body.push(...labelsView(m));
91
94
  } else if (view === "changes") {
92
95
  body.push("highlighted then newest changes, sessions split at the change time, metric before -> after; flags: small = <20 sessions a side, incomplete = a window runs past the data, confounded = other commits nearby");
93
96
  const { highlighted, folded } = select(m);
package/src/render.ts CHANGED
@@ -31,6 +31,7 @@ export function renderHtml(m: ReportModel, lang: Lang = "zh", range: Preset | "c
31
31
  ["cost", L("Cost", "費用")],
32
32
  ["coverage", L("Cleanup", "清理門檻")],
33
33
  ["labels", L("Labels", "你的標記")],
34
+ ["corrections", L("Corrections", "被糾正")],
34
35
  ["concepts", L("Concepts", "概念")],
35
36
  ];
36
37
  const date = m.generated.slice(0, 10);
@@ -30,6 +30,23 @@ function workCards(m: ReportModel, L: Words) {
30
30
  };
31
31
  }
32
32
 
33
+ /** When a label was given, with this report's numbers. */
34
+ function labelTiming(m: ReportModel, L: Words) {
35
+ const l = m.labels, name = (d: string) => m.meta.detectors[d]?.label[L("en", "zh") as "en" | "zh"] ?? d;
36
+ const pairs = l.agreement.filter((r) => r.bySource.batch.n).map((r) => [name(r.detector), `${num(r.bySource.batch.agree)}/${num(r.bySource.batch.n)}`]);
37
+ const en = pairs.map(([d, v]) => `${v} on "${d}"`).join(", "), zh = pairs.map(([d, v]) => `「${d}」${v}`).join("、");
38
+ const fact = l.sessions.batch
39
+ ? L(`So far ${num(l.sessions.batch)} sessions were labelled after the fact; the code agreed with you ${en || "on none that it judged"}.`, `目前事後標了 ${num(l.sessions.batch)} 段工作,程式和你一致的有:${zh || "沒有程式判斷可比"}。`)
40
+ : L("No sessions were labelled after the fact yet.", "目前還沒有事後標記。");
41
+ return [
42
+ L("Labelled in the moment vs after the fact", "當下標記 vs 事後標記"),
43
+ L(
44
+ `After the fact means judging later from a summary an AI wrote; in the moment means judging with /evals label while the work is in front of you. ${fact} A summary leaves things out, so when agreement is low it may be the summary or the code; labels after the fact alone cannot tell which. In-the-moment labels so far: ${num(l.bySource.live)}. Once each kind has at least 20, comparing their agreement shows where the gap comes from.`,
45
+ `事後標記是事情過了,讀 AI 寫的摘要再判斷;當下標記是工作還在眼前時,用 /evals label 直接判斷。${fact}摘要會漏掉細節,所以一致比例偏低時,可能是摘要沒寫清楚,也可能是程式判斷錯了,只看事後標記分不出來。當下標記目前 ${num(l.bySource.live)} 筆;兩種各累積到至少 20 筆,比較兩邊的一致比例,才看得出落差從哪裡來。`,
46
+ ),
47
+ ];
48
+ }
49
+
33
50
  export function concepts(m: ReportModel, week: Week, c: Change | undefined, L: Words) {
34
51
  const i = c?.impact,
35
52
  n = num(week.reduce((s, r) => s + r.sessions, 0)),
@@ -82,6 +99,7 @@ export function concepts(m: ReportModel, week: Week, c: Change | undefined, L: W
82
99
  ),
83
100
  ],
84
101
  ...workCards(m, L),
102
+ labelTiming: labelTiming(m, L),
85
103
  check: [
86
104
  L("Code check", "程式檢查"),
87
105
  L(