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
@@ -0,0 +1,40 @@
1
+ import type { ReportModel } from "../model.ts";
2
+ import type { Preset } from "../ranges.ts";
3
+ import { type Change, esc, type Lang, num, words } from "./format.ts";
4
+
5
+ const KINDS = ["pin", "model-routing", "rule", "agent-role", "skill", "manual"] as const;
6
+
7
+ /** Dense time slots get a count; every change still has its own mark and title. */
8
+ export function changeStrip(m: ReportModel, all: Change[], picks: Change[], ids: Map<Change, string>, lang: Lang, range: Preset | "custom") {
9
+ const L = words(lang), label = (k: Change["kind"]) => m.meta.changeKinds[k][lang];
10
+ const period = typeof range === "number" ? L(`Last ${range} days`, `近 ${range} 天`) : range === "all" ? L("All time", "全部期間") : L("Selected dates", "選定期間");
11
+ const since = m.window.since ?? "", until = m.window.until ?? "", start = Date.parse(since), span = Date.parse(until) + 86400000 - start;
12
+ const x = (c: Change) => 16 + Math.min(1, Math.max(0, (Date.parse(c.at) - start) / span)) * 968;
13
+ const bins = new Map<number, Change[]>(), counts = new Map<string, number>();
14
+ for (const c of all) {
15
+ const slot = Math.floor((x(c) - 16) / 30), cells = bins.get(slot) ?? [];
16
+ cells.push(c); bins.set(slot, cells); counts.set(c.kind, (counts.get(c.kind) ?? 0) + 1);
17
+ }
18
+ const short = { pin: "版本", "model-routing": "模型路由", rule: "規則", "agent-role": "角色", skill: "skill", manual: "手動" };
19
+ const breakdown = KINDS.map(k => `${L(label(k), short[k])} ${num(counts.get(k) ?? 0)}`).join(L(", ", "、"));
20
+ const total = L(`${period}: ${num(all.length)} changes: ${breakdown}; ${picks.length} worth a closer look.`, `${period}共 ${num(all.length)} 筆調整:${breakdown};其中 ${picks.length} 筆值得回看。`);
21
+ const legend = KINDS.map(k => `<span><i class="key kind-${k}"></i>${esc(label(k))}: ${num(counts.get(k) ?? 0)}</span>`).join("");
22
+ const base = 64, marks: string[] = [], labeled = new Map<Change, { px: number; py: number; dot: string }>();
23
+ for (const [slot, cells] of bins) {
24
+ cells.reverse(); // Earliest mark at the left of a dense slot.
25
+ const left = 16 + slot * 30, columns = Math.ceil(cells.length / 5);
26
+ cells.forEach((c, i) => {
27
+ const px = cells.length <= 5 ? x(c) : left + (Math.floor(i / 5) + .5) * 28 / columns;
28
+ const py = base - 6 - i % 5 * 5;
29
+ const dot = `<circle class="change-mark kind-${c.kind}" cx="${px.toFixed(1)}" cy="${py}" r="${Math.min(2.4, 13 / columns)}"><title>${esc(c.at)} · ${esc(label(c.kind))}</title></circle>`;
30
+ if (picks.includes(c)) labeled.set(c, { px, py, dot }); else marks.push(dot);
31
+ });
32
+ if (cells.length > 5) marks.push(`<text class="slot-count" x="${left + 14}" y="28" text-anchor="middle">×${cells.length}</text>`);
33
+ }
34
+ const links = picks.map((c,i) => {
35
+ const {px, py, dot} = labeled.get(c)!, end = px > 700, caption = c.package ? `${c.package} ${c.to ?? ""}` : `${label(c.kind)} · ${c.at.slice(5,16).replace("T", " ")}`;
36
+ const y = 87 + i * 23;
37
+ return `<a href="#${ids.get(c)}"><title>${esc(caption)}</title><path class="guide" d="M${px} ${py}V${y - 6}h${end ? -7 : 7}"/>${dot}<text x="${px + (end ? -10 : 10)}" y="${y}" text-anchor="${end ? "end" : "start"}">${esc(Array.from(caption).length > 48 ? Array.from(caption).slice(0, 47).join("") + "…" : caption)}</text></a>`;
38
+ }).join("");
39
+ return `<section class="change-strip"><h2>${total}</h2><div class="kind-key">${legend}</div><svg viewBox="0 0 1000 ${base + 14 + picks.length * 23}" aria-label="${esc(total)}"><path class="axis" d="M16 ${base}H984"/>${marks.join("")}${links}</svg><div class="ends"><span>${esc(since)}</span><span>${esc(until)} UTC</span></div></section>`;
40
+ }
@@ -21,6 +21,8 @@ header {min-height:75px;flex-wrap:wrap}
21
21
  .brand span {font-size:17px;font-weight:400;padding-left:20px;margin-left:16px;border-left:1px solid var(--line);color:var(--sub)}
22
22
  small,.muted,.intro,.deck,.ends {color:var(--sub)}
23
23
  small,.muted,.ends,summary,.footline,.button {font-size:15px}
24
+ .ranges,.ranges nav {display:flex;align-items:center;gap:6px;flex-wrap:wrap}.ranges {justify-content:space-between;margin-top:18px}
25
+ .ranges a {padding:5px 12px;text-decoration:none;border-radius:6px}.ranges a[aria-current] {background:var(--tint);font-weight:700}
24
26
  .hero {padding:36px 0 20px}
25
27
  .hero h1,.hero-title {font-size:clamp(29px,3.125vw,40px);line-height:1.25;margin:18px 0}
26
28
  .deck,.intro {font-size:19px;margin:0}.hero .deck+.deck {margin-top:24px}
@@ -42,7 +44,13 @@ h3,.big {font-size:29px;line-height:1.35;margin:14px 0 18px}
42
44
  .workload h2 {margin-bottom:0}.workload h3 {margin:25px 0 12px}.workload .muted {margin:5px 0}
43
45
  .workload svg {width:100%;height:auto;display:block;margin-top:8px}
44
46
  .area {fill:var(--area)}.trend {stroke:var(--green);stroke-width:2.5;stroke-linejoin:round;fill:none}
45
- .marker {stroke:var(--warm);stroke-dasharray:3 4}.dot {fill:var(--green)}.ends {margin:4px 0}
47
+ .ends {margin:4px 0}
48
+ .change-strip {margin:18px 0 0;padding:12px 0;border-block:1px solid var(--line)}.change-strip h2 {font-size:19px;margin:0 0 6px}
49
+ .kind-key {display:flex;flex-wrap:wrap;gap:4px 16px;font-size:14px;color:var(--sub)}.key {display:inline-block;width:.7em;height:.7em;border-radius:100%;background:var(--kind);margin-right:5px}
50
+ .kind-pin {--kind:#3b9090}.kind-model-routing {--kind:#736cc9}.kind-rule {--kind:#c78231}.kind-agent-role {--kind:#c16c89}.kind-skill {--kind:#718c40}.kind-manual {--kind:#477dac}
51
+ .change-mark,.work-mark {fill:var(--kind)}.change-strip svg {width:100%;display:block}.change-strip .axis,.change-strip .guide {stroke:var(--line);fill:none}
52
+ .change-strip .slot-count {fill:var(--sub);font:12px sans-serif}.change-strip a text {fill:var(--green);font-size:14px;text-decoration:underline}
53
+ @media(max-width:640px){.change-strip {overflow-x:auto}.change-strip svg {min-width:600px}}
46
54
  .footline {border-top:1px solid var(--line);padding-top:13px;margin:12px 0 0}
47
55
  .lesson,.tint,.after {background:var(--tint)}.lesson {padding:16px 19px}.lesson p {margin:5px 0 0}.side>.lesson {margin-top:16px}
48
56
  .topic {padding:38px 0}.topic h2 {margin:9px 0}.intro {margin:0 0 18px}
@@ -51,6 +59,10 @@ h3,.big {font-size:29px;line-height:1.35;margin:14px 0 18px}
51
59
  .scroll {overflow-x:auto}table {width:100%;border-collapse:collapse;margin:.4rem 0;background:var(--paper)}
52
60
  th,td {text-align:start;padding:7px 12px;border-bottom:1px solid var(--line)}th {font-size:15px;color:var(--green)}
53
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}
54
66
  .checks {margin-top:18px}.checks h3,.topic .panel h3 {font-size:22px}
55
67
  .detail {display:none;padding-bottom:24px;scroll-margin-top:75px}.detail:target {display:block;outline:none}
56
68
  body:has(.detail:target) main {display:none}.back {float:right;font-size:15px}
@@ -65,6 +77,7 @@ body:has(.detail:target) main {display:none}.back {float:right;font-size:15px}
65
77
  .notes-grid {margin:16px 0}.notes-grid .lesson {font-size:16px}
66
78
  footer {font-size:14px;margin-top:24px;padding:18px 0 25px;color:var(--sub);border-top:1px solid var(--line)}
67
79
  @media(max-width:850px) {
80
+ .tiles {grid-template-columns:repeat(2,minmax(0,1fr))}
68
81
  .layout,.pair,.notes-grid {grid-template-columns:1fr}.layout {gap:22px}.rail {padding-left:27px}.rail:before {left:7px}.card:before {left:-26px}
69
82
  .reading {flex-wrap:wrap}.ruler-head,footer {align-items:flex-start;flex-direction:column}
70
83
  }
@@ -1,7 +1,9 @@
1
1
  import type { ReportModel } from "../model.ts";
2
2
  import { concepts, lesson } from "./concepts.ts";
3
- import { finding, type Reading, readings, select, value, verdict } from "./findings.ts";
3
+ import { overview, type Reading, readings, value, verdict } from "./findings.ts";
4
4
  import { type Change, esc, type Lang, num, stamp, title, type Words, words } from "./format.ts";
5
+ import type { Preset } from "../ranges.ts";
6
+ import { changeStrip } from "./strip.ts";
5
7
  import type { Week } from "./week.ts";
6
8
 
7
9
  function card(c: Change, id: string, rs: Reading[], L: Words) {
@@ -91,8 +93,8 @@ ${
91
93
  L("Timeline", "回時間軸")
92
94
  }</a></section>`;
93
95
  }
94
- export function timeline(m: ReportModel, w: Week, lang: Lang) {
95
- const L = words(lang), { all, lead, highlighted, folded } = select(m);
96
+ export function timeline(m: ReportModel, w: Week, lang: Lang, range: Preset | "custom") {
97
+ const L = words(lang), { all, lead, highlighted, folded, headline, trust } = overview(m, lang);
96
98
  const ids = new Map(all.map((c, i) => [c, `change-${i + 1}`]));
97
99
  const metrics = new Map(all.map((c) => [c, readings(c, m, lang)]));
98
100
  const byDay = new Map<string, Change[]>(), byCommit = new Map<string, Change[]>();
@@ -108,29 +110,11 @@ export function timeline(m: ReportModel, w: Week, lang: Lang) {
108
110
  byCommit.get(key)!.push(c);
109
111
  }
110
112
  }
111
- const headline = lead
112
- ? finding(lead, metrics.get(lead)!, L)
113
- : all.length
114
- ? L("Not enough sessions to compare changes yet", "這批調整的工作段數還不夠比較")
115
- : L("No changes recorded in this period", "這段期間沒有調整紀錄");
116
- const reason = lead?.impact;
117
- const trust = lead && reason?.incomplete && reason.confounded && !reason.smallSample
118
- ? L(
119
- `There were ${
120
- num(reason.confounded)
121
- } other changes, and one side has less than ${reason.window.days} days of data. We cannot credit this change alone.`,
122
- `同期還有 ${num(reason.confounded)} 筆別的調整,一側的資料也未滿 ${reason.window.days} 天;目前不能把差異歸給這次調整。`,
123
- )
124
- : lead
125
- ? verdict(lead, metrics.get(lead)!, L)
126
- : L(
127
- `There are ${num(m.totals.sessions)} sessions in this report, but no eligible comparison.`,
128
- `報表收錄 ${num(m.totals.sessions)} 段工作,目前沒有適合放在首頁的比較。`,
129
- );
130
113
  return {
131
114
  lead,
132
115
  headline,
133
116
  trust,
117
+ strip: changeStrip(m, all, highlighted, ids, lang, range),
134
118
  count: highlighted.length,
135
119
  cards: highlighted.map((c) => card(c, ids.get(c)!, metrics.get(c)!, L)).join(""),
136
120
  archive: [...byDay].map(([day, list]) =>
@@ -1,28 +1,34 @@
1
1
  import type { ReportModel } from "../model.ts";
2
2
  import { esc, num, type Words } from "./format.ts";
3
3
 
4
- /** Last seven calendar days ending on the last complete UTC day in the selected period. */
5
- export function week(m: ReportModel) {
6
- const last = m.freshness.lastExtract?.slice(0, 10);
7
- if (!last || !m.window.until || !m.window.since) return [];
8
- const end = Math.min(Date.parse(last) - 86400000, Date.parse(m.window.until));
4
+ /** Workload over the selected dates with records; the extraction day is partial. */
5
+ export function periodRows(m: ReportModel) {
6
+ if (!m.series.days.length || !m.window.until || !m.window.since) return [];
7
+ const end = Math.min(Date.parse(m.freshness.lastExtract?.slice(0, 10) ?? m.window.until), Date.parse(m.window.until));
8
+ const positions = new Map(m.series.days.map((d, i) => [d, i]));
9
+ const changes = new Map<string, Set<string>>(), totals = new Map<string, number>();
10
+ for (const c of m.changes) {
11
+ const day = c.at.slice(0, 10), kinds = changes.get(day) ?? new Set<string>();
12
+ kinds.add(c.kind); changes.set(day, kinds); totals.set(day, (totals.get(day) ?? 0) + 1);
13
+ }
9
14
  const rows = [];
10
- for (let t = Math.max(end - 6 * 86400000, Date.parse(m.window.since)); t <= end; t += 86400000) {
11
- const day = new Date(t).toISOString().slice(0, 10), i = m.series.days.indexOf(day);
15
+ for (let t = Math.max(Date.parse(m.series.days[0]), Date.parse(m.window.since)); t <= end; t += 86400000) {
16
+ const day = new Date(t).toISOString().slice(0, 10), i = positions.get(day) ?? -1;
12
17
  rows.push({
13
18
  day,
14
19
  sessions: m.series.sessions[i] ?? 0,
15
20
  calls: m.series.toolCalls[i] ?? 0,
16
21
  loads: m.series.skillLoads[i] ?? 0,
17
- changes: m.changes.filter((c) => c.at.startsWith(day)).length,
22
+ changes: totals.get(day) ?? 0,
23
+ kinds: [...(changes.get(day) ?? [])],
18
24
  });
19
25
  }
20
26
  return rows;
21
27
  }
22
- export type Week = ReturnType<typeof week>;
28
+ export type Week = ReturnType<typeof periodRows>;
23
29
  export function workload(rows: Week, L: Words) {
24
- const heading = `<h2>${L("This week’s workload", "這週的工作量")}</h2>`;
25
- if (!rows.length) return `<div class="panel">${heading}<p>${L("No complete recorded day yet.", "尚無完整一天的紀錄。")}</p></div>`;
30
+ const heading = `<h2>${L("Workload in this period", "這段期間的工作量")}</h2>`;
31
+ if (!rows.length) return `<div class="panel">${heading}<p>${L("No records in this period.", "這段期間沒有紀錄。")}</p></div>`;
26
32
  const total = (key: "sessions" | "calls" | "loads") => num(rows.reduce((n, r) => n + r[key], 0));
27
33
  const max = Math.max(1, ...rows.map((r) => r.sessions));
28
34
  const points = rows.map((r, i) => [5 + i * 348 / Math.max(1, rows.length - 1), 89 - 64 * r.sessions / max]);
@@ -32,18 +38,16 @@ export function workload(rows: Week, L: Words) {
32
38
  "; ",
33
39
  );
34
40
  return `<div class="panel workload">${heading}<p class="muted">${md(rows[0].day)}–${md(rows.at(-1)!.day)} / ${
35
- L("Volume is not quality", "多寡不代表好壞")
41
+ L("Through the last extract", "統計至上次抽取")
36
42
  }</p><h3>${total("sessions")} ${L("sessions", "段工作")}</h3><p class="muted">${
37
- L("Sessions per day · dashes mark changes", "每日工作段數 · 虛線表示當天有調整")
43
+ L("Sessions per day · colored dots mark changes", "每日工作段數 · 彩點表示當日調整類別")
38
44
  }</p>
39
45
  <svg role="img" aria-label="${esc(desc)}" viewBox="0 0 358 96"><polygon points="5,89 ${line} ${
40
46
  points.at(-1)![0]
41
47
  },89" class="area"/><polyline points="${line}" class="trend"/>${
42
- points.map(([x, y], i) =>
48
+ points.map(([x], i) =>
43
49
  rows[i].changes
44
- ? `<path d="M${x} 12V89" class="marker"/><circle cx="${x}" cy="${y}" r="3.5" class="dot"><title>${esc(rows[i].day)}: ${
45
- rows[i].changes
46
- } ${L("changes", "筆調整")}</title></circle>`
50
+ ? `<g><title>${esc(rows[i].day)}: ${num(rows[i].changes)} ${L("changes", "筆調整")}</title>${rows[i].kinds.map((k,j) => `<circle class="work-mark kind-${esc(k)}" cx="${x}" cy="${5 + 4*j}" r="1.9"/>`).join("")}</g>`
47
51
  : ""
48
52
  ).join("")
49
53
  }</svg>
@@ -0,0 +1,87 @@
1
+ /** The 「工作」 section: one row per work item, a like-with-like comparison, and the items still open. */
2
+ import type { ReportModel } from "../model.ts";
3
+ import type { Comparison, Verdict, WorkModel } from "../work/model.ts";
4
+ import { esc, type Lang, num, usd, type Words, words } from "./format.ts";
5
+
6
+ const SHOWN = 15;
7
+
8
+ export function span(minutes: number, L: Words) {
9
+ if (minutes < 90) return L(`${Math.round(minutes)} min`, `${Math.round(minutes)} 分`);
10
+ if (minutes < 48 * 60) return L(`${(minutes / 60).toFixed(1)} h`, `${(minutes / 60).toFixed(1)} 小時`);
11
+ return L(`${(minutes / 1440).toFixed(1)} days`, `${(minutes / 1440).toFixed(1)} 天`);
12
+ }
13
+
14
+ const pct = (v: number) => `${Math.round(v * 100)}%`;
15
+
16
+ export function verdictText(c: Comparison, v: Verdict, L: Words, lines = false) {
17
+ const g = (value?: string) => c.groups.find((x) => x.value === value);
18
+ const n = (value?: string) => (lines ? g(value)?.nLines : g(value)?.n) ?? 0;
19
+ const what = lines ? L("per 100 changed lines", "每百行") : L("per item", "每件");
20
+ if (v.kind === "single") return v.a ? L(`Only one group (${v.a}): nothing to compare it with.`, `只有一組(${v.a}),沒有可比的對象。`) : L("No items with a line count.", "沒有算得出行數的工作。");
21
+ if (v.kind === "few") return L(`Too few items to tell yet (${v.a} ${n(v.a)}, ${v.b} ${n(v.b)}; each group needs 5).`, `件數太少,還看不出來(${v.a} ${n(v.a)} 件、${v.b} ${n(v.b)} 件,每組至少要 5 件)。`);
22
+ if (v.kind === "same") return L(`${v.a} and ${v.b} cost about the same ${what} (less than 20% apart).`, `${v.a} 和 ${v.b} ${what}花費差不到兩成,看不出差別。`);
23
+ return L(`${v.a} costs ${pct(v.by ?? 0)} less ${what} than ${v.b} (median of ${n(v.a)} and ${n(v.b)} items of the same kind). This is a difference, not its cause.`, `${v.a} ${what}比 ${v.b} 便宜 ${pct(v.by ?? 0)}(同類工作的中位數,各 ${n(v.a)}、${n(v.b)} 件)。這是差異,不是原因。`);
24
+ }
25
+
26
+ function stallText(stalls: Record<string, number>, m: ReportModel, lang: Lang) {
27
+ const L = words(lang);
28
+ const parts = Object.entries(stalls)
29
+ .sort((a, b) => b[1] - a[1])
30
+ .map(([k, v]) => `${m.meta.stallKinds[k]?.[lang] ?? k} ${span(v, L)}`);
31
+ return parts.join(L(", ", "、")) || "—";
32
+ }
33
+
34
+ export function workSection(m: ReportModel, lang: Lang, cards: { attribution: string[]; cheaper: string[] }, lesson: (c: string[], L: Words) => string) {
35
+ const L = words(lang);
36
+ const w = m.work;
37
+ 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>`;
38
+ if (!w) return `${head}<p class="intro">${L("Run /evals extract to build the work items.", "請執行 /evals extract 建立工作項目。")}</p></section>`;
39
+ const meta = m.meta.metrics;
40
+ const close = (k: string) => m.meta.closeKinds[k]?.[lang] ?? k;
41
+ const dims: Record<string, string> = { role: L("role", "角色"), model: L("model", "模型"), anchorloop: L("anchorloop version", "anchorloop 版本") };
42
+ const kinds: Record<string, string> = { delegated: L("Work handed to subagents", "交給子代理做的工作"), self: L("Work the main agent did itself", "主代理自己做的工作") };
43
+ const stallTotal = Object.values(w.stallMs).reduce((s, v) => s + v, 0);
44
+ const row = (r: WorkModel["list"][number]) =>
45
+ `<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>`;
46
+ 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>`;
47
+ const list = w.list.length
48
+ ? `<div class="scroll"><table class="items">${listHead}<tbody>${w.list.slice(0, SHOWN).map(row).join("")}</tbody></table></div>${
49
+ 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>` : ""
50
+ }`
51
+ : `<p class="muted">${L("No item closed in this period.", "這段期間沒有收尾的工作。")}</p>`;
52
+ const compare = w.compare.length
53
+ ? w.compare
54
+ .map(
55
+ (c) =>
56
+ `<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>${
57
+ 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("")
58
+ }</tbody></table></div><p class="verdict">${esc(verdictText(c, c.verdict, L))}</p><p class="muted">${esc(verdictText(c, c.verdictLines, L, true))}</p></article>`,
59
+ )
60
+ .join("")
61
+ : `<p class="muted">${L("No finished items to compare.", "沒有可比較的已完成工作。")}</p>`;
62
+ const open = w.open.length
63
+ ? `<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>${
64
+ w.open
65
+ .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>`)
66
+ .join("")
67
+ }</tbody></table></div>`
68
+ : `<p class="muted">${L("Nothing open in this period.", "這段期間沒有還開著的工作。")}</p>`;
69
+ 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>`;
70
+ const kindRows = Object.entries(w.closeKinds).filter(([, n]) => n > 0).map(([k, n]) => `${esc(close(k))} ${num(n)}`).join(L(", ", "、"));
71
+ return `${head}<p class="intro">${
72
+ L(
73
+ "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.",
74
+ "一項工作就是待辦清單上的一列:從它被切到「進行中」開始,到標成完成或刪除為止。開始前排隊的時間不算。",
75
+ )
76
+ }</p><div class="tiles">${
77
+ 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)}`))
78
+ }${
79
+ 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)}(估算)`))
80
+ }${
81
+ 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)}`))
82
+ }${
83
+ 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)))
84
+ }</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">${
85
+ L("Each panel compares only items of the same kind; a group needs at least 5 items.", "每一格只比同一類的工作;每組至少 5 件才下結論。")
86
+ }</p><div class="pair">${compare}</div><h3>${L("Still open: stopped where, waiting on whom, for how long", "還開著的工作:停在哪、等誰、多久")}</h3>${open}</section>`;
87
+ }
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";
package/src/trends.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { DayAgg } from "./aggregate.ts";
2
+ import type { DaysIndex } from "./build.ts";
3
+ import { ownerFor, sumDays } from "./model.ts";
4
+
5
+ const DAY = 86_400_000;
6
+
7
+ /** Counts by event date; session counts by skill in the index use session start date. */
8
+ export function recentDays(index: DaysIndex, project?: string) {
9
+ if (!index.lastExtract || !index.range.start) return [];
10
+ const end = Date.parse(index.lastExtract.slice(0, 10));
11
+ const dates = Array.from({ length: 14 }, (_, i) => new Date(end - (14 - i) * DAY).toISOString().slice(0, 10));
12
+ const rows = new Map(sumDays(index, { project, since: dates[0], until: dates[13] }).perDay);
13
+ return dates.filter(d => d >= index.range.start.slice(0, 10)).map(day => ({ day, agg: rows.get(day) }));
14
+ }
15
+
16
+ interface Count { errors: number; calls: number }
17
+ export function trendPair(r: { before: Count; after: Count }) {
18
+ const side = (c: Count) => `${c.errors}/${c.calls} (${(100 * c.errors / c.calls).toFixed(1)}%)`;
19
+ return `${side(r.before)} → ${side(r.after)}`;
20
+ }
21
+ const zero = (): Count => ({ errors: 0, calls: 0 });
22
+ function add(into: Count, from: Count) { into.errors += from.errors; into.calls += from.calls; }
23
+ export function packageCounts(index: DaysIndex, day?: DayAgg) {
24
+ const by = new Map<string, Count>();
25
+ for (const [tool, count] of Object.entries(day?.tools ?? {})) {
26
+ const owner = ownerFor(index, tool), total = by.get(owner) ?? zero();
27
+ add(total, count);
28
+ by.set(owner, total);
29
+ }
30
+ return by;
31
+ }
32
+
33
+ function week(index: DaysIndex, rows: ReturnType<typeof recentDays>) {
34
+ const packages = new Map<string, Count>(), monitors = zero();
35
+ for (const { agg } of rows) {
36
+ for (const [owner, count] of packageCounts(index, agg)) {
37
+ const total = packages.get(owner) ?? zero();
38
+ add(total, count);
39
+ packages.set(owner, total);
40
+ }
41
+ if (agg) add(monitors, { errors: agg.monitors.statuses.error ?? 0, calls: agg.monitors.finished });
42
+ }
43
+ return { packages, monitors };
44
+ }
45
+
46
+ function rise(before: Count | undefined, after: Count) {
47
+ if (!before || Math.min(before.calls, after.calls) < 20) return;
48
+ // Compare integer counts before rounding the displayed rates (threshold: five percentage points).
49
+ const diff = after.errors * before.calls - before.errors * after.calls;
50
+ if (20 * diff >= before.calls * after.calls) return { before, after, delta: diff / before.calls / after.calls };
51
+ }
52
+ export function weeklyRises(index: DaysIndex, since?: string, project?: string) {
53
+ const rows = recentDays(index, project);
54
+ if (rows.length !== 14 || (since && Date.parse(rows[0].day) < Date.parse(since) - 86400000)) return;
55
+ const prev = week(index, rows.slice(0, 7)), curr = week(index, rows.slice(7));
56
+ const packages = [...curr.packages].flatMap(([name, count]) => {
57
+ const r = rise(prev.packages.get(name), count);
58
+ return r ? [{ name, ...r }] : [];
59
+ }).sort((a, b) => b.delta - a.delta || b.after.calls - a.after.calls || a.name.localeCompare(b.name));
60
+ return { start: rows[0].day, end: rows[13].day, packages, monitors: rise(prev.monitors, curr.monitors) };
61
+ }