pi-evals 0.2.0 → 0.4.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +23 -9
  3. package/dist/build.js +14 -4
  4. package/dist/cli.js +2 -2
  5. package/dist/coverage.js +8 -1
  6. package/dist/extract/run.js +1 -1
  7. package/dist/extract/session.js +43 -3
  8. package/dist/findings.js +54 -0
  9. package/dist/index.js +14 -7
  10. package/dist/meta.js +43 -1
  11. package/dist/model.js +35 -14
  12. package/dist/ops.js +53 -22
  13. package/dist/paths.js +3 -0
  14. package/dist/query.js +36 -13
  15. package/dist/ranges.js +14 -0
  16. package/dist/render.js +15 -5
  17. package/dist/report/concepts.js +23 -1
  18. package/dist/report/findings.js +12 -1
  19. package/dist/report/sections.js +7 -5
  20. package/dist/report/strip.js +42 -0
  21. package/dist/report/style.js +14 -1
  22. package/dist/report/timeline.js +5 -14
  23. package/dist/report/week.js +21 -13
  24. package/dist/report/work.js +59 -0
  25. package/dist/schema.js +16 -1
  26. package/dist/trends.js +58 -0
  27. package/dist/work/join.js +429 -0
  28. package/dist/work/model.js +145 -0
  29. package/dist/work/query.js +59 -0
  30. package/dist/work/sb.js +131 -0
  31. package/dist/work/track.js +323 -0
  32. package/docs/design.md +15 -0
  33. package/docs/schema.md +8 -2
  34. package/package.json +5 -2
  35. package/scripts/change-impact.mjs +18 -0
  36. package/scripts/package-errors.mjs +10 -0
  37. package/scripts/query-lib.mjs +36 -0
  38. package/scripts/skill-days.mjs +9 -0
  39. package/skills/analyzing-evals/SKILL.md +23 -0
  40. package/src/aggregate.ts +14 -2
  41. package/src/build.ts +13 -4
  42. package/src/cli.ts +2 -2
  43. package/src/coverage.ts +8 -1
  44. package/src/extract/run.ts +1 -1
  45. package/src/extract/session.ts +36 -2
  46. package/src/findings.ts +52 -0
  47. package/src/index.ts +14 -9
  48. package/src/meta.ts +45 -1
  49. package/src/model.ts +40 -15
  50. package/src/ops.ts +50 -22
  51. package/src/paths.ts +7 -0
  52. package/src/query.ts +32 -13
  53. package/src/ranges.ts +15 -0
  54. package/src/render.ts +15 -5
  55. package/src/report/concepts.ts +30 -1
  56. package/src/report/findings.ts +19 -1
  57. package/src/report/sections.ts +9 -9
  58. package/src/report/strip.ts +40 -0
  59. package/src/report/style.ts +14 -1
  60. package/src/report/timeline.ts +6 -22
  61. package/src/report/week.ts +21 -17
  62. package/src/report/work.ts +87 -0
  63. package/src/schema.ts +16 -1
  64. package/src/trends.ts +61 -0
  65. package/src/work/join.ts +476 -0
  66. package/src/work/model.ts +179 -0
  67. package/src/work/query.ts +53 -0
  68. package/src/work/sb.ts +158 -0
  69. package/src/work/track.ts +397 -0
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,9 +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
- import { dayOf } from "./paths.ts";
13
+ import { weeklyRises } from "./trends.ts";
14
+ import { traceId } from "./schema.ts";
15
+ import type { ItemsFile } from "./work/join.ts";
16
+ import { workModel } from "./work/model.ts";
14
17
 
15
18
  export const SMALL_SAMPLE = 20;
16
19
  /** Data older than this (hours) is reported as stale. */
@@ -174,8 +177,8 @@ interface LabelRow {
174
177
  label: string;
175
178
  }
176
179
 
177
- function labelsJoin(labelsFile: string, evalsFile: string) {
178
- if (!existsSync(labelsFile)) return { present: false, n: 0, agreement: [] as { detector: string; n: number; agree: number; rate: Rate }[] };
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 }[] };
179
182
  const codeLabels = existsSync(evalsFile) ? (JSON.parse(readFileSync(evalsFile, "utf8")) as Record<string, Record<string, string>>) : {};
180
183
  const rows: LabelRow[] = readFileSync(labelsFile, "utf8")
181
184
  .split("\n")
@@ -187,27 +190,42 @@ function labelsJoin(labelsFile: string, evalsFile: string) {
187
190
  return [];
188
191
  }
189
192
  });
190
- const by = new Map<string, { n: number; agree: number }>();
193
+ const by = new Map<string, { n: number; agree: number; unclear: number }>();
194
+ let n = 0;
195
+ let unclear = 0;
191
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
+ }
192
207
  const code = codeLabels[row.session_id]?.[row.evaluation_name];
193
208
  if (!code || code === "na") continue;
194
- const t = by.get(row.evaluation_name) ?? { n: 0, agree: 0 };
195
209
  t.n += 1;
196
210
  if (code === row.label) t.agree += 1;
197
211
  by.set(row.evaluation_name, t);
198
212
  }
199
- return { present: true, n: rows.length, 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 })) };
200
214
  }
201
215
 
202
216
  export function buildModel(options: {
203
217
  index: DaysIndex;
204
218
  rows: SessionRow[];
205
219
  changes: Change[];
220
+ /** Already computed for the same index, project and comparison settings. */
221
+ comparisons?: (Change & { impact: ReturnType<typeof impactFromRows> | null })[];
206
222
  filter: Filter;
207
223
  windowDays: number;
208
224
  labelsFile: string;
209
225
  sessionEvalsFile: string;
210
226
  coverage?: Coverage;
227
+ /** Joined work items (`index/items.json`), when built. */
228
+ work?: ItemsFile;
211
229
  now?: Date;
212
230
  }) {
213
231
  const { index, filter } = options;
@@ -233,6 +251,11 @@ export function buildModel(options: {
233
251
  const byProject = [...projectSkills.values()].sort((a, b) => b.loads - a.loads);
234
252
  const projectRows = filter.project ? options.rows.filter((r) => r.p === filter.project) : options.rows;
235
253
  const owner = (tool: string) => ownerFor(index, tool);
254
+ const inRange = (at: string) => (!filter.since || at.slice(0, 10) >= filter.since) && (!filter.until || at.slice(0, 10) <= filter.until);
255
+ const selected = projectRows.filter(r => inRange(r.s)), children = selected.filter(r => r.k);
256
+ const scoped = Boolean(filter.since || filter.until || filter.project);
257
+ const hasSessionIds = selected.every(r => r.id !== undefined);
258
+ const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
236
259
  const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
237
260
  const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
238
261
  const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
@@ -246,13 +269,14 @@ export function buildModel(options: {
246
269
  versions.set(name, list);
247
270
  }
248
271
  const sortedChanges = [...options.changes].sort((a, b) => a.at.localeCompare(b.at));
249
- const firstDay = Object.keys(index.days).sort()[0] ?? "";
272
+ const earliest = [days[0], sortedChanges.find(c => inRange(c.at))?.at.slice(0, 10)].filter(Boolean).sort()[0];
250
273
  return {
251
274
  v: 1 as const,
252
275
  generated: now.toISOString(),
253
- window: { since: days[0] ?? filter.since ?? null, until: days.at(-1) ?? filter.until ?? null, days: days.length, project: filter.project ?? null },
276
+ weekly: weeklyRises(index, filter.since ?? earliest, filter.project),
277
+ window: { since: filter.since ?? earliest ?? null, until: filter.until ?? days.at(-1) ?? null, days: days.length, project: filter.project ?? null },
254
278
  freshness: { lastExtract: lastExtract ?? null, built: index.built, stale: ageHours > STALE_HOURS, ageHours: Number.isFinite(ageHours) ? round(ageHours, 1) : null },
255
- 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 },
256
280
  totals: {
257
281
  sessions: total.sessions,
258
282
  subagentSessions: total.subagentSessions,
@@ -308,8 +332,8 @@ export function buildModel(options: {
308
332
  costByRole: Object.entries(total.subagentCost)
309
333
  .map(([role, cost]) => ({ role, cost: round(cost, 2) }))
310
334
  .sort((a, b) => b.cost - a.cost),
311
- linked: index.sessions.linked,
312
- subagentTotal: index.sessions.subagent,
335
+ linked: scoped ? (children.every(r => r.linked !== undefined) ? children.filter(r => r.linked).length : null) : index.sessions.linked,
336
+ subagentTotal: scoped ? children.length : index.sessions.subagent,
313
337
  },
314
338
  process: {
315
339
  eraStart: ERA_START,
@@ -335,11 +359,12 @@ export function buildModel(options: {
335
359
  .slice(0, 25)
336
360
  .map(({ name, cost, sessions }) => ({ skill: name, cost, sessions })),
337
361
  },
338
- changes: sortedChanges
339
- .filter((c) => (!filter.since || c.at.slice(0, 10) >= filter.since) && (!filter.until || c.at.slice(0, 10) <= filter.until))
362
+ changes: options.comparisons?.filter(c => inRange(c.at)) ?? sortedChanges
363
+ .filter((c) => inRange(c.at))
340
364
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
341
- labels: labelsJoin(options.labelsFile, options.sessionEvalsFile),
365
+ labels: { ...labelsJoin(options.labelsFile, options.sessionEvalsFile, labelIds), needsIndex: !!labelIds && !hasSessionIds },
342
366
  coverage: options.coverage ?? null,
367
+ work: workModel(options.work, filter),
343
368
  };
344
369
  }
345
370
 
package/src/ops.ts CHANGED
@@ -5,9 +5,11 @@ import { buildIndex, loadIndex, loadRows } from "./build.ts";
5
5
  import { addMark, readChanges } from "./changes.ts";
6
6
  import { coverage } from "./coverage.ts";
7
7
  import { extract, loadCheckpoint, type Progress } from "./extract/run.ts";
8
- import { buildModel, type Filter } from "./model.ts";
8
+ import { PRESETS, type Preset, rangeFilter, suffix } from "./ranges.ts";
9
+ import { buildModel, type Filter, type ReportModel } from "./model.ts";
9
10
  import { agentDir, home, layout, loadSettings, stateDir } from "./paths.ts";
10
11
  import { renderHtml, type Lang } from "./render.ts";
12
+ import { loadWork } from "./work/join.ts";
11
13
 
12
14
  type Env = Record<string, string | undefined>;
13
15
 
@@ -52,34 +54,60 @@ export function coverageNow(env?: Env, cutDays?: number) {
52
54
  return coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), cutDays ?? ctx.settings.coverageDays);
53
55
  }
54
56
 
57
+ type RangeInput = Filter & { days?: number };
58
+ function coverageReader(ctx: ReturnType<typeof context>, now: Date) {
59
+ const activity = new Map<string, { files: number; indexed: number }>();
60
+ const cov = coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), ctx.settings.coverageDays, now.getTime(), activity);
61
+ return (filter: Filter) => {
62
+ const inRange = { files: 0, indexed: 0 };
63
+ for (const [day, a] of activity) if ((!filter.since || day >= filter.since) && (!filter.until || day <= filter.until)) {
64
+ inRange.files += a.files; inRange.indexed += a.indexed;
65
+ }
66
+ return { ...cov, inRange };
67
+ };
68
+ }
69
+ export function coverageInRange(input: RangeInput, env?: Env) {
70
+ const ctx = context(env), now = new Date(), last = loadIndex(ctx.layout)?.lastExtract;
71
+ const filter = rangeFilter(input, last ?? now.toISOString());
72
+ return { filter, last, coverage: coverageReader(ctx, now)(filter) };
73
+ }
74
+ function snapshot(env?: Env, withCoverage = true) {
75
+ const ctx = context(env), index = loadIndex(ctx.layout);
76
+ if (!index) return;
77
+ const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date(), work = loadWork(ctx.layout);
78
+ const cov = withCoverage ? coverageReader(ctx, now) : undefined;
79
+ return { index, build(input: RangeInput, preset: Preset, comparisons?: ReportModel["changes"]) {
80
+ const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
81
+ return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
82
+ labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
83
+ } };
84
+ }
85
+ export function indexedModel(filter: RangeInput, env?: Env, withCoverage = true) {
86
+ const data = snapshot(env, withCoverage);
87
+ return data && { report: data.build(filter, 30), index: data.index };
88
+ }
89
+
55
90
  export function model(filter: Filter, env?: Env, withCoverage = true) {
56
- const ctx = context(env);
57
- const index = loadIndex(ctx.layout);
58
- if (!index) return undefined;
59
- return buildModel({
60
- index,
61
- rows: loadRows(ctx.layout),
62
- changes: readChanges(ctx.layout.changes),
63
- filter,
64
- windowDays: ctx.settings.impactWindowDays,
65
- labelsFile: ctx.layout.labels,
66
- sessionEvalsFile: ctx.layout.sessionEvals,
67
- coverage: withCoverage ? coverageNow(env) : undefined,
68
- });
91
+ return indexedModel(filter, env, withCoverage)?.report;
69
92
  }
70
93
 
71
94
  /** Builds the report; returns the HTML path, or undefined when nothing was extracted yet. */
72
- export function runReport(options: { env?: Env; filter?: Filter; outDir?: string; lang?: Lang } = {}): { html: string; json: string } | undefined {
95
+ export function runReport(options: { env?: Env; filter?: RangeInput; outDir?: string; lang?: Lang } = {}): { html: string; json: string } | undefined {
73
96
  const ctx = context(options.env);
74
- const m = model(options.filter ?? {}, options.env);
75
- if (!m) return undefined;
97
+ const data = snapshot(options.env), filter = options.filter ?? {};
98
+ if (!data) return;
76
99
  const dir = resolve(options.outDir ?? ctx.layout.reports);
77
100
  mkdirSync(dir, { recursive: true });
78
- const html = join(dir, "report.html");
79
- const json = join(dir, "model.json");
80
- writeFileSync(json, JSON.stringify(m, null, 1));
81
- writeFileSync(html, renderHtml(m, options.lang ?? "zh"));
82
- return { html, json };
101
+ const write = (m: ReportModel, range: Preset | "custom") => {
102
+ const html = join(dir, `report${suffix(range)}.html`), json = join(dir, `model${suffix(range)}.json`);
103
+ writeFileSync(json, JSON.stringify(m, null, 1));
104
+ writeFileSync(html, renderHtml(m, options.lang ?? "zh", range));
105
+ return { html, json };
106
+ };
107
+ if (filter.since || filter.until || filter.days !== undefined) return write(data.build(filter, 30), "custom");
108
+ const all = data.build(filter, "all");
109
+ for (const p of PRESETS) if (p !== 30) write(p === "all" ? all : data.build(filter, p, all.changes), p);
110
+ return write(data.build(filter, 30, all.changes), 30);
83
111
  }
84
112
 
85
113
  export function reportPath(env?: Env): string {
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
@@ -1,8 +1,11 @@
1
1
  /** `evals_query`: bounded plain-text summaries of the index for an agent (names and numbers only, under 2 KB). */
2
- import { coverageNow, model, reportPath } from "./ops.ts";
2
+ import { coverageInRange, indexedModel, reportPath } from "./ops.ts";
3
+ import { findings } from "./findings.ts";
4
+ import { select } from "./report/findings.ts";
3
5
  import type { Rate } from "./model.ts";
6
+ import { itemsView } from "./work/query.ts";
4
7
 
5
- export const VIEWS = ["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;
6
9
  export type View = (typeof VIEWS)[number];
7
10
  export const MAX_BYTES = 1900;
8
11
 
@@ -12,25 +15,34 @@ const sec = (v: number | null) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)
12
15
  /** Cuts text to the byte limit at a line boundary. */
13
16
  export function bound(text: string, limit = MAX_BYTES): string {
14
17
  if (Buffer.byteLength(text) <= limit) return text;
15
- const lines = text.split("\n");
16
- while (lines.length > 1 && Buffer.byteLength(`${lines.join("\n")}\n…`) > limit) lines.splice(lines.length - 2, 1);
17
- return `${lines.join("\n")}\n…`.slice(0, limit);
18
+ const lines = text.split("\n"), tail = lines.at(-1) ?? "";
19
+ const suffix = tail.startsWith("report: ") && Buffer.byteLength(tail) < limit / 2 ? `\n…\n${tail}` : "\n…";
20
+ const kept: string[] = [];
21
+ for (const line of lines) {
22
+ if (Buffer.byteLength([...kept, line].join("\n") + suffix) > limit) break;
23
+ kept.push(line);
24
+ }
25
+ return kept.join("\n") + suffix;
18
26
  }
19
27
 
20
- export function query(view: View, options: { since?: string; project?: string; env?: Record<string, string | undefined> } = {}): string {
28
+ export function query(view: View, options: { since?: string; days?: number; project?: string; env?: Record<string, string | undefined> } = {}): string {
21
29
  if (view === "coverage") {
22
- const c = coverageNow(options.env);
30
+ const { coverage: c, filter, last } = coverageInRange(options, options.env);
23
31
  return bound(
24
32
  [
33
+ `${filter.since}..${filter.until} UTC; last extract ${last ?? "never"}; live cleanup check across all dates and projects`,
25
34
  `coverage, sessions inactive > ${c.cutDays} days (before ${c.cutoff.slice(0, 10)}):`,
26
35
  `indexed ${c.indexed.files}/${c.old.files} files, ${(c.indexed.bytes / 1e9).toFixed(2)} of ${(c.old.bytes / 1e9).toFixed(2)} GB; not indexed ${c.notIndexed.files}`,
36
+ `modified in report dates (all projects): ${c.inRange?.indexed ?? 0}/${c.inRange?.files ?? 0} files indexed`,
27
37
  `all files: ${c.all.indexedFiles}/${c.all.files} indexed; index keeps ${c.retainedGone} sessions whose file is gone`,
28
38
  "meaning: only indexed files keep their numbers if the session files are cleaned up",
29
39
  ].join("\n"),
30
40
  );
31
41
  }
32
- const m = model({ since: options.since, project: options.project }, options.env, false);
33
- if (!m) return "pi-evals: nothing extracted yet; the user can run /evals extract.";
42
+ const data = indexedModel(options, options.env, view === "findings");
43
+ if (!data) return "pi-evals: nothing extracted yet; the user can run /evals extract.";
44
+ const { report: m, index } = data;
45
+ if (view === "findings") return bound(findings(m), 1499);
34
46
  const head = [
35
47
  `pi-evals ${view} · ${m.window.since ?? "?"}..${m.window.until ?? "?"}${m.window.project ? ` · project ${m.window.project}` : ""} · sessions ${m.totals.sessions}`,
36
48
  m.freshness.stale ? `STALE: last extract ${m.freshness.lastExtract ?? "never"} (${m.freshness.ageHours ?? "?"}h ago); /evals extract refreshes` : `last extract ${m.freshness.lastExtract}`,
@@ -42,6 +54,8 @@ export function query(view: View, options: { since?: string; project?: string; e
42
54
  body.push(`ways: ${Object.entries(m.skills.triggers).map(([k, v]) => `${k} ${v}`).join(", ")}`);
43
55
  body.push(`offered but never loaded (${m.skills.neverLoaded.length}/${m.skills.offered}): ${m.skills.neverLoaded.slice(0, 25).join(", ")}`);
44
56
  } else if (view === "packages") {
57
+ const w = m.weekly;
58
+ for (const p of w?.packages.slice(0, 3) ?? []) body.push(`${p.name} weekly errors/calls: ${p.before.errors}/${p.before.calls} -> ${p.after.errors}/${p.after.calls}`);
45
59
  body.push("package: calls, error rate, avg time");
46
60
  for (const p of m.packages.slice(0, 15)) body.push(`${p.owner}${p.version ? `@${p.version}` : ""}: ${p.calls}, ${pct(p.errorRate)}, ${sec(p.avgMs)}`);
47
61
  } else if (view === "ask_user") {
@@ -49,11 +63,13 @@ export function query(view: View, options: { since?: string; project?: string; e
49
63
  body.push(`questions ${a.calls}; dismissed ${pct(a.cancelRate)}; avg wait for answer ${sec(a.avgWaitMs)} (n=${a.waitN}); errors ${a.errors}`);
50
64
  body.push(`answer source: ${Object.entries(a.sources).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
51
65
  } else if (view === "monitors") {
66
+ const w = m.weekly?.monitors;
67
+ if (w) body.push(`weekly jobs ending in error: ${w.before.errors}/${w.before.calls} -> ${w.after.errors}/${w.after.calls}`);
52
68
  const mo = m.monitors;
53
69
  body.push(`started ${mo.started}; ending recorded ${mo.finished}; avg duration ${sec(mo.avgMs)} (n=${mo.durationN})`);
54
70
  body.push(`outcomes: ${Object.entries(mo.statuses).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
55
71
  } else if (view === "subagents") {
56
- body.push(`subagent sessions ${m.subagents.sessions}; linked to parent ${m.subagents.linked}/${m.subagents.subagentTotal} (all time)`);
72
+ body.push(`subagent sessions ${m.subagents.sessions}; linked to parent: ${m.subagents.linked === null ? "run /evals extract for counts in this range" : `${m.subagents.linked}/${m.subagents.subagentTotal}`}`);
57
73
  body.push("role / model: launches");
58
74
  for (const l of m.subagents.launches.slice(0, 12)) body.push(`${l.role} / ${l.model}: ${l.n}`);
59
75
  body.push(`cost by role: ${m.subagents.costByRole.slice(0, 8).map((r) => `${r.role} $${r.cost}`).join(", ")}`);
@@ -70,15 +86,18 @@ export function query(view: View, options: { since?: string; project?: string; e
70
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}`);
71
87
  body.push("cost of sessions loading skill (not caused by it):");
72
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));
73
91
  } else if (view === "changes") {
74
- body.push("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");
75
- for (const c of m.changes.slice(-8).reverse()) {
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");
93
+ const { highlighted, folded } = select(m);
94
+ for (const c of [...highlighted, ...folded].slice(0, 8)) {
76
95
  const what = c.package ? `${c.package} ${c.from ?? "-"}->${c.to ?? "-"}` : c.subject.slice(0, 60);
77
96
  const i = c.impact;
78
97
  const fx = i
79
98
  ? `sessions ${i.before.sessions}->${i.after.sessions}, tool errors ${pct(i.before.tool_error_rate)}->${pct(i.after.tool_error_rate)}, anchor-first ${pct(i.before.anchor_before_first_edit)}->${pct(i.after.anchor_before_first_edit)}${i.smallSample ? ", small" : ""}${i.incomplete ? `, incomplete (days with data ${i.daysWithData.before}/${i.daysWithData.after})` : ""}${i.confounded ? `, confounded ${i.confounded}` : ""}`
80
99
  : "no data before";
81
- body.push(`${c.at.slice(0, 10)} ${c.kind} ${what}: ${fx}`);
100
+ body.push(`${c.at} ${c.kind} ${what}: ${fx}`);
82
101
  }
83
102
  }
84
103
  return bound([...head, ...body, `report: ${reportPath(options.env)}`].join("\n"));
package/src/ranges.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { Filter } from "./model.ts";
2
+
3
+ export const PRESETS = [14, 30, 90, "all"] as const;
4
+ export type Preset = typeof PRESETS[number];
5
+ export const suffix = (r: Preset | "custom") => r === 30 ? "" : typeof r === "number" ? `-${r}d` : `-${r}`;
6
+
7
+ /** Calendar ranges include the (possibly partial) UTC day of the last extraction. */
8
+ export function rangeFilter(input: Filter & { days?: number }, end: string, preset: Preset = 30): Filter {
9
+ const until = input.until ?? end.slice(0, 10), days = input.days ?? preset;
10
+ if (input.since && input.days !== undefined) throw new Error("Choose either --days or --since.");
11
+ if (days !== "all" && (!Number.isSafeInteger(days) || days < 1 || days > 365000)) throw new Error("--days must be a positive integer (at most 365000).");
12
+ if (input.since && (!/^\d{4}-\d\d-\d\d$/.test(input.since) || !Number.isFinite(Date.parse(input.since)) || new Date(input.since).toISOString().slice(0, 10) !== input.since)) throw new Error("since must be YYYY-MM-DD.");
13
+ const since = input.since ?? (days === "all" ? undefined : new Date(Date.parse(until) - (days - 1) * 86400000).toISOString().slice(0, 10));
14
+ return { since, until, project: input.project };
15
+ }
package/src/render.ts CHANGED
@@ -5,12 +5,22 @@ import { esc, type Lang, num, words } from "./report/format.ts";
5
5
  import { sections } from "./report/sections.ts";
6
6
  import { css } from "./report/style.ts";
7
7
  import { timeline } from "./report/timeline.ts";
8
- import { week, workload } from "./report/week.ts";
8
+ import { PRESETS, type Preset, suffix } from "./ranges.ts";
9
+ import { trendPair } from "./trends.ts";
10
+ import type { Words } from "./report/format.ts";
11
+ import { periodRows, workload } from "./report/week.ts";
9
12
  export type { Lang } from "./report/format.ts";
10
13
 
11
- export function renderHtml(m: ReportModel, lang: Lang = "zh"): string {
12
- const L = words(lang), w = week(m), t = timeline(m, w, lang), c = concepts(m, w, t.lead, L);
14
+ function weeklyPanel(m: ReportModel, L: Words) {
15
+ const w = m.weekly, p = w?.packages[0];
16
+ if (!w || (!p && !w.monitors)) return "";
17
+ const rows = [p && `${p.name === "unknown" ? L("Tools with no known package", "套件不明的工具") : p.name} ${L("errors/calls", "錯誤數/呼叫數")} ${trendPair(p)}`, w.monitors && `${L("Failed/finished jobs", "失敗數/已結束工作數")} ${trendPair(w.monitors)}`];
18
+ return `<section class="panel"><h2>${L("Weekly error increases", "每週錯誤比例上升")}</h2><p>${esc(w.start)}–${esc(w.end)} UTC · ${L("Earlier week → later week", "前一週 → 後一週")}</p>${rows.filter(Boolean).map(s => `<p>${esc(s!)}</p>`).join("")}</section>`;
19
+ }
20
+ export function renderHtml(m: ReportModel, lang: Lang = "zh", range: Preset | "custom" = "custom"): string {
21
+ const L = words(lang), w = periodRows(m), t = timeline(m, w, lang, range), c = concepts(m, w, t.lead, L);
13
22
  const nav = [
23
+ ["work", L("Work items", "工作")],
14
24
  ["archive", L("All changes", "所有調整")],
15
25
  ["skills", L("Skills", "技能")],
16
26
  ["packages", L("Tools", "套件與工具")],
@@ -31,7 +41,7 @@ export function renderHtml(m: ReportModel, lang: Lang = "zh"): string {
31
41
  }</title><style>${css}</style></head><body><header><a href="#timeline" class="brand"><svg width="30" height="30" viewBox="0 0 30 30" aria-hidden="true"><rect width="30" height="30" rx="8" fill="#174e47"/><path d="M7 22V15M15 22V8M23 22V12" fill="none" stroke="white" stroke-width="3"/></svg>pi-evals<span>${
32
42
  L("Agent work, observed", "代理工作觀察")
33
43
  }</span></a><small>${esc(date)} ${L("report", "更新")} / ${L("All times UTC", "時間皆為 UTC")}</small></header>
34
- <main id="timeline"><div class="hero"><p class="eyebrow">${L("Change journal / Newest first", "調整紀事 / 依更新時間排列")}</p><h1>${
44
+ <main id="timeline"><div class="ranges">${range === "custom" ? "" : `<nav aria-label="${L("Time range", "時間範圍")}">${PRESETS.map(p => `<a href="report${suffix(p)}.html"${p === range ? ' aria-current="page"' : ""}>${p === "all" ? L("All time", "全部") : L(`Last ${p} days`, `近 ${p} 天`)}</a>`).join("")}</nav>`}<small>${esc(m.window.since ?? "—")} – ${esc(m.window.until ?? "—")} UTC</small></div>${t.strip}<div class="hero"><p class="eyebrow">${L("Change journal / Newest first", "調整紀事 / 依更新時間排列")}</p><h1>${
35
45
  esc(t.headline)
36
46
  }</h1><p class="deck">${esc(t.trust)}</p>${
37
47
  m.freshness.stale
@@ -44,7 +54,7 @@ export function renderHtml(m: ReportModel, lang: Lang = "zh"): string {
44
54
  L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)
45
55
  }</h2><div class="layout"><div class="rail">${
46
56
  t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`
47
- }</div><aside class="side">${workload(w, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${
57
+ }</div><aside class="side">${workload(w, L)}${weeklyPanel(m, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${
48
58
  L("How to read the comparisons", "怎麼讀時間軸上的比較?")
49
59
  }</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
50
60
  <nav class="jump" aria-label="${L("Report sections", "報表章節")}">${
@@ -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 { verdictText } from "./work.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 ? verdictText(first, first.verdict, 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(
@@ -41,7 +41,7 @@ export function verdict(c: Change, rs: Reading[], L: Words): string {
41
41
  }
42
42
  if (i.incomplete) notes.push(L(`less than ${i.window.days} days on one side`, `一側未滿 ${i.window.days} 天`));
43
43
  if (!rs.some(comparable)) notes.push(L("no comparable readings", "沒有可比較的數字"));
44
- const other = i.confounded ? L(`${num(i.confounded)} other changes in the same period`, `同期還有 ${num(i.confounded)} 筆別的調整`) : "";
44
+ const other = i.confounded ? L(`${num(i.confounded)} other changes in the same period`, `同期還有 ${num(i.confounded)} 筆別的調整`) + L("; we cannot tell which change mattered", ",無法分辨是哪一筆造成的") : "";
45
45
  if (notes.length || other) {
46
46
  return [notes.length ? L(`Too early to tell: ${notes.join("; ")}`, `還看不出來(${notes.join("、")})`) : "", other].filter(Boolean)
47
47
  .join(" · ");
@@ -67,6 +67,24 @@ export function select(m: ReportModel) {
67
67
  const highlighted = all.filter((c) => c === lead || c === second);
68
68
  return { all, lead, highlighted, folded: all.filter((c) => !highlighted.includes(c)) };
69
69
  }
70
+ /** Editorial choices shared by the HTML timeline and the compact query. */
71
+ export function overview(m: ReportModel, lang: Lang) {
72
+ const selected = select(m), { lead, all } = selected, L = words(lang);
73
+ const rs = lead ? readings(lead, m, lang) : [];
74
+ const headline = lead ? finding(lead, rs, L) : all.length
75
+ ? L("Not enough sessions to compare changes yet", "這批調整的工作段數還不夠比較")
76
+ : L("No changes recorded in this period", "這段期間沒有調整紀錄");
77
+ const i = lead?.impact;
78
+ const trust = i?.incomplete && i.confounded && !i.smallSample ? L(
79
+ `There were ${num(i.confounded)} other changes, and one side has less than ${i.window.days} days of data. We cannot credit this change alone.`,
80
+ `同期還有 ${num(i.confounded)} 筆別的調整,一側的資料也未滿 ${i.window.days} 天;目前不能把差異歸給這次調整。`,
81
+ ) : lead ? verdict(lead, rs, L) : L(
82
+ `There are ${num(m.totals.sessions)} sessions in this report, but no eligible comparison.`,
83
+ `報表收錄 ${num(m.totals.sessions)} 段工作,目前沒有適合放在首頁的比較。`,
84
+ );
85
+ return { ...selected, headline, trust };
86
+ }
87
+
70
88
  export function finding(c: Change, rs: Reading[], L: Words) {
71
89
  const r = rs.find(comparable);
72
90
  if (!r) return L("There are not enough records to compare this change", "這次調整還沒有足夠紀錄可比較");
@@ -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;
@@ -89,9 +90,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
89
90
  meta.subagent_launches.meaning[lang],
90
91
  T([L("Role", "角色"), L("Model", "模型"), L("Launches", "啟動次數")], s.launches.slice(0, 40).map((r) => [r.role, r.model, r.n])) +
91
92
  more(label("subagent_cost"), T([L("Role", "角色"), L("USD", "美元")], s.costByRole.map((r) => [r.role, usd(r.cost)]))) +
92
- `<p>${L("Linked to a parent across the index", "整份索引中能對回母工作階段的子代理")}:${num(s.linked)} / ${
93
- num(s.subagentTotal)
94
- }</p>`,
93
+ `<p>${L("Linked to a parent in this period", "這段期間能對回母工作階段的子代理")}:${s.linked === null ? L("Run /evals extract for this breakdown.", "請執行 /evals extract 更新分期統計。") : `${num(s.linked)} / ${num(s.subagentTotal)}`} </p>`,
95
94
  );
96
95
  const process = section(
97
96
  "process",
@@ -145,7 +144,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
145
144
  "所有舊檔的大小和修改時間都要和索引相符,未建索引的檔案數和位元組數都歸零,才考慮開啟清理。報表不會刪檔。",
146
145
  ),
147
146
  cov
148
- ? `<p>${L("Inactive days", "閒置天數")} &gt; ${cov.cutDays} / ${L("Files indexed", "已建索引")} ${num(cov.indexed.files)} / ${
147
+ ? `<p>${L("Files modified in the selected dates, indexed (all projects)", "選定日期內有修改的檔案,已建索引(全部專案)")}:${num(cov.inRange?.indexed ?? 0)} / ${num(cov.inRange?.files ?? 0)}</p><p>${L("Cleanup gate across all dates", "清理門檻不分日期")} · ${L("Inactive days", "閒置天數")} &gt; ${cov.cutDays} / ${L("Files indexed", "已建索引")} ${num(cov.indexed.files)} / ${
149
148
  num(cov.old.files)
150
149
  }</p><p>${L("Not indexed", "未建索引")}:${num(cov.notIndexed.files)} ${L("files", "個檔案")} · ${
151
150
  num(cov.notIndexed.bytes)
@@ -156,11 +155,11 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
156
155
  "labels",
157
156
  L("Your labels", "你的標記"),
158
157
  meta.agreement.meaning[lang],
159
- m.labels.present && m.labels.n
158
+ m.labels.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : m.labels.present && m.labels.n
160
159
  ? T(
161
- [L("Check", "檢查"), L("Labelled", "已標記"), L("Agreement", "一致比例")],
162
- m.labels.agreement.map((r) => [m.meta.detectors[r.detector]?.label[lang] ?? r.detector, r.n, pct(r.rate)]),
163
- )
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>`
164
163
  : `<p>${
165
164
  L(
166
165
  "No labels yet. In phase 2 you will judge sessions yourself and compare your answers with the code checks.",
@@ -169,6 +168,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
169
168
  }</p>`,
170
169
  );
171
170
  return [
171
+ workSection(m, lang, cards, lesson),
172
172
  skills,
173
173
  packages,
174
174
  ask,
@@ -181,7 +181,7 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
181
181
  section(
182
182
  "concepts",
183
183
  L("Concepts", "概念"),
184
- 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} 個概念判讀數字。`),
185
185
  `<div class="notes-grid">${Object.values(cards).map((c) => lesson(c, L)).join("")}</div>${selfCheck(L)}`,
186
186
  ),
187
187
  ].join("");