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.
@@ -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/meta.ts CHANGED
@@ -248,7 +248,10 @@ export const DETECTOR_META: Record<string, DetectorMeta> = {
248
248
  label: t("Said how to check before editing", "動手前先說好怎麼驗證"),
249
249
  meaning: t("The agent named the check that proves the work (its Anchor) before changing any file.", "代理人在改任何檔案前,先說出用什麼檢查證明工作完成(Anchor)。"),
250
250
  goodDirection: "higher",
251
- howComputed: t("Passes when an Anchor line or a todo anchor appears before the first successful edit or write; sessions without edits do not count.", "第一次成功修改或寫檔之前出現 Anchor 行或待辦的 anchor 即通過;沒改檔的工作階段不算。"),
251
+ howComputed: t(
252
+ "Passes when, before the first successful edit or write, the agent or its brief named the check (an Anchor, Gates, Checks or 驗證 line, a todo anchor or check spec, or a check command in the brief), or the first change was a test file; sessions without edits do not count.",
253
+ "第一次成功修改或寫檔之前,代理人或交辦內容已說出檢查(Anchor、Gates、Checks、驗證 等標示行,待辦的 anchor 或檢查設定,或交辦內容裡的檢查指令),或第一個修改的就是測試檔,即通過;沒改檔的工作階段不算。",
254
+ ),
252
255
  example: {
253
256
  pass: t("Writes 'Anchor: `npm test`', then edits src/app.ts.", "先寫「Anchor: `npm test`」,再修改 src/app.ts。"),
254
257
  fail: t("Edits src/app.ts first and names the check afterwards.", "先修改 src/app.ts,之後才說要怎麼檢查。"),
@@ -258,7 +261,10 @@ export const DETECTOR_META: Record<string, DetectorMeta> = {
258
261
  label: t("Ran the check after the last edit", "最後一次修改後有跑檢查"),
259
262
  meaning: t("After its final change, the agent ran the check it named and the check passed.", "最後一次修改後,代理人有跑它說好的檢查,而且通過。"),
260
263
  goodDirection: "higher",
261
- howComputed: t("Passes when every command in the Anchor has a passing run after the last edit; sessions with no edit or no runnable Anchor do not count.", "Anchor 裡每個指令在最後一次修改後都有通過的執行即通過;沒改檔或 Anchor 不是可執行指令的不算。"),
264
+ howComputed: t(
265
+ "Passes when, after the last edit, every Anchor command passed (in bash or a monitor), the agent recorded passing evidence, or a test, build, lint or type-check run passed; a failing Anchor run fails it. Edits to Markdown or text after the check do not count as edits. Sessions with no edit, only prose edits, or an Anchor that is not a command and no run do not count.",
266
+ "最後一次修改後,Anchor 每個指令都通過(bash 或 monitor),或代理人記下通過的證據,或有測試、建置、lint、型別檢查通過,即通過;Anchor 指令失敗則不通過。檢查之後才改的 Markdown 或文字檔不算修改。沒改檔、只改文字,或 Anchor 不是指令又沒有執行的不算。",
267
+ ),
262
268
  example: {
263
269
  pass: t("Edits a file, then runs `npm test`, which exits 0.", "改完檔案後執行 `npm test`,結束碼 0。"),
264
270
  fail: t("Runs `npm test`, edits one more file, and stops.", "跑完 `npm test` 又改了一個檔案就結束。"),
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(
@@ -1,4 +1,5 @@
1
- import type { ReportModel } from "../model.ts";
1
+ import { FAILURE_TYPE_META, type FailureType, ruleLabel } from "../labels.ts";
2
+ import { type ReportModel, SMALL_SAMPLE } from "../model.ts";
2
3
  import { type concepts, lesson, selfCheck } from "./concepts.ts";
3
4
  import { duration, esc, type Lang, num, pct, table, usd, words } from "./format.ts";
4
5
  import { workSection } from "./work.ts";
@@ -151,21 +152,52 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
151
152
  } bytes</p>`
152
153
  : `<p>${L("Coverage not measured; keep cleanup off.", "沒有索引覆蓋資料,請勿開啟清理。")}</p>`,
153
154
  );
155
+ const lb = m.labels, rule = (r: string) => ruleLabel(r, lang);
156
+ const pair = (c: { agree: number; n: number }) => (c.n ? `${num(c.agree)} / ${num(c.n)}` : "—");
154
157
  const labels = section(
155
158
  "labels",
156
159
  L("Your labels", "你的標記"),
157
160
  meta.agreement.meaning[lang],
158
- m.labels.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : m.labels.present && m.labels.n
159
- ? T(
160
- [L("Check", "檢查"), L("Labelled", "已標記"), L("Agreement", "一致比例"), L("Cannot tell", "看不出來")],
161
- m.labels.agreement.map((r) => [m.meta.detectors[r.detector]?.label[lang] ?? r.detector, r.n, pct(r.rate), r.unclear]),
162
- ) + `<p class="muted">${L(`Cannot tell ${num(m.labels.unclear)}: labels marked unclear are left out of the agreement rate.`, `看不出來 ${num(m.labels.unclear)}:標成「看不出來」的不算進一致比例。`)}</p>`
161
+ lb.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : lb.present && lb.n
162
+ ? `<p>${L(`After the fact ${num(lb.bySource.batch)} (${num(lb.sessions.batch)} sessions) / In the moment ${num(lb.bySource.live)} (${num(lb.sessions.live)} sessions)`, `事後標 ${num(lb.bySource.batch)} 筆(${num(lb.sessions.batch)} 段工作) / 當下標 ${num(lb.bySource.live)} 筆(${num(lb.sessions.live)} 段工作)`)}${
163
+ lb.fromWords ? L(`; ${num(lb.fromWords)} of them the agent wrote from your words`, `;其中 ${num(lb.fromWords)} 筆是代理人依你的話整理的`) : ""
164
+ }</p>` +
165
+ T(
166
+ [L("Check", "檢查"), L("Agreement", "一致比例"), L("After the fact: agreed / compared", "事後標:一致 / 比對"), L("In the moment: agreed / compared", "當下標:一致 / 比對"), L("Cannot tell", "看不出來")],
167
+ lb.agreement.map((r) => [rule(r.detector), `${pct(r.rate)}(${num(r.n)})`, pair(r.bySource.batch), pair(r.bySource.live), r.unclear]),
168
+ ) +
169
+ `<p class="muted">${L(`Cannot tell ${num(lb.unclear)}: labels marked unclear are left out of the agreement rate.`, `看不出來 ${num(lb.unclear)}:標成「看不出來」的不算進一致比例。`)}${
170
+ lb.noCode ? L(` ${num(lb.noCode)} labels have no code verdict to compare: the session is not extracted yet (run /evals extract), or the rule did not apply to it.`, `另有 ${num(lb.noCode)} 筆沒有程式判斷可比:那段工作還沒整理(執行 /evals extract 後就能比),或這條規則不適用於它。`) : ""
171
+ }${lb.other ? L(` ${num(lb.other)} labels are on "Other", which no code check covers.`, `${num(lb.other)} 筆標在「其他」,沒有程式檢查可比。`) : ""}</p>` + lesson(cards.labelTiming, L)
163
172
  : `<p>${
164
173
  L(
165
- "No labels yet. In phase 2 you will judge sessions yourself and compare your answers with the code checks.",
166
- "還沒有標記。第二階段會讓你親自判讀工作紀錄,再對照程式與你的判斷是否一致。",
174
+ "No labels yet. Type /evals label in any session to say, while the work is in front of you, whether the agent followed a rule.",
175
+ "還沒有標記。在任何工作階段輸入 /evals label,就能趁工作還在眼前,標記代理人有沒有照規則做。",
176
+ )
177
+ }</p>` + lesson(cards.labelTiming, L),
178
+ );
179
+ const c = lb.corrections, few = c.n < SMALL_SAMPLE;
180
+ const corrections = section(
181
+ "corrections",
182
+ L("Times the agent was corrected", "被糾正"),
183
+ L(
184
+ "When you correct how the agent worked, it logs one line with evals_label. This counts the corrections it logged, not all its mistakes: a slip nobody caught, or one it forgot to log, is not here.",
185
+ "你糾正代理人的做法時,它會用 evals_label 自己記一筆。這裡數的是它記下的被糾正次數,不是所有錯誤:沒人發現、沒被糾正,或它忘了記的,都不在這裡。",
186
+ ),
187
+ c.n
188
+ ? `<p class="big">${num(c.n)} <small>${L("corrections", "次")} · ${num(c.sessions)} ${L("sessions", "段工作")}</small></p>${
189
+ few ? `<p class="stale">${L(`Only ${num(c.n)}: too few to show a trend. Read it as a hint of where slips may recur.`, `只有 ${num(c.n)} 次,太少,看不出趨勢;只能當提醒,看哪裡可能常出錯。`)}</p>` : ""
190
+ }<div class="pair"><article class="panel"><h3>${L("By rule", "依規則")}</h3>${T([L("Rule", "規則"), L("Times", "次數")], c.byRule.map((r) => [rule(r.rule), r.n]))}</article><article class="panel"><h3>${L("By kind of slip", "依錯誤類型")}</h3>${
191
+ T([L("Kind", "類型"), L("Times", "次數")], c.byType.map((r) => [FAILURE_TYPE_META[r.type as FailureType]?.[lang] ?? r.type, r.n]))
192
+ }</article></div>` +
193
+ more(
194
+ L("By skill loaded and by anchorloop version", "依載入的技能、anchorloop 版本"),
195
+ `<p class="muted">${L("Skills the session had loaded before the correction. One correction counts for each of them; this does not mean the skill caused it.", "被糾正時這段工作已載入的技能。一次糾正會算進每個已載入的技能,不代表是技能造成的。")}</p>` +
196
+ T([L("Skill", "技能"), L("Times", "次數"), L("Sessions", "工作段數")], c.bySkill.map((r) => [r.skill || L("(none loaded)", "(沒載入技能)"), r.n, r.sessions])) +
197
+ `<p class="muted">${L("The anchorloop version in use when the correction was logged.", "依糾正當時使用的 anchorloop 版本。")}</p>` +
198
+ T([L("Version", "版本"), L("Times", "次數"), L("Sessions", "工作段數")], c.byVersion.map((r) => [r.version === "unknown" ? L("unknown", "不明") : r.version, r.n, r.sessions])),
167
199
  )
168
- }</p>`,
200
+ : `<p>${L("None logged in this period. When you correct the agent, it logs one line here.", "這段期間沒有紀錄。你糾正代理人時,它會在這裡記一筆。")}</p>`,
169
201
  );
170
202
  return [
171
203
  workSection(m, lang, cards, lesson),
@@ -178,6 +210,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
178
210
  cost,
179
211
  coverage,
180
212
  labels,
213
+ corrections,
181
214
  section(
182
215
  "concepts",
183
216
  L("Concepts", "概念"),
package/src/work/track.ts CHANGED
@@ -142,6 +142,15 @@ function liteOf(raw: unknown): TaskLite | undefined {
142
142
  };
143
143
  }
144
144
 
145
+ /** A task's own key: its uid, else `<origin session>#<id>` for a task handed over from another session. */
146
+ const ownKey = (task: TaskLite) => task.uid ?? (task.origin ? `${task.origin}#${task.id}` : undefined);
147
+
148
+ /** The key of the task in progress in a live todo list, as the back-fill keys it on the session's main branch. */
149
+ export function liveItemKey(tasks: readonly unknown[], session: string): string | undefined {
150
+ const task = tasks.map(liteOf).find((x) => x?.status === "in_progress");
151
+ return task && (ownKey(task) ?? `${session}#${task.id}`);
152
+ }
153
+
145
154
  /** The kind of stall a waking entry ends, or undefined when the entry does not start a turn. */
146
155
  export function wakeOf(entry: Obj): { kind: StallKind; on?: string } | undefined {
147
156
  const type = entry.type;
@@ -346,8 +355,8 @@ export class WorkTracker {
346
355
 
347
356
  private newItem(session: string, nested: boolean, task: TaskLite, snap: Snapshot, si: number, main: Set<number>, reuse: Map<number, number>): ItemRaw {
348
357
  let key: string;
349
- if (task.uid) key = task.uid;
350
- else if (task.origin) key = `${task.origin}#${task.id}`;
358
+ const own = ownKey(task);
359
+ if (own) key = own;
351
360
  else if (main.has(si)) {
352
361
  const count = (reuse.get(task.id) ?? 0) + 1;
353
362
  reuse.set(task.id, count);