pi-evals 0.1.0 → 0.3.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 (49) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +29 -9
  3. package/dist/build.js +4 -3
  4. package/dist/cli.js +2 -2
  5. package/dist/coverage.js +8 -1
  6. package/dist/findings.js +50 -0
  7. package/dist/index.js +22 -10
  8. package/dist/model.js +21 -10
  9. package/dist/ops.js +52 -22
  10. package/dist/query.js +32 -13
  11. package/dist/ranges.js +14 -0
  12. package/dist/render.js +38 -170
  13. package/dist/report/concepts.js +37 -0
  14. package/dist/report/findings.js +84 -0
  15. package/dist/report/format.js +16 -0
  16. package/dist/report/sections.js +61 -0
  17. package/dist/report/strip.js +42 -0
  18. package/dist/report/style.js +85 -0
  19. package/dist/report/timeline.js +82 -0
  20. package/dist/report/week.js +44 -0
  21. package/dist/trends.js +58 -0
  22. package/docs/design.md +26 -0
  23. package/docs/learn.zh-TW.md +33 -0
  24. package/package.json +6 -3
  25. package/scripts/change-impact.mjs +18 -0
  26. package/scripts/package-errors.mjs +10 -0
  27. package/scripts/query-lib.mjs +36 -0
  28. package/scripts/skill-days.mjs +9 -0
  29. package/skills/analyzing-evals/SKILL.md +21 -0
  30. package/src/aggregate.ts +3 -0
  31. package/src/build.ts +4 -3
  32. package/src/cli.ts +2 -2
  33. package/src/coverage.ts +8 -1
  34. package/src/findings.ts +49 -0
  35. package/src/index.ts +22 -12
  36. package/src/model.ts +22 -10
  37. package/src/ops.ts +49 -22
  38. package/src/query.ts +29 -13
  39. package/src/ranges.ts +15 -0
  40. package/src/render.ts +70 -187
  41. package/src/report/concepts.ts +94 -0
  42. package/src/report/findings.ts +102 -0
  43. package/src/report/format.ts +24 -0
  44. package/src/report/sections.ts +186 -0
  45. package/src/report/strip.ts +40 -0
  46. package/src/report/style.ts +85 -0
  47. package/src/report/timeline.ts +127 -0
  48. package/src/report/week.ts +59 -0
  49. package/src/trends.ts +61 -0
package/src/render.ts CHANGED
@@ -1,189 +1,72 @@
1
- /**
2
- * A plain, functional HTML renderer for the ReportModel: one file, no network, no external assets, inline SVG.
3
- * It reads only the model. The human-readable design comes later from approved mockups and replaces this file.
4
- */
5
- import type { Text } from "./meta.ts";
6
- import type { Rate, ReportModel } from "./model.ts";
7
-
8
- export type Lang = "en" | "zh";
9
-
10
- const esc = (v: unknown) =>
11
- String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c] as string);
12
-
13
- const pct = (r: Rate | null | undefined) => (r && r.value !== null ? `${(r.value * 100).toFixed(1)}%` : "—");
14
- const nOf = (r: Rate | null | undefined) => (r ? r.n : 0);
15
- const ms = (v: number | null | undefined) => {
16
- if (v === null || v === undefined) return "—";
17
- if (v < 1000) return `${v} ms`;
18
- if (v < 60_000) return `${(v / 1000).toFixed(1)} s`;
19
- if (v < 3_600_000) return `${(v / 60_000).toFixed(1)} min`;
20
- return `${(v / 3_600_000).toFixed(1)} h`;
21
- };
22
- const usd = (v: number | null | undefined) => (v === null || v === undefined ? "—" : `$${v.toFixed(2)}`);
23
- const num = (v: number) => v.toLocaleString("en-US");
24
-
25
- function bars(rows: { label: string; value: number; note?: string }[], width = 560): string {
26
- if (!rows.length) return `<p class="empty">—</p>`;
27
- const max = Math.max(...rows.map((r) => r.value), 1);
28
- const h = 18;
29
- const labelW = 220;
30
- const body = rows
31
- .map((r, i) => {
32
- const w = Math.max(1, Math.round(((width - labelW - 90) * r.value) / max));
33
- const y = i * (h + 4);
34
- return `<text x="0" y="${y + 13}" class="lbl">${esc(r.label.length > 34 ? `${r.label.slice(0, 33)}…` : r.label)}</text><rect x="${labelW}" y="${y}" width="${w}" height="${h}" class="bar"/><text x="${labelW + w + 6}" y="${y + 13}" class="val">${esc(r.note ?? num(r.value))}</text>`;
35
- })
36
- .join("");
37
- return `<svg role="img" width="${width}" height="${rows.length * (h + 4)}" viewBox="0 0 ${width} ${rows.length * (h + 4)}">${body}</svg>`;
38
- }
39
-
40
- function columns(days: string[], values: number[], width = 720, height = 120): string {
41
- if (!days.length) return `<p class="empty">—</p>`;
42
- const max = Math.max(...values, 1);
43
- const w = Math.max(2, Math.floor(width / days.length) - 1);
44
- const body = values
45
- .map((v, i) => {
46
- const bh = Math.round(((height - 16) * v) / max);
47
- return `<rect x="${i * (w + 1)}" y="${height - 14 - bh}" width="${w}" height="${bh}" class="bar"><title>${esc(days[i])}: ${esc(num(v))}</title></rect>`;
48
- })
49
- .join("");
50
- const axis = `<text x="0" y="${height - 2}" class="val">${esc(days[0])}</text><text x="${width}" y="${height - 2}" class="val" text-anchor="end">${esc(days.at(-1))}</text>`;
51
- return `<svg role="img" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${body}${axis}</svg>`;
1
+ /** Offline, script-free views of one ReportModel. A fragment selects a detail page without loading another file. */
2
+ import type { ReportModel } from "./model.ts";
3
+ import { concepts, lesson } from "./report/concepts.ts";
4
+ import { esc, type Lang, num, words } from "./report/format.ts";
5
+ import { sections } from "./report/sections.ts";
6
+ import { css } from "./report/style.ts";
7
+ import { timeline } from "./report/timeline.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";
12
+ export type { Lang } from "./report/format.ts";
13
+
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>`;
52
19
  }
53
-
54
- function table(head: string[], rows: (string | number)[][]): string {
55
- if (!rows.length) return `<p class="empty">—</p>`;
56
- return `<table><thead><tr>${head.map((h) => `<th>${esc(h)}</th>`).join("")}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c) => `<td>${typeof c === "number" ? esc(num(c)) : c}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
57
- }
58
-
59
- export function renderHtml(model: ReportModel, lang: Lang = "zh"): string {
60
- const tx = (t: Text | undefined) => esc(t ? t[lang] : "");
61
- const m = model.meta.metrics;
62
- const explain = (id: string) => {
63
- const meta = m[id];
64
- if (!meta) return "";
65
- const dir = meta.goodDirection === "higher" ? (lang === "zh" ? "越高越好" : "higher is better") : meta.goodDirection === "lower" ? (lang === "zh" ? "越低越好" : "lower is better") : "";
66
- return `<p class="meaning"><b>${tx(meta.label)}</b>: ${tx(meta.meaning)}${dir ? ` <span class="dir">(${dir})</span>` : ""}<br><span class="how">${tx(meta.howComputed)}</span></p>`;
67
- };
68
- const L = (en: string, zh: string) => (lang === "zh" ? zh : en);
69
- const sections: string[] = [];
70
-
71
- const fresh = model.freshness;
72
- sections.push(`<section><h2>${L("Overview", "總覽")}</h2>
73
- <p>${L("Window", "期間")}: ${esc(model.window.since ?? "—")} → ${esc(model.window.until ?? "—")} (${model.window.days} ${L("days", "天")})${model.window.project ? ` · ${L("project", "專案")} ${esc(model.window.project)}` : ""}</p>
74
- <p class="${fresh.stale ? "warn" : ""}">${L("Last extract", "上次抽取")}: ${esc(fresh.lastExtract ?? "—")}${fresh.stale ? ` — ${L("data is stale; run /evals extract", "資料過時,請執行 /evals extract")}` : ""}</p>
75
- ${table([L("Number", "數字"), L("Value", "數值")], [
76
- [tx(m.sessions.label), model.totals.sessions],
77
- [tx(m.subagent_sessions.label), model.totals.subagentSessions],
78
- [tx(m.prompts.label), model.totals.prompts],
79
- [tx(m.tool_calls.label), model.totals.toolCalls],
80
- [tx(m.tool_error_rate.label), `${pct(model.totals.toolErrorRate)} (n=${num(nOf(model.totals.toolErrorRate))})`],
81
- [tx(m.cost.label), usd(model.totals.cost)],
82
- ])}
83
- ${explain("sessions")}
84
- <h3>${L("Sessions per day", "每日工作階段")}</h3>${columns(model.series.days, model.series.sessions)}
85
- <h3>${L("Cost per day (USD)", "每日費用(美元)")}</h3>${columns(model.series.days, model.series.cost)}</section>`);
86
-
87
- const sk = model.skills;
88
- sections.push(`<section><h2>${L("Skills", "技能")}</h2>${explain("skill_loads")}
89
- <h3>${L("Loads per day", "每日載入")}</h3>${columns(model.series.days, model.series.skillLoads)}
90
- <h3>${L("Most loaded", "最常載入")}</h3>${bars(sk.top.slice(0, 25).map((s) => ({ label: s.name, value: s.loads, note: `${num(s.loads)} · ${num(s.sessions)} ${L("sessions", "階段")}` })))}
91
- ${explain("skill_sessions")}
92
- <h3>${L("How skills were loaded", "載入方式")}</h3>${table([L("Way", "方式"), L("Loads", "次數")], Object.entries(sk.triggers).map(([k, v]) => [esc(k), v]))}
93
- <h3>${L("By project (top 30)", "各專案(前 30)")}</h3>${table([L("Project", "專案"), L("Skill", "技能"), L("Loads", "次數")], sk.byProject.slice(0, 30).map((r) => [esc(r.project), esc(r.skill), r.loads]))}
94
- <h3>${tx(m.never_loaded.label)} (${sk.neverLoaded.length} / ${sk.offered})</h3>${explain("never_loaded")}<p>${sk.neverLoaded.map(esc).join(", ") || "—"}</p></section>`);
95
-
96
- sections.push(`<section><h2>${L("Packages", "套件")}</h2>${explain("package_calls")}${explain("tool_error_rate")}${explain("avg_duration_ms")}
97
- ${table([L("Package", "套件"), L("Version", "版本"), L("Calls", "呼叫"), L("Errors", "錯誤"), tx(m.tool_error_rate.label), tx(m.avg_duration_ms.label)], model.packages.map((p) => [esc(p.owner), esc(p.version ?? "—"), p.calls, p.errors, pct(p.errorRate), ms(p.avgMs)]))}
98
- <h3>${L("Tools (top 40)", "工具(前 40)")}</h3>${table([L("Tool", "工具"), L("Package", "套件"), L("Calls", "呼叫"), tx(m.tool_error_rate.label), tx(m.avg_duration_ms.label)], model.tools.slice(0, 40).map((t) => [esc(t.name), esc(t.owner), t.calls, pct(t.errorRate), ms(t.avgMs)]))}</section>`);
99
-
100
- const ask = model.askUser;
101
- const bucketLabel = (up: number | null, i: number, all: { upToMs: number | null }[]) => (up === null ? `≥ ${ms(all[i - 1]?.upToMs ?? 0)}` : `< ${ms(up)}`);
102
- sections.push(`<section><h2>${L("Questions to you", "問你的問題")}</h2>${explain("ask_calls")}${explain("ask_wait_ms")}${explain("ask_cancel_rate")}
103
- ${table([L("Number", "數字"), L("Value", "數值")], [
104
- [tx(m.ask_calls.label), ask.calls],
105
- [tx(m.ask_wait_ms.label), `${ms(ask.avgWaitMs)} (n=${num(ask.waitN)})`],
106
- [tx(m.ask_cancel_rate.label), `${pct(ask.cancelRate)} (n=${num(nOf(ask.cancelRate))})`],
107
- ])}
108
- <h3>${L("How long you took", "你花多久回答")}</h3>${bars(ask.buckets.map((b, i) => ({ label: bucketLabel(b.upToMs, i, ask.buckets), value: b.n })))}
109
- <h3>${L("Where the answer came from", "回答來源")}</h3>${table([L("Source", "來源"), L("Questions", "題數")], Object.entries(ask.sources).map(([k, v]) => [esc(k), v]))}</section>`);
110
-
111
- const mon = model.monitors;
112
- sections.push(`<section><h2>${L("Background jobs", "背景工作")}</h2>${explain("monitor_outcomes")}${explain("monitor_duration_ms")}
113
- <p>${L("Started", "啟動")}: ${num(mon.started)} · ${L("Ending recorded", "有結束紀錄")}: ${num(mon.finished)} · ${tx(m.monitor_duration_ms.label)}: ${ms(mon.avgMs)} (n=${num(mon.durationN)})</p>
114
- ${bars(Object.entries(mon.statuses).map(([k, v]) => ({ label: k, value: v })))}</section>`);
115
-
116
- const sub = model.subagents;
117
- sections.push(`<section><h2>${L("Subagents", "子代理")}</h2>${explain("subagent_launches")}
118
- ${table([L("Role", "角色"), L("Model", "模型"), L("Launches", "次數")], sub.launches.slice(0, 40).map((r) => [esc(r.role), esc(r.model), r.n]))}
119
- ${explain("subagent_cost")}${bars(sub.costByRole.slice(0, 20).map((r) => ({ label: r.role, value: r.cost, note: usd(r.cost) })))}
120
- <p>${L("Subagent sessions linked to a parent", "能對回母工作階段的子代理")}: ${num(sub.linked)} / ${num(sub.subagentTotal)}</p></section>`);
121
-
122
- const proc = model.process;
123
- const dm = model.meta.detectors;
124
- sections.push(`<section><h2>${L("Process: does the work follow the anchorloop rules?", "流程:工作有沒有照 anchorloop 規則走?")}</h2>
125
- <p>${L(`Only sessions from ${proc.eraStart} (anchorloop 3.0.0) on are judged; older ones are out of scope, not failures.`, `只評 ${proc.eraStart}(anchorloop 3.0.0)之後的工作階段;更早的不在範圍內,不算失敗。`)}</p>${explain("pass_rate")}
126
- ${proc.detectors
127
- .map((d) => {
128
- const meta = dm[d.name];
129
- const daily = d.perDay.map((x) => (x.pass + x.fail ? Math.round((100 * x.pass) / (x.pass + x.fail)) : 0));
130
- return `<div class="detector"><h3>${tx(meta?.label)}: ${pct(d.passRate)} <small>(n=${num(nOf(d.passRate))}, ${L("not applicable", "不適用")} ${num(d.na)})</small></h3>
131
- <p>${tx(meta?.meaning)}<br><span class="how">${tx(meta?.howComputed)}</span></p>
132
- <p class="ex">✔ ${tx(meta?.example.pass)}<br>✘ ${tx(meta?.example.fail)}</p>
133
- <h4>${L("Share followed per day (%)", "每日遵守比例(%)")}</h4>${columns(model.series.days, daily, 720, 80)}
134
- ${table([L("anchorloop version", "anchorloop 版本"), L("Followed", "遵守"), L("Not followed", "未遵守"), tx(m.pass_rate.label)], d.byVersion.map((v) => [esc(v.version), v.pass, v.fail, pct(v.passRate)]))}</div>`;
135
- })
136
- .join("")}
137
- <h3>${L("Close-guard reminders", "收尾提醒")}</h3>${table([L("Kind", "種類"), L("Count", "次數")], Object.entries(proc.notices).map(([k, v]) => [tx(model.meta.notices[k]) || esc(k), v]))}</section>`);
138
-
139
- sections.push(`<section><h2>${L("Cost", "費用")}</h2>${explain("cost")}${explain("cost_per_session")}${explain("skill_cost")}
140
- <p>${tx(m.cost_per_session.label)}: ${model.cost.perSession.value === null ? "—" : usd(model.cost.perSession.value)} (n=${num(model.cost.perSession.n)})</p>
141
- <h3>${L("By skill loaded (top 25)", "依載入技能(前 25)")}</h3>${bars(model.cost.bySkill.map((r) => ({ label: r.skill, value: r.cost, note: `${usd(r.cost)} · ${num(r.sessions)}` })))}
142
- <h3>${L("Model replies by model", "各模型回覆數")}</h3>${table([L("Model", "模型"), L("Replies", "回覆")], model.cost.byModel.slice(0, 20).map((r) => [esc(r.model), r.replies]))}</section>`);
143
-
144
- const changes = model.changes.slice(-40).reverse();
145
- const imp = (c: (typeof model.changes)[number]) => {
146
- if (!c.impact) return L("no data before this change", "變更前沒有資料");
147
- const i = c.impact;
148
- const row = (key: keyof typeof i.before, label: string) => {
149
- const b = i.before[key] as Rate | number | undefined;
150
- const a = i.after[key] as Rate | number | undefined;
151
- if (b === undefined || a === undefined) return "";
152
- const show = (x: Rate | number) => (typeof x === "number" ? num(x) : key === "cost_per_session" ? (x.value === null ? "—" : usd(x.value)) : key.endsWith("per_session") ? (x.value === null ? "—" : x.value.toFixed(2)) : pct(x));
153
- return `<tr><td>${esc(label)}</td><td>${show(b)}</td><td>${show(a)}</td></tr>`;
154
- };
155
- const kinds = Object.entries(i.confounders)
156
- .map(([k, v]) => `${tx(model.meta.changeKinds[k])} ${v}`)
157
- .join(", ");
158
- const flags = [
159
- i.smallSample ? `<span class="warn">${tx(m.small_sample.label)}</span>` : "",
160
- i.incomplete ? `<span class="warn">${tx(m.incomplete_window.label)} (${L("days with data", "有資料的天數")}: ${i.daysWithData.before} / ${i.daysWithData.after})</span>` : "",
161
- i.confounded ? `<span class="warn">${tx(m.confounded.label)}: ${i.confounded} (${esc(kinds)})</span>` : "",
162
- ]
163
- .filter(Boolean)
164
- .join(" · ");
165
- return `<table><thead><tr><th></th><th>${L("before", "之前")}</th><th>${L("after", "之後")}</th></tr></thead><tbody>${row("sessions", tx(m.sessions.label))}${row("tool_error_rate", tx(m.tool_error_rate.label))}${row("package_error_rate", L("This package's error rate", "此套件出錯比例"))}${row("ask_cancel_rate", tx(m.ask_cancel_rate.label))}${row("cost_per_session", tx(m.cost_per_session.label))}${row("skill_loads_per_session", tx(m.skill_loads_per_session.label))}${row("notices_per_session", tx(m.notices_per_session.label))}${row("anchor_before_first_edit", tx(dm.anchor_before_first_edit.label))}${row("check_after_last_edit", tx(dm.check_after_last_edit.label))}</tbody></table>${flags}`;
166
- };
167
- sections.push(`<section><h2>${L("Your changes and what followed", "你的變更與之後的變化")}</h2>${explain("impact")}${explain("small_sample")}${explain("incomplete_window")}${explain("confounded")}
168
- ${changes.map((c) => `<details><summary>${esc(c.at.slice(0, 10))} · ${tx(model.meta.changeKinds[c.kind])} · ${esc(c.package ? `${c.package} ${c.from ?? "∅"} → ${c.to ?? "∅"}` : c.subject)}${c.repo ? ` <small>${esc(c.repo)} ${esc(c.sha ?? "")}</small>` : ""}</summary><p>${esc(c.subject)}</p>${imp(c)}</details>`).join("") || `<p class="empty">—</p>`}</section>`);
169
-
170
- const lab = model.labels;
171
- sections.push(`<section><h2>${L("Your labels", "你的標記")}</h2>${explain("agreement")}
172
- ${lab.present ? table([L("Check", "檢查"), L("Labelled", "已標記"), L("Agree", "一致"), tx(m.agreement.label)], lab.agreement.map((a) => [tx(dm[a.detector]?.label) || esc(a.detector), a.n, a.agree, pct(a.rate)])) : `<p class="empty">${L("No labels yet. Labelling sessions comes in a later phase.", "還沒有標記。標記工作階段會在之後的階段加入。")}</p>`}</section>`);
173
-
174
- const cov = model.coverage;
175
- if (cov)
176
- sections.push(`<section><h2>${tx(m.coverage.label)}</h2>${explain("coverage")}
177
- <p>${L(`Inactive more than ${cov.cutDays} days`, `閒置超過 ${cov.cutDays} 天`)}: ${num(cov.old.files)} ${L("files", "個檔案")} (${(cov.old.bytes / 1e9).toFixed(2)} GB) · ${L("indexed", "已建索引")} ${num(cov.indexed.files)} · ${L("not indexed", "未建索引")} ${num(cov.notIndexed.files)} (${(cov.notIndexed.bytes / 1e9).toFixed(2)} GB)</p></section>`);
178
-
179
- return `<!doctype html><html lang="${lang === "zh" ? "zh-Hant-TW" : "en"}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>pi-evals report</title>
180
- <style>
181
- :root{color-scheme:light dark;--fg:#1d1d1f;--bg:#fff;--muted:#666;--bar:#4a7bd0;--line:#ddd;--warn:#b35c00}
182
- @media (prefers-color-scheme:dark){:root{--fg:#e6e6e6;--bg:#151515;--muted:#9a9a9a;--bar:#7aa2f7;--line:#333;--warn:#f0a050}}
183
- body{font:15px/1.55 system-ui,-apple-system,"PingFang TC","Noto Sans TC",sans-serif;color:var(--fg);background:var(--bg);max-width:980px;margin:2rem auto;padding:0 1rem}
184
- section{border-top:1px solid var(--line);padding:1rem 0}h1{font-size:1.6rem}h2{font-size:1.3rem}h3{font-size:1.05rem;margin-top:1.2rem}
185
- table{border-collapse:collapse;margin:.5rem 0}td,th{border-bottom:1px solid var(--line);padding:.25rem .6rem;text-align:left;vertical-align:top}
186
- .bar{fill:var(--bar)}.lbl,.val{fill:var(--fg);font-size:12px}.meaning{color:var(--fg)}.how,.dir,small{color:var(--muted)}.warn{color:var(--warn)}.empty{color:var(--muted)}
187
- .ex{color:var(--muted);font-size:.92em}details{margin:.3rem 0}summary{cursor:pointer}
188
- </style></head><body><h1>pi-evals</h1><p class="how">${L("Generated", "產生時間")} ${esc(model.generated)} · ${L("numbers only: no transcript text is stored or shown", "只有數字:不儲存也不顯示對話內容")}</p>${sections.join("\n")}</body></html>`;
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);
22
+ const nav = [
23
+ ["archive", L("All changes", "所有調整")],
24
+ ["skills", L("Skills", "技能")],
25
+ ["packages", L("Tools", "套件與工具")],
26
+ ["ask", L("Questions", "提問")],
27
+ ["monitors", L("Jobs", "背景工作")],
28
+ ["subagents", L("Subagents", "子代理")],
29
+ ["process", L("Process checks", "流程檢查")],
30
+ ["cost", L("Cost", "費用")],
31
+ ["coverage", L("Cleanup", "清理門檻")],
32
+ ["labels", L("Labels", "你的標記")],
33
+ ["concepts", L("Concepts", "概念")],
34
+ ];
35
+ const date = m.generated.slice(0, 10);
36
+ return `<!doctype html><html lang="${
37
+ lang === "zh" ? "zh-Hant-TW" : "en"
38
+ }"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>pi-evals · ${
39
+ L("Change timeline", "調整時間軸")
40
+ }</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>${
41
+ L("Agent work, observed", "代理工作觀察")
42
+ }</span></a><small>${esc(date)} ${L("report", "更新")} / ${L("All times UTC", "時間皆為 UTC")}</small></header>
43
+ <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>${
44
+ esc(t.headline)
45
+ }</h1><p class="deck">${esc(t.trust)}</p>${
46
+ m.freshness.stale
47
+ ? `<p class="stale">${L("Last extract", "上次抽取")}:${esc(m.freshness.lastExtract ?? "—")} · ${
48
+ L("Refresh with /evals extract.", "資料過時,請執行 /evals extract。")
49
+ }</p>`
50
+ : ""
51
+ }</div>
52
+ <div class="spine"><h2>${
53
+ L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)
54
+ }</h2><div class="layout"><div class="rail">${
55
+ t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`
56
+ }</div><aside class="side">${workload(w, L)}${weeklyPanel(m, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${
57
+ L("How to read the comparisons", "怎麼讀時間軸上的比較?")
58
+ }</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
59
+ <nav class="jump" aria-label="${L("Report sections", "報表章節")}">${
60
+ nav.map(([id, text]) => `<a href="#${id}">${text}</a>`).join("")
61
+ }</nav><section class="topic" id="archive"><h2>${L("Other changes by day", "按日期查其餘調整")}</h2><p>${
62
+ L("Open a day for its changes. Each link opens the before-and-after comparison.", "展開一天,點選調整名稱,就能看到它的前後比較。")
63
+ }</p>${t.archive || "—"}</section>
64
+ <p class="muted">${esc(m.window.project ?? L("All projects", "全部專案"))} · ${esc(m.window.since ?? "—")} → ${
65
+ esc(m.window.until ?? "—")
66
+ } · ${num(m.totals.sessions)} ${L("sessions", "段工作")} · ${num(m.totals.prompts)} ${L("prompts", "次提示")}</p>${
67
+ sections(m, lang, c)
68
+ }</main>
69
+ ${t.details}<footer><b>PI-EVALS / ${L("Change timeline", "調整時間軸")}</b><span>${
70
+ esc(m.window.project ?? L("All projects", "全部專案"))
71
+ } · ${L("Transcript text not included", "統計不含對話原文")}</span></footer></body></html>`;
189
72
  }
@@ -0,0 +1,94 @@
1
+ import type { ReportModel } from "../model.ts";
2
+ import { type Change, esc, num, type Words } from "./format.ts";
3
+ import type { Week } from "./week.ts";
4
+
5
+ export function concepts(m: ReportModel, week: Week, c: Change | undefined, L: Words) {
6
+ const i = c?.impact,
7
+ n = num(week.reduce((s, r) => s + r.sessions, 0)),
8
+ d = m.process.detectors.find((r) => r.name === "anchor_before_first_edit");
9
+ return {
10
+ record: [
11
+ L("Record", "紀錄"),
12
+ L(
13
+ `A tool call leaves a record: ${
14
+ num(week.reduce((s, r) => s + r.calls, 0))
15
+ } calls in this chart’s period. The words exchanged are not kept.`,
16
+ `一次工具呼叫留下一筆紀錄。圖中這幾天共 ${num(week.reduce((s, r) => s + r.calls, 0))} 次,不保留對話原文。`,
17
+ ),
18
+ ],
19
+ metric: [
20
+ L("Metric", "指標"),
21
+ L(
22
+ `Count sessions by their start date: ${n} in the chart. This measures workload, not whether the work was good.`,
23
+ `把工作按開始日期計數,圖中共有 ${n} 段。這個指標量的是工作量,不是工作品質。`,
24
+ ),
25
+ ],
26
+ sample: [
27
+ L("Before, after and sample size", "前後比較與樣本數"),
28
+ i
29
+ ? L(
30
+ `Split sessions at the change time: ${num(i.before.sessions)} before and ${
31
+ num(i.after.sessions)
32
+ } after. Only sessions to which a rule applies count in its percentage.`,
33
+ `依開始時間分組:調整前 ${num(i.before.sessions)} 段、調整後 ${
34
+ num(i.after.sessions)
35
+ } 段。算一條規則的通過比例時,只數適用的工作段。`,
36
+ )
37
+ : L(
38
+ `There are ${num(m.totals.sessions)} sessions in the report. Without records on both sides, we cannot compare a change.`,
39
+ `報表裡有 ${num(m.totals.sessions)} 段工作。調整前後都要有紀錄,才有兩組數字能比。`,
40
+ ),
41
+ ],
42
+ confounding: [
43
+ L("Other changes at the same time", "同期多個調整"),
44
+ i
45
+ ? L(
46
+ `There were ${
47
+ num(i.confounded)
48
+ } other changes in these windows. If a rule and a package changed together, their effects cannot be separated here.`,
49
+ `這段期間另有 ${num(i.confounded)} 筆調整。規則和套件若一起改,只比前後分不出哪一項影響了結果。`,
50
+ )
51
+ : L(
52
+ `There are ${num(m.changes.length)} changes on this timeline. Check what else changed before crediting a new version.`,
53
+ `時間軸有 ${num(m.changes.length)} 筆調整。要把差異歸給某個版本,得先查同一期間還改了什麼。`,
54
+ ),
55
+ ],
56
+ check: [
57
+ L("Code check", "程式檢查"),
58
+ L(
59
+ `In ${
60
+ num(d?.passRate.n ?? 0)
61
+ } eligible sessions, code checked whether the agent named a check before editing. It cannot judge whether that check tested the right thing.`,
62
+ `程式在 ${num(d?.passRate.n ?? 0)} 段適用的工作裡查「改檔前有沒有先說怎麼驗證」。它看得出先後順序,判斷不了方法好不好。`,
63
+ ),
64
+ ],
65
+ };
66
+ }
67
+ export function lesson(entry: string[], L: Words) {
68
+ return `<aside class="lesson"><strong class="eyebrow">${L("Reading the numbers", "讀數字")} / ${esc(entry[0])}</strong><p>${
69
+ esc(entry[1])
70
+ }</p></aside>`;
71
+ }
72
+ export function selfCheck(L: Words) {
73
+ const item = (q: string, a: string) => `<p>${q}</p><details><summary>${L("Answer", "看答案")}</summary><p>${a}</p></details>`;
74
+ return `<h3>${L("Check your reading", "試著判讀")}</h3>${
75
+ item(
76
+ L("1. Tool errors fell after a pin. Did the new version fix them?", "1. 更新後工具出錯比例下降,就能說是新版本修好了嗎?"),
77
+ L(
78
+ "Not from this alone. Check the window, the sample and what else changed.",
79
+ "還不能。先看前後各有幾段工作、資料收齊了沒,以及同期還改了什麼。",
80
+ ),
81
+ )
82
+ }${
83
+ item(
84
+ L(
85
+ "2. A session passed the check for naming a test before editing. Did the test cover the bug?",
86
+ "2. 一段工作通過「動手前先說好怎麼驗證」,表示測試驗到了那個錯誤嗎?",
87
+ ),
88
+ L(
89
+ "The order was right. Whether the test could catch the bug is a different question.",
90
+ "只知道順序對。那個測試抓不抓得到錯誤,要另外看測試內容。",
91
+ ),
92
+ )
93
+ }`;
94
+ }
@@ -0,0 +1,102 @@
1
+ import type { Rate, ReportModel } from "../model.ts";
2
+ import { type Change, type Lang, num, pct, usd, type Words, words } from "./format.ts";
3
+
4
+ type Key = "anchor_before_first_edit" | "check_after_last_edit" | "package_error_rate" | "tool_error_rate" | "cost_per_session";
5
+ export interface Reading {
6
+ key: Key;
7
+ label: string;
8
+ direction: string;
9
+ unit: string;
10
+ before?: Rate;
11
+ after?: Rate;
12
+ }
13
+ export function readings(c: Change, m: ReportModel, lang: Lang): Reading[] {
14
+ const L = words(lang), i = c.impact;
15
+ const has = (k: Key) => i?.before[k]?.value != null && i.after[k]?.value != null;
16
+ const process = c.package === "pi-anchorloop" && has("anchor_before_first_edit");
17
+ const keys: Key[] = process
18
+ ? ["anchor_before_first_edit", "check_after_last_edit"]
19
+ : [has("package_error_rate") ? "package_error_rate" : "tool_error_rate", "cost_per_session"];
20
+ return keys.map((key) => {
21
+ const meta = m.meta.detectors[key] ?? m.meta.metrics[key === "package_error_rate" ? "tool_error_rate" : key];
22
+ return {
23
+ key,
24
+ label: key === "package_error_rate" ? L("Package tool error rate", "套件工具出錯比例") : meta.label[lang],
25
+ direction: meta.goodDirection === "higher" ? L("higher is better", "越高越好") : L("lower is better", "越低越好"),
26
+ unit: key.endsWith("error_rate") ? L("calls", "次呼叫") : L("sessions", "段"),
27
+ before: i?.before[key],
28
+ after: i?.after[key],
29
+ };
30
+ });
31
+ }
32
+ export const value = (r: Reading, side: "before" | "after") => r.key === "cost_per_session" ? usd(r[side]?.value ?? null) : pct(r[side]);
33
+ const comparable = (r: Reading) => r.before?.value != null && r.after?.value != null;
34
+ export function verdict(c: Change, rs: Reading[], L: Words): string {
35
+ const i = c.impact;
36
+ if (!i) return L("Too early to tell: no earlier records.", "還看不出來:調整前沒有紀錄。");
37
+ const notes: string[] = [];
38
+ if (i.smallSample) notes.push(L("too few sessions", "樣本太少"));
39
+ else if (rs.some((r) => comparable(r) && Math.min(r.before!.n, r.after!.n) < 20)) {
40
+ notes.push(L("a reading is based on fewer than 20 observations", "有指標的樣本不到 20"));
41
+ }
42
+ if (i.incomplete) notes.push(L(`less than ${i.window.days} days on one side`, `一側未滿 ${i.window.days} 天`));
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)} 筆別的調整`) + L("; we cannot tell which change mattered", ",無法分辨是哪一筆造成的") : "";
45
+ if (notes.length || other) {
46
+ return [notes.length ? L(`Too early to tell: ${notes.join("; ")}`, `還看不出來(${notes.join("、")})`) : "", other].filter(Boolean)
47
+ .join(" · ");
48
+ }
49
+ return rs.some((r) => comparable(r) && value(r, "before") !== value(r, "after"))
50
+ ? L("An observable difference, not proof of cause.", "看得出變化,但不能證明原因。")
51
+ : L("No visible difference at this precision.", "依顯示精度,前後數字持平。");
52
+ }
53
+
54
+ export const eligible = (c: Change) => c.kind === "pin" || c.kind === "model-routing" || (!!c.impact && !c.impact.smallSample);
55
+ export function select(m: ReportModel) {
56
+ const all = [...m.changes].sort((a, b) => b.at.localeCompare(a.at));
57
+ const candidates = all.filter(eligible);
58
+ const recent = candidates.filter((c) => Date.parse(c.at) >= Date.parse(all[0]?.at ?? "") - 7 * 86400000);
59
+ const lead = recent.find((c) =>
60
+ c.package === "pi-anchorloop" && (c.impact?.before.anchor_before_first_edit.n ?? 0) >= 20 &&
61
+ (c.impact?.after.anchor_before_first_edit.n ?? 0) >= 20
62
+ ) ??
63
+ candidates.find((c) => c.impact && !c.impact.smallSample) ?? candidates[0];
64
+ const rest = candidates.filter((c) => c !== lead && c.at <= lead.at && (!lead.sha || c.sha !== lead.sha));
65
+ const second = rest.find((c) => c.impact?.smallSample && c.impact.before.sessions && c.impact.after.sessions) ??
66
+ rest.find((c) => (c.kind === "pin" || c.kind === "model-routing") && c.impact && !c.impact.incomplete) ?? rest[0];
67
+ const highlighted = all.filter((c) => c === lead || c === second);
68
+ return { all, lead, highlighted, folded: all.filter((c) => !highlighted.includes(c)) };
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
+
88
+ export function finding(c: Change, rs: Reading[], L: Words) {
89
+ const r = rs.find(comparable);
90
+ if (!r) return L("There are not enough records to compare this change", "這次調整還沒有足夠紀錄可比較");
91
+ const dir = value(r, "before") === value(r, "after")
92
+ ? L(" held steady", "持平")
93
+ : r.after!.value! > r.before!.value!
94
+ ? L(" rose", "上升")
95
+ : L(" fell", "下降");
96
+ const label = r.key === "anchor_before_first_edit" ? L("The share naming a check before editing", "先說驗證方法的比例") : r.label;
97
+ return `${label}${dir}${
98
+ c.impact?.confounded || c.impact?.smallSample || c.impact?.incomplete || Math.min(r.before!.n, r.after!.n) < 20
99
+ ? L("; the reason is unclear", ",原因還不明")
100
+ : ""
101
+ }`;
102
+ }
@@ -0,0 +1,24 @@
1
+ import type { Rate, ReportModel } from "../model.ts";
2
+
3
+ export type Lang = "en" | "zh";
4
+ export type Words = (en: string, zh: string) => string;
5
+ export type Change = ReportModel["changes"][number];
6
+ export const words = (lang: Lang): Words => (en, zh) => lang === "zh" ? zh : en;
7
+ export const esc = (s: unknown) =>
8
+ String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
9
+ const formatter = new Intl.NumberFormat("en-US");
10
+ export const num = (n: number) => formatter.format(n);
11
+ export const pct = (r?: Rate) => r?.value != null ? `${(100 * r.value).toFixed(1)}%` : "—";
12
+ export const usd = (v: number | null) => v == null ? "—" : `$${v.toFixed(2)}`;
13
+ export const duration = (v: number | null) =>
14
+ v == null ? "—" : v < 1000 ? `${v} ms` : v < 60_000 ? `${(v / 1000).toFixed(1)} s` : `${(v / 60_000).toFixed(1)} min`;
15
+ export const stamp = (at: string) => `${at.slice(5, 10).replace("-", ".")} ${at.slice(11, 16)}`;
16
+ export const title = (c: Change) => c.package ? `${c.package} ${c.from ?? "∅"} → ${c.to ?? "∅"}` : c.subject;
17
+ /** Cells are text, never markup. */
18
+ export function table(headers: string[], rows: (string | number)[][], L: Words) {
19
+ if (!rows.length) return `<p class="muted">${L("No records in this period.", "這段期間沒有紀錄。")}</p>`;
20
+ const cell = (x: string | number) => esc(typeof x === "number" ? num(x) : x);
21
+ return `<div class="scroll"><table><thead><tr>${headers.map((h) => `<th scope="col">${esc(h)}</th>`).join("")}</tr></thead><tbody>${
22
+ rows.map((r) => `<tr>${r.map((c) => `<td>${cell(c)}</td>`).join("")}</tr>`).join("")
23
+ }</tbody></table></div>`;
24
+ }