pi-evals 0.3.0 → 0.4.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +7 -3
  3. package/dist/build.js +10 -1
  4. package/dist/extract/run.js +1 -1
  5. package/dist/extract/session.js +43 -3
  6. package/dist/findings.js +4 -0
  7. package/dist/meta.js +43 -1
  8. package/dist/model.js +15 -5
  9. package/dist/ops.js +3 -2
  10. package/dist/paths.js +3 -0
  11. package/dist/query.js +5 -1
  12. package/dist/render.js +1 -0
  13. package/dist/report/concepts.js +23 -1
  14. package/dist/report/sections.js +4 -2
  15. package/dist/report/style.js +5 -0
  16. package/dist/report/work.js +47 -0
  17. package/dist/schema.js +16 -1
  18. package/dist/work/join.js +429 -0
  19. package/dist/work/model.js +145 -0
  20. package/dist/work/query.js +51 -0
  21. package/dist/work/sb.js +131 -0
  22. package/dist/work/track.js +323 -0
  23. package/dist/work/wording.js +27 -0
  24. package/docs/schema.md +8 -2
  25. package/package.json +1 -1
  26. package/skills/analyzing-evals/SKILL.md +3 -1
  27. package/src/aggregate.ts +11 -2
  28. package/src/build.ts +9 -1
  29. package/src/extract/run.ts +1 -1
  30. package/src/extract/session.ts +36 -2
  31. package/src/findings.ts +3 -0
  32. package/src/meta.ts +45 -1
  33. package/src/model.ts +19 -6
  34. package/src/ops.ts +3 -2
  35. package/src/paths.ts +7 -0
  36. package/src/query.ts +4 -1
  37. package/src/render.ts +1 -0
  38. package/src/report/concepts.ts +30 -1
  39. package/src/report/sections.ts +6 -4
  40. package/src/report/style.ts +5 -0
  41. package/src/report/work.ts +76 -0
  42. package/src/schema.ts +16 -1
  43. package/src/work/join.ts +476 -0
  44. package/src/work/model.ts +179 -0
  45. package/src/work/query.ts +48 -0
  46. package/src/work/sb.ts +158 -0
  47. package/src/work/track.ts +397 -0
  48. package/src/work/wording.ts +26 -0
@@ -10,10 +10,15 @@ import { dayOf } from "../paths.ts";
10
10
  import { projectKey } from "../project.ts";
11
11
  import { type Attrs, type EvalRecord, NAMES, record, safeName, type SkillTrigger, spanId, traceId } from "../schema.ts";
12
12
  import { skillFromPath, skillsFromBlocks, skillsFromCatalog, skillsFromCommand } from "../skills.ts";
13
+ import { WorkTracker } from "../work/track.ts";
13
14
 
14
15
  const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
15
16
  const CHILD_FILE = new RegExp(`_(${UUID})-[0-9a-f]{8}-[0-9a-f]{8}-[0-9a-f]{4}\\.jsonl$`);
16
17
  const BRIEF_PARENT = new RegExp(`/artifacts/(${UUID})/context/`);
18
+ /** The subagent name in a brief path `…/context/<name>-<YYYY-MM-DDTHH-MM-SS>.md`. */
19
+ const BRIEF_NAME = new RegExp(`/artifacts/${UUID}/context/([A-Za-z0-9_.-]+?)-\\d{4}-\\d{2}-\\d{2}T[0-9-]+\\.md`);
20
+ /** Question tools: the main waits on a person while one runs. */
21
+ const HUMAN_WAIT = new Set(["ask_user_question", "ask_user", "secret_drop"]);
17
22
  const ASK_TOOLS = new Set(["ask_user_question", "ask_user"]);
18
23
 
19
24
  interface PendingCall {
@@ -63,6 +68,9 @@ export class SessionReader {
63
68
  private notices: SessionSummary["notices"] = {};
64
69
  private firstUser = true;
65
70
  private model?: string;
71
+ private childName?: string;
72
+ private cwd?: string;
73
+ private work = new WorkTracker();
66
74
  readonly logicalId?: string;
67
75
  private readonly home: string;
68
76
  private readonly emit: (r: EvalRecord) => void;
@@ -101,6 +109,7 @@ export class SessionReader {
101
109
  if (type === "session") return this.header(entry);
102
110
  if (!this.start && ts) this.start = ts;
103
111
  const kind = this.tracker.feed(entry);
112
+ this.work.entry(entry, ts);
104
113
  if (type === "model_change") {
105
114
  this.model = safeName(`${str(entry.provider) ?? "?"}/${str(entry.modelId) ?? "?"}`);
106
115
  } else if (type === "compaction") {
@@ -122,6 +131,8 @@ export class SessionReader {
122
131
  this.sessionId = safeName(str(entry.id) ?? "");
123
132
  this.start = str(entry.timestamp) ?? this.start;
124
133
  this.project = safeName(projectKey(str(entry.cwd), this.home));
134
+ const cwd = str(entry.cwd);
135
+ if (cwd && safeName(cwd) === cwd) this.cwd = cwd;
125
136
  }
126
137
 
127
138
  private system(message: Obj) {
@@ -134,8 +145,11 @@ export class SessionReader {
134
145
  const text = textOf(message.content);
135
146
  if (this.firstUser) {
136
147
  this.firstUser = false;
137
- const parent = text.slice(0, 2000).match(BRIEF_PARENT)?.[1];
148
+ const head = text.slice(0, 2000);
149
+ const parent = head.match(BRIEF_PARENT)?.[1];
138
150
  if (parent && this.logicalId) this.parentId = parent;
151
+ const name = head.match(BRIEF_NAME)?.[1];
152
+ if (name && this.logicalId) this.childName = safeName(name);
139
153
  }
140
154
  const anchor = str(entry.id) ?? ts;
141
155
  this.closeTrace();
@@ -188,6 +202,7 @@ export class SessionReader {
188
202
  day.usage.calls += 1;
189
203
  bump(day.models, model);
190
204
  this.cost += u.cost;
205
+ this.work.assistant(ts, u.cost, message.stopReason);
191
206
  this.tokens += num(usage.totalTokens) || u.input + u.output + u.cacheRead + u.cacheWrite;
192
207
  if (this.traceUsage) {
193
208
  this.traceUsage.input += u.input;
@@ -257,8 +272,20 @@ export class SessionReader {
257
272
  attrs["gen_ai.request.model"] = model;
258
273
  attrs["pi.subagent.logical_id"] = child;
259
274
  bump(day.subagents, `${role}|${model}`);
260
- if (child) this.spawned.push({ id: child, role, model });
275
+ if (child) {
276
+ const name = str(details.name) ? safeName(details.name) : undefined;
277
+ const item = str(details.item) ? safeName(details.item) : undefined;
278
+ this.spawned.push({ id: child, role, model, name });
279
+ this.work.launch({ id: child, name, role, model, item, at: ts });
280
+ }
281
+ }
282
+ if (!isError && call && HUMAN_WAIT.has(name)) this.work.wait(call.ts, ts, "human");
283
+ if (!isError && name === "subagent_resume" && str(details.name)) this.work.child(ts, String(details.name), "resume");
284
+ if (!isError && name === "boss_pair" && str(details.thread)) {
285
+ const opt = (v: unknown) => (str(v) ? safeName(v) : undefined);
286
+ this.work.pair({ thread: safeName(details.thread), worker: opt(details.worker), reviewer: opt(details.reviewer), item: opt(details.item), at: ts });
261
287
  }
288
+ if (!isError && name === "boss_wrap") this.work.wrap(ts, details.wrapped === true);
262
289
  if (call?.monitor && !isError) {
263
290
  const monitorId = textOf(message.content).concat(" ", str(details.summary) ?? "").match(/Monitor #(\d+)/)?.[1];
264
291
  day.monitors.started += 1;
@@ -300,6 +327,8 @@ export class SessionReader {
300
327
  const type = entry.customType;
301
328
  if (type === "pi-herdr-agents:declared-skills") {
302
329
  for (const skill of skillsFromBlocks(textOf(entry.content))) this.skillLoad(skill, "declared", ts);
330
+ } else if (type === "subagent_result" && str(obj(entry.details).name)) {
331
+ this.work.child(ts, String(obj(entry.details).name), "result");
303
332
  } else if (kind) {
304
333
  bump(this.notices as Record<string, number>, kind);
305
334
  bump(this.day(ts).notices, kind);
@@ -417,6 +446,9 @@ export class SessionReader {
417
446
  kind: this.logicalId ? "subagent" : "interactive",
418
447
  logicalId: this.logicalId,
419
448
  parentId: this.parentId,
449
+ model: this.model,
450
+ childName: this.childName,
451
+ cwd: this.cwd,
420
452
  spawned: this.spawned,
421
453
  cost: this.cost,
422
454
  tokens: this.tokens,
@@ -425,6 +457,8 @@ export class SessionReader {
425
457
  notices: this.notices,
426
458
  days: this.days,
427
459
  };
460
+ const work = this.work.finish(this.sessionId, !!this.logicalId);
461
+ if (work) summary.work = work;
428
462
  return { summary, catalog: this.catalog };
429
463
  }
430
464
  }
package/src/findings.ts CHANGED
@@ -4,6 +4,7 @@ import { overview, readings, value, verdict } from "./report/findings.ts";
4
4
  import { words } from "./report/format.ts";
5
5
  import { safeName } from "./schema.ts";
6
6
  import { trendPair } from "./trends.ts";
7
+ import { itemsFinding } from "./work/query.ts";
7
8
 
8
9
  export const scriptsDir = fileURLToPath(new URL("../scripts", import.meta.url));
9
10
 
@@ -35,6 +36,8 @@ export function findings(m: ReportModel) {
35
36
  const gate = !cov ? "not measured" : !cov.old.files ? "no old files" : cov.notIndexed.files || cov.notIndexed.bytes
36
37
  ? `blocked: ${cov.notIndexed.files}/${cov.old.files} old files not indexed` : `all ${cov.old.files} old files indexed`;
37
38
  lines.push(`Cleanup (all projects/dates): ${gate} → coverage`);
39
+ const work = itemsFinding(m.work);
40
+ if (work) lines.push(work);
38
41
  const w = m.weekly;
39
42
  if (!w) lines.push("Need two weeks in range for error trends → packages / monitors");
40
43
  else {
package/src/meta.ts CHANGED
@@ -165,7 +165,7 @@ export const METRICS: Record<string, MetricMeta> = {
165
165
  label: t("Your verdict matches the automatic check", "你的判斷與自動檢查一致"),
166
166
  meaning: t("How far the automatic check can be trusted: it is the share of sessions you labelled where you and it gave the same verdict.", "自動檢查有多可信:在你標記過的工作階段中,你和它判斷相同的比例。"),
167
167
  goodDirection: "higher",
168
- howComputed: t("Sessions where your label equals the check's label, divided by sessions you labelled for that check.", "你的標記與檢查結果相同的工作階段數,除以你為該檢查標記的工作階段數。"),
168
+ howComputed: t("Sessions where your label equals the check's label, divided by sessions you labelled pass or fail for that check; labels marked unclear are counted apart.", "你的標記與檢查結果相同的工作階段數,除以你為該檢查標成通過或未通過的工作階段數;標成「看不出來」的另外計數。"),
169
169
  },
170
170
  coverage: {
171
171
  label: t("Old sessions already indexed", "已建索引的舊工作階段"),
@@ -197,6 +197,50 @@ export const METRICS: Record<string, MetricMeta> = {
197
197
  goodDirection: "none",
198
198
  howComputed: t("Set when the window before starts before the first session or the window after ends after the last extract; the days with data on each side are shown.", "變更前的期間早於第一個工作階段、或變更後的期間晚於上次抽取時標記;並列出兩邊各有資料的天數。"),
199
199
  },
200
+ item_cost: {
201
+ label: t("Cost of a work item", "一項工作的花費"),
202
+ meaning: t("What one todo item cost from start to close: the subagents that worked on it plus its share of the main agent.", "一項待辦從開始到收尾花了多少:做它的子代理,加上主代理分給它的部分。"),
203
+ goodDirection: "lower",
204
+ howComputed: t("Child cost is exact (every reply of each joined subagent session added up); main cost is the main's replies while the item was in progress, each split evenly among the items in progress at that moment.", "子代理費用是精確的(每個對到的子代理工作階段,每次回覆的費用加總);主代理費用取這項工作進行中時主代理的每次回覆,平均分給當下所有進行中的工作。"),
205
+ },
206
+ item_minutes: {
207
+ label: t("Minutes in progress", "進行中的分鐘數"),
208
+ meaning: t("How long the item was marked in progress; queue time before it started is not counted.", "這項工作標成「進行中」的時間;開始前排隊等待的時間不算。"),
209
+ goodDirection: "none",
210
+ howComputed: t("From each switch to in_progress to the next switch away from it, added up.", "每次切到「進行中」到下一次離開它的時間,加總。"),
211
+ },
212
+ item_stall: {
213
+ label: t("Stall time", "停頓時間"),
214
+ meaning: t("Time inside an item's window when the main agent sat idle for two minutes or more, by what woke it.", "工作進行中,主代理閒著超過兩分鐘的時間,依叫醒它的是誰分類。"),
215
+ goodDirection: "lower",
216
+ howComputed: t("A stall starts when the main ends a turn (or asks you a question) and ends at the next prompt, peer message, subagent result, timer or job ending; gaps under two minutes are left out.", "主代理結束一輪(或開始問你問題)時開始,下一個提示、其他工作階段的訊息、子代理結果、排程或背景工作結束時結束;少於兩分鐘不算。"),
217
+ },
218
+ item_per_100_lines: {
219
+ label: t("Cost per 100 changed lines", "每百行改動的花費"),
220
+ meaning: t("Cost scaled by the size of the change, so a big item and a small one can be compared.", "把花費除以改動大小,大工作和小工作才比得起來。"),
221
+ goodDirection: "lower",
222
+ howComputed: t("Item cost divided by added plus deleted lines (git) from the previous item's last evidence commit to this item's last, times 100; only items whose evidence names commits.", "工作花費除以從上一項工作最後的證據提交到這項最後的證據提交之間,git 增刪的行數,再乘 100;只算證據有記提交的工作。"),
223
+ },
224
+ };
225
+
226
+ export const CLOSE_KIND_META: Record<string, Text> = {
227
+ review_done: t("Reviewer approved", "審查通過"),
228
+ landed: t("Car landed", "車已進站(合併)"),
229
+ wrap: t("Closed at a wrap", "收工時結束"),
230
+ evidence: t("Done with evidence", "附證據完成"),
231
+ unproven: t("Marked done, no evidence", "標完成,沒附證據"),
232
+ deleted: t("Deleted", "刪除"),
233
+ open: t("Still open", "還開著"),
234
+ };
235
+
236
+ export const STALL_KIND_META: Record<string, Text> = {
237
+ human: t("waiting for you", "等你"),
238
+ peer: t("waiting for another session", "等其他工作階段"),
239
+ child: t("waiting for a subagent", "等子代理"),
240
+ timer: t("waiting for a timer", "等排程喚醒"),
241
+ ci: t("waiting for a background job", "等背景工作"),
242
+ device: t("waiting for another device", "等其他裝置"),
243
+ working: t("still working (never stopped)", "還在做(沒停下來)"),
200
244
  };
201
245
 
202
246
  export const DETECTOR_META: Record<string, DetectorMeta> = {
package/src/model.ts CHANGED
@@ -8,10 +8,12 @@ import type { DaysIndex } from "./build.ts";
8
8
  import type { Change } from "./changes.ts";
9
9
  import type { Coverage } from "./coverage.ts";
10
10
  import { DETECTORS, ERA_START } from "./detectors.ts";
11
- import { CHANGE_KIND_META, DETECTOR_META, METRICS, NOTICE_META } from "./meta.ts";
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
14
  import { traceId } from "./schema.ts";
15
+ import type { ItemsFile } from "./work/join.ts";
16
+ import { workModel } from "./work/model.ts";
15
17
 
16
18
  export const SMALL_SAMPLE = 20;
17
19
  /** Data older than this (hours) is reported as stale. */
@@ -176,7 +178,7 @@ interface LabelRow {
176
178
  }
177
179
 
178
180
  function labelsJoin(labelsFile: string, evalsFile: string, sessionIds?: Set<string>) {
179
- if (!existsSync(labelsFile)) return { present: false, n: 0, agreement: [] as { detector: string; n: number; agree: number; rate: Rate }[] };
181
+ if (!existsSync(labelsFile)) return { present: false, n: 0, unclear: 0, agreement: [] as { detector: string; n: number; agree: number; rate: Rate; unclear: number }[] };
180
182
  const codeLabels = existsSync(evalsFile) ? (JSON.parse(readFileSync(evalsFile, "utf8")) as Record<string, Record<string, string>>) : {};
181
183
  const rows: LabelRow[] = readFileSync(labelsFile, "utf8")
182
184
  .split("\n")
@@ -188,19 +190,27 @@ function labelsJoin(labelsFile: string, evalsFile: string, sessionIds?: Set<stri
188
190
  return [];
189
191
  }
190
192
  });
191
- const by = new Map<string, { n: number; agree: number }>();
193
+ const by = new Map<string, { n: number; agree: number; unclear: number }>();
192
194
  let n = 0;
195
+ let unclear = 0;
193
196
  for (const row of rows) {
194
197
  if (sessionIds && !sessionIds.has(traceId(row.session_id, "labels"))) continue;
195
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
+ }
196
207
  const code = codeLabels[row.session_id]?.[row.evaluation_name];
197
208
  if (!code || code === "na") continue;
198
- const t = by.get(row.evaluation_name) ?? { n: 0, agree: 0 };
199
209
  t.n += 1;
200
210
  if (code === row.label) t.agree += 1;
201
211
  by.set(row.evaluation_name, t);
202
212
  }
203
- return { present: true, n, agreement: [...by].map(([detector, t]) => ({ detector, n: t.n, agree: t.agree, rate: rate(t.agree, t.n) })) };
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 })) };
204
214
  }
205
215
 
206
216
  export function buildModel(options: {
@@ -214,6 +224,8 @@ export function buildModel(options: {
214
224
  labelsFile: string;
215
225
  sessionEvalsFile: string;
216
226
  coverage?: Coverage;
227
+ /** Joined work items (`index/items.json`), when built. */
228
+ work?: ItemsFile;
217
229
  now?: Date;
218
230
  }) {
219
231
  const { index, filter } = options;
@@ -264,7 +276,7 @@ export function buildModel(options: {
264
276
  weekly: weeklyRises(index, filter.since ?? earliest, filter.project),
265
277
  window: { since: filter.since ?? earliest ?? null, until: filter.until ?? days.at(-1) ?? null, days: days.length, project: filter.project ?? null },
266
278
  freshness: { lastExtract: lastExtract ?? null, built: index.built, stale: ageHours > STALE_HOURS, ageHours: Number.isFinite(ageHours) ? round(ageHours, 1) : null },
267
- meta: { metrics: METRICS, detectors: DETECTOR_META, notices: NOTICE_META, changeKinds: CHANGE_KIND_META },
279
+ meta: { metrics: METRICS, detectors: DETECTOR_META, notices: NOTICE_META, changeKinds: CHANGE_KIND_META, closeKinds: CLOSE_KIND_META, stallKinds: STALL_KIND_META },
268
280
  totals: {
269
281
  sessions: total.sessions,
270
282
  subagentSessions: total.subagentSessions,
@@ -352,6 +364,7 @@ export function buildModel(options: {
352
364
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
353
365
  labels: { ...labelsJoin(options.labelsFile, options.sessionEvalsFile, labelIds), needsIndex: !!labelIds && !hasSessionIds },
354
366
  coverage: options.coverage ?? null,
367
+ work: workModel(options.work, filter),
355
368
  };
356
369
  }
357
370
 
package/src/ops.ts CHANGED
@@ -9,6 +9,7 @@ import { PRESETS, type Preset, rangeFilter, suffix } from "./ranges.ts";
9
9
  import { buildModel, type Filter, type ReportModel } from "./model.ts";
10
10
  import { agentDir, home, layout, loadSettings, stateDir } from "./paths.ts";
11
11
  import { renderHtml, type Lang } from "./render.ts";
12
+ import { loadWork } from "./work/join.ts";
12
13
 
13
14
  type Env = Record<string, string | undefined>;
14
15
 
@@ -73,12 +74,12 @@ export function coverageInRange(input: RangeInput, env?: Env) {
73
74
  function snapshot(env?: Env, withCoverage = true) {
74
75
  const ctx = context(env), index = loadIndex(ctx.layout);
75
76
  if (!index) return;
76
- const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date();
77
+ const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date(), work = loadWork(ctx.layout);
77
78
  const cov = withCoverage ? coverageReader(ctx, now) : undefined;
78
79
  return { index, build(input: RangeInput, preset: Preset, comparisons?: ReportModel["changes"]) {
79
80
  const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
80
81
  return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
81
- labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter) });
82
+ labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
82
83
  } };
83
84
  }
84
85
  export function indexedModel(filter: RangeInput, env?: Env, withCoverage = true) {
package/src/paths.ts CHANGED
@@ -85,6 +85,10 @@ export interface Layout {
85
85
  labels: string;
86
86
  status: string;
87
87
  reports: string;
88
+ /** Joined work items (what the report reads), their records, and the lines-changed cache. */
89
+ items: string;
90
+ itemRecords: string;
91
+ lines: string;
88
92
  }
89
93
 
90
94
  export function layout(state = stateDir()): Layout {
@@ -101,6 +105,9 @@ export function layout(state = stateDir()): Layout {
101
105
  labels: join(state, "labels.jsonl"),
102
106
  status: join(state, "index", "status.json"),
103
107
  reports: join(state, "reports"),
108
+ items: join(state, "index", "items.json"),
109
+ itemRecords: join(state, "index", "workitems.jsonl"),
110
+ lines: join(state, "index", "lines.json"),
104
111
  };
105
112
  }
106
113
 
package/src/query.ts CHANGED
@@ -3,8 +3,9 @@ import { coverageInRange, indexedModel, reportPath } from "./ops.ts";
3
3
  import { findings } from "./findings.ts";
4
4
  import { select } from "./report/findings.ts";
5
5
  import type { Rate } from "./model.ts";
6
+ import { itemsView } from "./work/query.ts";
6
7
 
7
- export const VIEWS = ["findings", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
8
+ export const VIEWS = ["findings", "items", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"] as const;
8
9
  export type View = (typeof VIEWS)[number];
9
10
  export const MAX_BYTES = 1900;
10
11
 
@@ -85,6 +86,8 @@ export function query(view: View, options: { since?: string; days?: number; proj
85
86
  body.push(`total $${m.cost.total}; per session ${m.cost.perSession.value === null ? "n/a" : `$${m.cost.perSession.value.toFixed(2)}`} (n=${m.cost.perSession.n}); tokens ${m.totals.tokens}`);
86
87
  body.push("cost of sessions loading skill (not caused by it):");
87
88
  for (const s of m.cost.bySkill.slice(0, 10)) body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
89
+ } else if (view === "items") {
90
+ body.push(...itemsView(m.work));
88
91
  } else if (view === "changes") {
89
92
  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");
90
93
  const { highlighted, folded } = select(m);
package/src/render.ts CHANGED
@@ -20,6 +20,7 @@ function weeklyPanel(m: ReportModel, L: Words) {
20
20
  export function renderHtml(m: ReportModel, lang: Lang = "zh", range: Preset | "custom" = "custom"): string {
21
21
  const L = words(lang), w = periodRows(m), t = timeline(m, w, lang, range), c = concepts(m, w, t.lead, L);
22
22
  const nav = [
23
+ ["work", L("Work items", "工作")],
23
24
  ["archive", L("All changes", "所有調整")],
24
25
  ["skills", L("Skills", "技能")],
25
26
  ["packages", L("Tools", "套件與工具")],
@@ -1,6 +1,34 @@
1
1
  import type { ReportModel } from "../model.ts";
2
- import { type Change, esc, num, type Words } from "./format.ts";
2
+ import { type Change, esc, num, usd, type Words } from "./format.ts";
3
3
  import type { Week } from "./week.ts";
4
+ import { comparisonText } from "../work/wording.ts";
5
+
6
+ /** The two work-item ideas, with this report's own numbers. */
7
+ function workCards(m: ReportModel, L: Words) {
8
+ const w = m.work;
9
+ if (!w) {
10
+ const none = L("Run /evals extract to see the numbers.", "請執行 /evals extract 看這段期間的數字。");
11
+ return { attribution: [L("Who a cost belongs to", "花費歸屬"), none], cheaper: [L("When is one way cheaper?", "怎麼比才算比較省"), none] };
12
+ }
13
+ const first = w.compare.find((c) => c.kind === "delegated") ?? w.compare[0];
14
+ const now = first ? comparisonText(first, L) : L("No finished items to compare yet.", "還沒有完成的工作可以比。");
15
+ return {
16
+ attribution: [
17
+ L("Who a cost belongs to", "花費歸屬"),
18
+ L(
19
+ `Subagent cost is exact: every reply of every subagent session joined to an item is added up, ${usd(w.cost.child)} over ${num(w.delegated)} items handed to subagents here. Main-agent cost is an estimate: the main looks after several items at once, so each of its replies is split evenly among the items in progress at that moment (two at once: half each; ${num(w.shared)} items overlapped another), ${usd(w.cost.main)} in all. ${usd(w.cost.unattributed)} of main cost fell outside every item and belongs to none.`,
20
+ `子代理的花費是精確的:對到某項工作的子代理工作階段,每次回覆的費用全部加起來;這段期間 ${num(w.delegated)} 件交給子代理的工作共 ${usd(w.cost.child)}。主代理的花費是估算:主代理同時照顧好幾件事,所以它每次回覆的費用,平均分給當下進行中的工作(同時兩件就各算一半;有 ${num(w.shared)} 件和別件重疊),共 ${usd(w.cost.main)}。另有 ${usd(w.cost.unattributed)} 的主代理費用不在任何工作進行中,不算進任何一件。`,
21
+ ),
22
+ ],
23
+ cheaper: [
24
+ L("When is one way cheaper?", "怎麼比才算比較省"),
25
+ L(
26
+ `Three things must hold. Compare like with like (work handed to subagents with the same, work the main did with the same). Account for size: cost per 100 changed lines, which ${num(w.withLines)} of ${num(w.completed)} finished items have. Have enough items: at least ${w.minItems} per group. Now: ${now}`,
27
+ `三件事都要做到。一、只比同類:交給子代理的跟交給子代理的比,主代理自己做的跟自己做的比。二、看規模:用每百行改動的花費,這段期間 ${num(w.completed)} 件完成的工作裡有 ${num(w.withLines)} 件算得出行數。三、件數要夠:每組至少 ${w.minItems} 件。目前:${now}`,
28
+ ),
29
+ ],
30
+ };
31
+ }
4
32
 
5
33
  export function concepts(m: ReportModel, week: Week, c: Change | undefined, L: Words) {
6
34
  const i = c?.impact,
@@ -53,6 +81,7 @@ export function concepts(m: ReportModel, week: Week, c: Change | undefined, L: W
53
81
  `時間軸有 ${num(m.changes.length)} 筆調整。要把差異歸給某個版本,得先查同一期間還改了什麼。`,
54
82
  ),
55
83
  ],
84
+ ...workCards(m, L),
56
85
  check: [
57
86
  L("Code check", "程式檢查"),
58
87
  L(
@@ -1,6 +1,7 @@
1
1
  import type { ReportModel } from "../model.ts";
2
2
  import { type concepts, lesson, selfCheck } from "./concepts.ts";
3
3
  import { duration, esc, type Lang, num, pct, table, usd, words } from "./format.ts";
4
+ import { workSection } from "./work.ts";
4
5
 
5
6
  export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof concepts>) {
6
7
  const L = words(lang), meta = m.meta.metrics;
@@ -156,9 +157,9 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
156
157
  meta.agreement.meaning[lang],
157
158
  m.labels.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : m.labels.present && m.labels.n
158
159
  ? T(
159
- [L("Check", "檢查"), L("Labelled", "已標記"), L("Agreement", "一致比例")],
160
- m.labels.agreement.map((r) => [m.meta.detectors[r.detector]?.label[lang] ?? r.detector, r.n, pct(r.rate)]),
161
- )
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>`
162
163
  : `<p>${
163
164
  L(
164
165
  "No labels yet. In phase 2 you will judge sessions yourself and compare your answers with the code checks.",
@@ -167,6 +168,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
167
168
  }</p>`,
168
169
  );
169
170
  return [
171
+ workSection(m, lang, cards, lesson),
170
172
  skills,
171
173
  packages,
172
174
  ask,
@@ -179,7 +181,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
179
181
  section(
180
182
  "concepts",
181
183
  L("Concepts", "概念"),
182
- L("Use these five ideas when you read the next report.", "下次讀報表時,可以用這五個概念判讀數字。"),
184
+ L(`Use these ${Object.keys(cards).length} ideas when you read the next report.`, `下次讀報表時,可以用這 ${Object.keys(cards).length} 個概念判讀數字。`),
183
185
  `<div class="notes-grid">${Object.values(cards).map((c) => lesson(c, L)).join("")}</div>${selfCheck(L)}`,
184
186
  ),
185
187
  ].join("");
@@ -59,6 +59,10 @@ h3,.big {font-size:29px;line-height:1.35;margin:14px 0 18px}
59
59
  .scroll {overflow-x:auto}table {width:100%;border-collapse:collapse;margin:.4rem 0;background:var(--paper)}
60
60
  th,td {text-align:start;padding:7px 12px;border-bottom:1px solid var(--line)}th {font-size:15px;color:var(--green)}
61
61
  .pair,.notes-grid {display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px}
62
+ .tiles {display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin:18px 0 6px}.tiles .panel {padding:16px 18px}.tiles .big {font-size:27px;margin:6px 0}.tiles .muted {margin:0}
63
+ #work h3 {font-size:22px;margin:30px 0 10px}#work .pair {margin-top:14px}#work .lesson {margin:0}
64
+ table.items td {vertical-align:top}table.items td small {display:block;color:var(--sub);font-size:13px}table.items .item-title {min-width:14em;font-weight:600}table.items .nowrap {white-space:nowrap}
65
+ #work .panel th,#work .panel td {white-space:nowrap}#work .panel td:first-child {white-space:normal}
62
66
  .checks {margin-top:18px}.checks h3,.topic .panel h3 {font-size:22px}
63
67
  .detail {display:none;padding-bottom:24px;scroll-margin-top:75px}.detail:target {display:block;outline:none}
64
68
  body:has(.detail:target) main {display:none}.back {float:right;font-size:15px}
@@ -73,6 +77,7 @@ body:has(.detail:target) main {display:none}.back {float:right;font-size:15px}
73
77
  .notes-grid {margin:16px 0}.notes-grid .lesson {font-size:16px}
74
78
  footer {font-size:14px;margin-top:24px;padding:18px 0 25px;color:var(--sub);border-top:1px solid var(--line)}
75
79
  @media(max-width:850px) {
80
+ .tiles {grid-template-columns:repeat(2,minmax(0,1fr))}
76
81
  .layout,.pair,.notes-grid {grid-template-columns:1fr}.layout {gap:22px}.rail {padding-left:27px}.rail:before {left:7px}.card:before {left:-26px}
77
82
  .reading {flex-wrap:wrap}.ruler-head,footer {align-items:flex-start;flex-direction:column}
78
83
  }
@@ -0,0 +1,76 @@
1
+ import { comparisonText } from "../work/wording.ts";
2
+ /** The 「工作」 section: one row per work item, a like-with-like comparison, and the items still open. */
3
+ import type { ReportModel } from "../model.ts";
4
+ import type { WorkModel } from "../work/model.ts";
5
+ import { esc, type Lang, num, usd, type Words, words } from "./format.ts";
6
+
7
+ const SHOWN = 15;
8
+
9
+ export function span(minutes: number, L: Words) {
10
+ if (minutes < 90) return L(`${Math.round(minutes)} min`, `${Math.round(minutes)} 分`);
11
+ if (minutes < 48 * 60) return L(`${(minutes / 60).toFixed(1)} h`, `${(minutes / 60).toFixed(1)} 小時`);
12
+ return L(`${(minutes / 1440).toFixed(1)} days`, `${(minutes / 1440).toFixed(1)} 天`);
13
+ }
14
+
15
+ function stallText(stalls: Record<string, number>, m: ReportModel, lang: Lang) {
16
+ const L = words(lang);
17
+ const parts = Object.entries(stalls)
18
+ .sort((a, b) => b[1] - a[1])
19
+ .map(([k, v]) => `${m.meta.stallKinds[k]?.[lang] ?? k} ${span(v, L)}`);
20
+ return parts.join(L(", ", "、")) || "—";
21
+ }
22
+
23
+ export function workSection(m: ReportModel, lang: Lang, cards: { attribution: string[]; cheaper: string[] }, lesson: (c: string[], L: Words) => string) {
24
+ const L = words(lang);
25
+ const w = m.work;
26
+ const head = `<section id="work" class="topic"><p class="eyebrow">PI-EVALS / ${L("Work items", "工作")}</p><h2>${L("Work items: what each cost, where it closed, where it stalled", "工作:每一項花多少、在哪裡收尾、卡在哪裡")}</h2>`;
27
+ if (!w) return `${head}<p class="intro">${L("Run /evals extract to build the work items.", "請執行 /evals extract 建立工作項目。")}</p></section>`;
28
+ const meta = m.meta.metrics;
29
+ const close = (k: string) => m.meta.closeKinds[k]?.[lang] ?? k;
30
+ const dims: Record<string, string> = { role: L("role", "角色"), model: L("model", "模型"), anchorloop: L("anchorloop version", "anchorloop 版本") };
31
+ const kinds: Record<string, string> = { delegated: L("Work handed to subagents", "交給子代理做的工作"), self: L("Work the main agent did itself", "主代理自己做的工作") };
32
+ const stallTotal = Object.values(w.stallMs).reduce((s, v) => s + v, 0);
33
+ const row = (r: WorkModel["list"][number]) =>
34
+ `<tr><td class="item-title">${esc(r.title || r.key)}</td><td>${esc(r.owner ?? "—")}</td><td class="nowrap">${usd(r.main + r.child)}<small>${r.child > 0 ? `${L("main", "主")} ${usd(r.main)}+${L("sub", "子")} ${usd(r.child)}` : L("main agent only", "只有主代理")}</small></td><td class="nowrap">${esc(span(r.minutes, L))}</td><td>${esc(close(r.closeKind))}${r.thread ? `<small>${esc(r.thread)}</small>` : ""}</td><td>${esc(stallText(r.stalls, m, lang))}</td></tr>`;
35
+ const listHead = `<thead><tr><th scope="col">${L("Item", "工作")}</th><th scope="col">${L("Owner", "誰做")}</th><th scope="col">${L("Cost (main + subagents)", "花費(主+子)")}</th><th scope="col">${L("In progress", "進行")}</th><th scope="col">${L("Closed by", "收尾方式")}</th><th scope="col">${L("Stalls", "停頓")}</th></tr></thead>`;
36
+ const list = w.list.length
37
+ ? `<div class="scroll"><table class="items">${listHead}<tbody>${w.list.slice(0, SHOWN).map(row).join("")}</tbody></table></div>${
38
+ w.list.length > SHOWN ? `<details><summary>${L(`${w.list.length - SHOWN} more`, `再看 ${w.list.length - SHOWN} 項`)}</summary><div class="scroll"><table class="items">${listHead}<tbody>${w.list.slice(SHOWN).map(row).join("")}</tbody></table></div></details>` : ""
39
+ }`
40
+ : `<p class="muted">${L("No item closed in this period.", "這段期間沒有收尾的工作。")}</p>`;
41
+ const compare = w.compare.length
42
+ ? w.compare
43
+ .map(
44
+ (c) =>
45
+ `<article class="panel"><h3>${esc(kinds[c.kind])} / ${L("by", "依")}${esc(dims[c.dimension])}</h3><div class="scroll"><table><thead><tr><th scope="col">${esc(dims[c.dimension])}</th><th scope="col">${L("Items", "件數")}</th><th scope="col">${L("Median per item", "每件中位數")}</th><th scope="col">${L("Per 100 lines (items)", "每百行(件數)")}</th></tr></thead><tbody>${
46
+ c.groups.map((g) => `<tr><td>${esc(g.value)}</td><td>${num(g.n)}</td><td>${usd(g.median)}</td><td>${g.per100 === null ? "—" : `${usd(g.per100)}(${num(g.nLines)})`}</td></tr>`).join("")
47
+ }</tbody></table></div><p class="verdict">${esc(comparisonText(c, L))} ${L("This is a difference, not its cause.", "這是差異,不是原因。")}</p></article>`,
48
+ )
49
+ .join("")
50
+ : `<p class="muted">${L("No finished items to compare.", "沒有可比較的已完成工作。")}</p>`;
51
+ const open = w.open.length
52
+ ? `<div class="scroll"><table class="items"><thead><tr><th scope="col">${L("Item", "工作")}</th><th scope="col">${L("Stopped at", "停在哪")}</th><th scope="col">${L("Waiting on", "等誰")}</th><th scope="col">${L("For how long", "多久")}</th></tr></thead><tbody>${
53
+ w.open
54
+ .map((o) => `<tr><td class="item-title">${esc(o.title || o.key)}</td><td>${esc(m.meta.stallKinds[o.kind]?.[lang] ?? o.kind)}</td><td>${esc(o.on ?? (o.kind === "human" ? L("you (next prompt)", "你(下一個指示)") : "—"))}${o.owner && o.owner !== o.on ? `<small>${esc(o.owner)}</small>` : ""}</td><td>${esc(span(o.waitMinutes, L))}<small>${L("since", "自")} ${esc(o.since.slice(5, 16).replace("T", " "))} UTC</small></td></tr>`)
55
+ .join("")
56
+ }</tbody></table></div>`
57
+ : `<p class="muted">${L("Nothing open in this period.", "這段期間沒有還開著的工作。")}</p>`;
58
+ const tile = (label: string, big: string, note: string) => `<article class="panel"><p class="eyebrow">${esc(label)}</p><p class="big">${big}</p><p class="muted">${note}</p></article>`;
59
+ const kindRows = Object.entries(w.closeKinds).filter(([, n]) => n > 0).map(([k, n]) => `${esc(close(k))} ${num(n)}`).join(L(", ", "、"));
60
+ return `${head}<p class="intro">${
61
+ L(
62
+ "A work item is one todo task, from the moment it was switched to in progress until it was marked done or deleted. Time spent waiting in the queue before that does not count.",
63
+ "一項工作就是待辦清單上的一列:從它被切到「進行中」開始,到標成完成或刪除為止。開始前排隊的時間不算。",
64
+ )
65
+ }</p><div class="tiles">${
66
+ tile(L("Items", "件數"), num(w.completed), L(`finished; ${num(w.inProgress)} in progress, ${num(w.pending)} not started, ${num(w.deleted)} deleted`, `件完成;進行中 ${num(w.inProgress)}、還沒開始 ${num(w.pending)}、刪掉 ${num(w.deleted)}`))
67
+ }${
68
+ tile(L("Cost of finished items", "完成工作的總花費"), usd(w.cost.main + w.cost.child), L(`subagents ${usd(w.cost.child)} (exact) + main ${usd(w.cost.main)} (estimated)`, `子代理 ${usd(w.cost.child)}(精確)+主代理 ${usd(w.cost.main)}(估算)`))
69
+ }${
70
+ tile(L("Median item", "每件中位數"), usd(w.cost.median), L(`${w.cost.medianMinutes === null ? "—" : span(w.cost.medianMinutes, L)} in progress`, `進行 ${w.cost.medianMinutes === null ? "—" : span(w.cost.medianMinutes, L)}`))
71
+ }${
72
+ tile(meta.item_stall.label[lang], span(stallTotal / 60_000, L), L(`of ${span(w.activeMs / 60_000, L)} in progress`, `占進行中 ${span(w.activeMs / 60_000, L)}`) + "<br>" + esc(stallText(Object.fromEntries(Object.entries(w.stallMs).filter(([, v]) => v > 0).map(([k, v]) => [k, v / 60_000])), m, lang)))
73
+ }</div><p class="muted">${L("How items closed", "收尾方式")}:${kindRows || "—"}</p><h3>${L("Latest finished items", "最近完成的工作")}</h3>${list}<p class="muted">${esc(meta.item_stall.howComputed[lang])}</p><div class="pair">${lesson(cards.attribution, L)}${lesson(cards.cheaper, L)}</div><h3>${L("Is one way cheaper?", "有沒有比較省?")}</h3><p class="intro">${
74
+ L("Each panel compares only items of the same kind; a group needs at least 5 items.", "每一格只比同一類的工作;每組至少 5 件才下結論。")
75
+ }</p><div class="pair">${compare}</div><h3>${L("Still open: stopped where, waiting on whom, for how long", "還開著的工作:停在哪、等誰、多久")}</h3>${open}</section>`;
76
+ }
package/src/schema.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * Privacy is enforced here: every string attribute must look like a name (no spaces, no newlines, bounded length).
6
6
  * Anything else is replaced by "redacted", so free text from a transcript cannot reach a record by accident.
7
+ * The single exception is `pi.item.title`, a todo subject cut to one line of 80 characters.
7
8
  */
8
9
  import { createHash } from "node:crypto";
9
10
 
@@ -37,11 +38,23 @@ export function safeName(value: unknown): string {
37
38
  return NAME.test(value) ? value : "redacted";
38
39
  }
39
40
 
41
+ export const TITLE_MAX = 80;
42
+ /** The one attribute that may hold source text: a work item's todo subject, as one line of at most 80 characters. */
43
+ export const TITLE_ATTR = "pi.item.title";
44
+
45
+ /** The todo subject as a one-line title of at most 80 characters (the boss's rule: 「顯示,最多 80 字」). */
46
+ export function titleOf(subject: unknown): string {
47
+ if (typeof subject !== "string") return "";
48
+ const line = subject.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
49
+ return Array.from(line).slice(0, TITLE_MAX).join("");
50
+ }
51
+
40
52
  function clean(attrs: Attrs): Record<string, AttrValue> {
41
53
  const out: Record<string, AttrValue> = {};
42
54
  for (const [key, value] of Object.entries(attrs)) {
43
55
  if (value === undefined) continue;
44
- if (typeof value === "string") out[key] = safeName(value);
56
+ if (key === TITLE_ATTR) out[key] = titleOf(value);
57
+ else if (typeof value === "string") out[key] = safeName(value);
45
58
  else if (Array.isArray(value)) out[key] = value.slice(0, 200).map(safeName);
46
59
  else if (typeof value === "number") {
47
60
  if (Number.isFinite(value)) out[key] = value;
@@ -78,6 +91,8 @@ export const NAMES = {
78
91
  tools: "pi.tools.snapshot",
79
92
  skills: "pi.skills.available",
80
93
  compaction: "pi.compaction",
94
+ workitem: "pi.workitem",
95
+ stall: "pi.stall",
81
96
  } as const;
82
97
 
83
98
  export type SkillTrigger = "read" | "slash" | "declared" | "bash";