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/dist/ops.js CHANGED
@@ -5,9 +5,11 @@ import { buildIndex, loadIndex, loadRows } from "./build.js";
5
5
  import { addMark, readChanges } from "./changes.js";
6
6
  import { coverage } from "./coverage.js";
7
7
  import { extract, loadCheckpoint } from "./extract/run.js";
8
+ import { PRESETS, rangeFilter, suffix } from "./ranges.js";
8
9
  import { buildModel } from "./model.js";
9
10
  import { agentDir, home, layout, loadSettings, stateDir } from "./paths.js";
10
11
  import { renderHtml } from "./render.js";
12
+ import { loadWork } from "./work/join.js";
11
13
  export function context(env = process.env) {
12
14
  const settings = loadSettings(env);
13
15
  const lay = layout(stateDir(env));
@@ -38,35 +40,64 @@ export function coverageNow(env, cutDays) {
38
40
  const ctx = context(env);
39
41
  return coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), cutDays ?? ctx.settings.coverageDays);
40
42
  }
41
- export function model(filter, env, withCoverage = true) {
42
- const ctx = context(env);
43
- const index = loadIndex(ctx.layout);
43
+ function coverageReader(ctx, now) {
44
+ const activity = new Map();
45
+ const cov = coverage(ctx.roots, loadCheckpoint(ctx.layout.checkpoint), ctx.settings.coverageDays, now.getTime(), activity);
46
+ return (filter) => {
47
+ const inRange = { files: 0, indexed: 0 };
48
+ for (const [day, a] of activity)
49
+ if ((!filter.since || day >= filter.since) && (!filter.until || day <= filter.until)) {
50
+ inRange.files += a.files;
51
+ inRange.indexed += a.indexed;
52
+ }
53
+ return { ...cov, inRange };
54
+ };
55
+ }
56
+ export function coverageInRange(input, env) {
57
+ const ctx = context(env), now = new Date(), last = loadIndex(ctx.layout)?.lastExtract;
58
+ const filter = rangeFilter(input, last ?? now.toISOString());
59
+ return { filter, last, coverage: coverageReader(ctx, now)(filter) };
60
+ }
61
+ function snapshot(env, withCoverage = true) {
62
+ const ctx = context(env), index = loadIndex(ctx.layout);
44
63
  if (!index)
45
- return undefined;
46
- return buildModel({
47
- index,
48
- rows: loadRows(ctx.layout),
49
- changes: readChanges(ctx.layout.changes),
50
- filter,
51
- windowDays: ctx.settings.impactWindowDays,
52
- labelsFile: ctx.layout.labels,
53
- sessionEvalsFile: ctx.layout.sessionEvals,
54
- coverage: withCoverage ? coverageNow(env) : undefined,
55
- });
64
+ return;
65
+ const rows = loadRows(ctx.layout), changes = readChanges(ctx.layout.changes), now = new Date(), work = loadWork(ctx.layout);
66
+ const cov = withCoverage ? coverageReader(ctx, now) : undefined;
67
+ return { index, build(input, preset, comparisons) {
68
+ const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
69
+ return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays,
70
+ labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
71
+ } };
72
+ }
73
+ export function indexedModel(filter, env, withCoverage = true) {
74
+ const data = snapshot(env, withCoverage);
75
+ return data && { report: data.build(filter, 30), index: data.index };
76
+ }
77
+ export function model(filter, env, withCoverage = true) {
78
+ return indexedModel(filter, env, withCoverage)?.report;
56
79
  }
57
80
  /** Builds the report; returns the HTML path, or undefined when nothing was extracted yet. */
58
81
  export function runReport(options = {}) {
59
82
  const ctx = context(options.env);
60
- const m = model(options.filter ?? {}, options.env);
61
- if (!m)
62
- return undefined;
83
+ const data = snapshot(options.env), filter = options.filter ?? {};
84
+ if (!data)
85
+ return;
63
86
  const dir = resolve(options.outDir ?? ctx.layout.reports);
64
87
  mkdirSync(dir, { recursive: true });
65
- const html = join(dir, "report.html");
66
- const json = join(dir, "model.json");
67
- writeFileSync(json, JSON.stringify(m, null, 1));
68
- writeFileSync(html, renderHtml(m, options.lang ?? "zh"));
69
- return { html, json };
88
+ const write = (m, range) => {
89
+ const html = join(dir, `report${suffix(range)}.html`), json = join(dir, `model${suffix(range)}.json`);
90
+ writeFileSync(json, JSON.stringify(m, null, 1));
91
+ writeFileSync(html, renderHtml(m, options.lang ?? "zh", range));
92
+ return { html, json };
93
+ };
94
+ if (filter.since || filter.until || filter.days !== undefined)
95
+ return write(data.build(filter, 30), "custom");
96
+ const all = data.build(filter, "all");
97
+ for (const p of PRESETS)
98
+ if (p !== 30)
99
+ write(p === "all" ? all : data.build(filter, p, all.changes), p);
100
+ return write(data.build(filter, 30, all.changes), 30);
70
101
  }
71
102
  export function reportPath(env) {
72
103
  return join(context(env).layout.reports, "report.html");
package/dist/paths.js CHANGED
@@ -70,6 +70,9 @@ export function layout(state = stateDir()) {
70
70
  labels: join(state, "labels.jsonl"),
71
71
  status: join(state, "index", "status.json"),
72
72
  reports: join(state, "reports"),
73
+ items: join(state, "index", "items.json"),
74
+ itemRecords: join(state, "index", "workitems.jsonl"),
75
+ lines: join(state, "index", "lines.json"),
73
76
  };
74
77
  }
75
78
  /** UTC day of an epoch-ms or ISO time. */
package/dist/query.js CHANGED
@@ -1,6 +1,9 @@
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.js";
3
- export const VIEWS = ["skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"];
2
+ import { coverageInRange, indexedModel, reportPath } from "./ops.js";
3
+ import { findings } from "./findings.js";
4
+ import { select } from "./report/findings.js";
5
+ import { itemsView } from "./work/query.js";
6
+ export const VIEWS = ["findings", "items", "skills", "packages", "ask_user", "monitors", "subagents", "process", "cost", "changes", "coverage"];
4
7
  export const MAX_BYTES = 1900;
5
8
  const pct = (r) => (r && r.value !== null ? `${(r.value * 100).toFixed(1)}% (n=${r.n})` : `n/a (n=${r?.n ?? 0})`);
6
9
  const sec = (v) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)}s`);
@@ -8,24 +11,34 @@ const sec = (v) => (v === null ? "n/a" : `${(v / 1000).toFixed(1)}s`);
8
11
  export function bound(text, limit = MAX_BYTES) {
9
12
  if (Buffer.byteLength(text) <= limit)
10
13
  return text;
11
- const lines = text.split("\n");
12
- while (lines.length > 1 && Buffer.byteLength(`${lines.join("\n")}\n…`) > limit)
13
- lines.splice(lines.length - 2, 1);
14
- return `${lines.join("\n")}\n…`.slice(0, limit);
14
+ const lines = text.split("\n"), tail = lines.at(-1) ?? "";
15
+ const suffix = tail.startsWith("report: ") && Buffer.byteLength(tail) < limit / 2 ? `\n…\n${tail}` : "\n…";
16
+ const kept = [];
17
+ for (const line of lines) {
18
+ if (Buffer.byteLength([...kept, line].join("\n") + suffix) > limit)
19
+ break;
20
+ kept.push(line);
21
+ }
22
+ return kept.join("\n") + suffix;
15
23
  }
16
24
  export function query(view, options = {}) {
17
25
  if (view === "coverage") {
18
- const c = coverageNow(options.env);
26
+ const { coverage: c, filter, last } = coverageInRange(options, options.env);
19
27
  return bound([
28
+ `${filter.since}..${filter.until} UTC; last extract ${last ?? "never"}; live cleanup check across all dates and projects`,
20
29
  `coverage, sessions inactive > ${c.cutDays} days (before ${c.cutoff.slice(0, 10)}):`,
21
30
  `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}`,
31
+ `modified in report dates (all projects): ${c.inRange?.indexed ?? 0}/${c.inRange?.files ?? 0} files indexed`,
22
32
  `all files: ${c.all.indexedFiles}/${c.all.files} indexed; index keeps ${c.retainedGone} sessions whose file is gone`,
23
33
  "meaning: only indexed files keep their numbers if the session files are cleaned up",
24
34
  ].join("\n"));
25
35
  }
26
- const m = model({ since: options.since, project: options.project }, options.env, false);
27
- if (!m)
36
+ const data = indexedModel(options, options.env, view === "findings");
37
+ if (!data)
28
38
  return "pi-evals: nothing extracted yet; the user can run /evals extract.";
39
+ const { report: m, index } = data;
40
+ if (view === "findings")
41
+ return bound(findings(m), 1499);
29
42
  const head = [
30
43
  `pi-evals ${view} · ${m.window.since ?? "?"}..${m.window.until ?? "?"}${m.window.project ? ` · project ${m.window.project}` : ""} · sessions ${m.totals.sessions}`,
31
44
  m.freshness.stale ? `STALE: last extract ${m.freshness.lastExtract ?? "never"} (${m.freshness.ageHours ?? "?"}h ago); /evals extract refreshes` : `last extract ${m.freshness.lastExtract}`,
@@ -39,6 +52,9 @@ export function query(view, options = {}) {
39
52
  body.push(`offered but never loaded (${m.skills.neverLoaded.length}/${m.skills.offered}): ${m.skills.neverLoaded.slice(0, 25).join(", ")}`);
40
53
  }
41
54
  else if (view === "packages") {
55
+ const w = m.weekly;
56
+ for (const p of w?.packages.slice(0, 3) ?? [])
57
+ body.push(`${p.name} weekly errors/calls: ${p.before.errors}/${p.before.calls} -> ${p.after.errors}/${p.after.calls}`);
42
58
  body.push("package: calls, error rate, avg time");
43
59
  for (const p of m.packages.slice(0, 15))
44
60
  body.push(`${p.owner}${p.version ? `@${p.version}` : ""}: ${p.calls}, ${pct(p.errorRate)}, ${sec(p.avgMs)}`);
@@ -49,12 +65,15 @@ export function query(view, options = {}) {
49
65
  body.push(`answer source: ${Object.entries(a.sources).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
50
66
  }
51
67
  else if (view === "monitors") {
68
+ const w = m.weekly?.monitors;
69
+ if (w)
70
+ body.push(`weekly jobs ending in error: ${w.before.errors}/${w.before.calls} -> ${w.after.errors}/${w.after.calls}`);
52
71
  const mo = m.monitors;
53
72
  body.push(`started ${mo.started}; ending recorded ${mo.finished}; avg duration ${sec(mo.avgMs)} (n=${mo.durationN})`);
54
73
  body.push(`outcomes: ${Object.entries(mo.statuses).map(([k, v]) => `${k} ${v}`).join(", ") || "n/a"}`);
55
74
  }
56
75
  else if (view === "subagents") {
57
- body.push(`subagent sessions ${m.subagents.sessions}; linked to parent ${m.subagents.linked}/${m.subagents.subagentTotal} (all time)`);
76
+ 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}`}`);
58
77
  body.push("role / model: launches");
59
78
  for (const l of m.subagents.launches.slice(0, 12))
60
79
  body.push(`${l.role} / ${l.model}: ${l.n}`);
@@ -77,15 +96,19 @@ export function query(view, options = {}) {
77
96
  for (const s of m.cost.bySkill.slice(0, 10))
78
97
  body.push(`${s.skill}: $${s.cost} over ${s.sessions} sessions`);
79
98
  }
99
+ else if (view === "items") {
100
+ body.push(...itemsView(m.work));
101
+ }
80
102
  else if (view === "changes") {
81
- 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");
82
- for (const c of m.changes.slice(-8).reverse()) {
103
+ 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");
104
+ const { highlighted, folded } = select(m);
105
+ for (const c of [...highlighted, ...folded].slice(0, 8)) {
83
106
  const what = c.package ? `${c.package} ${c.from ?? "-"}->${c.to ?? "-"}` : c.subject.slice(0, 60);
84
107
  const i = c.impact;
85
108
  const fx = i
86
109
  ? `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}` : ""}`
87
110
  : "no data before";
88
- body.push(`${c.at.slice(0, 10)} ${c.kind} ${what}: ${fx}`);
111
+ body.push(`${c.at} ${c.kind} ${what}: ${fx}`);
89
112
  }
90
113
  }
91
114
  return bound([...head, ...body, `report: ${reportPath(options.env)}`].join("\n"));
package/dist/ranges.js ADDED
@@ -0,0 +1,14 @@
1
+ export const PRESETS = [14, 30, 90, "all"];
2
+ export const suffix = (r) => r === 30 ? "" : typeof r === "number" ? `-${r}d` : `-${r}`;
3
+ /** Calendar ranges include the (possibly partial) UTC day of the last extraction. */
4
+ export function rangeFilter(input, end, preset = 30) {
5
+ const until = input.until ?? end.slice(0, 10), days = input.days ?? preset;
6
+ if (input.since && input.days !== undefined)
7
+ throw new Error("Choose either --days or --since.");
8
+ if (days !== "all" && (!Number.isSafeInteger(days) || days < 1 || days > 365000))
9
+ throw new Error("--days must be a positive integer (at most 365000).");
10
+ 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))
11
+ throw new Error("since must be YYYY-MM-DD.");
12
+ const since = input.since ?? (days === "all" ? undefined : new Date(Date.parse(until) - (days - 1) * 86400000).toISOString().slice(0, 10));
13
+ return { since, until, project: input.project };
14
+ }
package/dist/render.js CHANGED
@@ -3,10 +3,20 @@ import { esc, num, words } from "./report/format.js";
3
3
  import { sections } from "./report/sections.js";
4
4
  import { css } from "./report/style.js";
5
5
  import { timeline } from "./report/timeline.js";
6
- import { week, workload } from "./report/week.js";
7
- export function renderHtml(m, lang = "zh") {
8
- const L = words(lang), w = week(m), t = timeline(m, w, lang), c = concepts(m, w, t.lead, L);
6
+ import { PRESETS, suffix } from "./ranges.js";
7
+ import { trendPair } from "./trends.js";
8
+ import { periodRows, workload } from "./report/week.js";
9
+ function weeklyPanel(m, L) {
10
+ const w = m.weekly, p = w?.packages[0];
11
+ if (!w || (!p && !w.monitors))
12
+ return "";
13
+ 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)}`];
14
+ 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>`;
15
+ }
16
+ export function renderHtml(m, lang = "zh", range = "custom") {
17
+ const L = words(lang), w = periodRows(m), t = timeline(m, w, lang, range), c = concepts(m, w, t.lead, L);
9
18
  const nav = [
19
+ ["work", L("Work items", "工作")],
10
20
  ["archive", L("All changes", "所有調整")],
11
21
  ["skills", L("Skills", "技能")],
12
22
  ["packages", L("Tools", "套件與工具")],
@@ -21,10 +31,10 @@ export function renderHtml(m, lang = "zh") {
21
31
  ];
22
32
  const date = m.generated.slice(0, 10);
23
33
  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 · ${L("Change timeline", "調整時間軸")}</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>${L("Agent work, observed", "代理工作觀察")}</span></a><small>${esc(date)} ${L("report", "更新")} / ${L("All times UTC", "時間皆為 UTC")}</small></header>
24
- <main id="timeline"><div class="hero"><p class="eyebrow">${L("Change journal / Newest first", "調整紀事 / 依更新時間排列")}</p><h1>${esc(t.headline)}</h1><p class="deck">${esc(t.trust)}</p>${m.freshness.stale
34
+ <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>${esc(t.headline)}</h1><p class="deck">${esc(t.trust)}</p>${m.freshness.stale
25
35
  ? `<p class="stale">${L("Last extract", "上次抽取")}:${esc(m.freshness.lastExtract ?? "—")} · ${L("Refresh with /evals extract.", "資料過時,請執行 /evals extract。")}</p>`
26
36
  : ""}</div>
27
- <div class="spine"><h2>${L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)}</h2><div class="layout"><div class="rail">${t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`}</div><aside class="side">${workload(w, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${L("How to read the comparisons", "怎麼讀時間軸上的比較?")}</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
37
+ <div class="spine"><h2>${L(`${t.count} changes worth a closer look`, `${t.count === 2 ? "兩" : t.count === 1 ? "一" : "零"}筆值得回看的調整`)}</h2><div class="layout"><div class="rail">${t.cards || `<p>${L("Nothing to highlight yet.", "還沒有適合比較的調整。")}</p>`}</div><aside class="side">${workload(w, L)}${weeklyPanel(m, L)}${lesson(c.record, L)}${lesson(c.metric, L)}</aside></div><details><summary>${L("How to read the comparisons", "怎麼讀時間軸上的比較?")}</summary><div class="notes-grid">${lesson(c.sample, L)}${lesson(c.confounding, L)}${lesson(c.check, L)}</div></details></div>
28
38
  <nav class="jump" aria-label="${L("Report sections", "報表章節")}">${nav.map(([id, text]) => `<a href="#${id}">${text}</a>`).join("")}</nav><section class="topic" id="archive"><h2>${L("Other changes by day", "按日期查其餘調整")}</h2><p>${L("Open a day for its changes. Each link opens the before-and-after comparison.", "展開一天,點選調整名稱,就能看到它的前後比較。")}</p>${t.archive || "—"}</section>
29
39
  <p class="muted">${esc(m.window.project ?? L("All projects", "全部專案"))} · ${esc(m.window.since ?? "—")} → ${esc(m.window.until ?? "—")} · ${num(m.totals.sessions)} ${L("sessions", "段工作")} · ${num(m.totals.prompts)} ${L("prompts", "次提示")}</p>${sections(m, lang, c)}</main>
30
40
  ${t.details}<footer><b>PI-EVALS / ${L("Change timeline", "調整時間軸")}</b><span>${esc(m.window.project ?? L("All projects", "全部專案"))} · ${L("Transcript text not included", "統計不含對話原文")}</span></footer></body></html>`;
@@ -1,4 +1,25 @@
1
- import { esc, num } from "./format.js";
1
+ import { esc, num, usd } from "./format.js";
2
+ import { verdictText } from "./work.js";
3
+ /** The two work-item ideas, with this report's own numbers. */
4
+ function workCards(m, L) {
5
+ const w = m.work;
6
+ if (!w) {
7
+ const none = L("Run /evals extract to see the numbers.", "請執行 /evals extract 看這段期間的數字。");
8
+ return { attribution: [L("Who a cost belongs to", "花費歸屬"), none], cheaper: [L("When is one way cheaper?", "怎麼比才算比較省"), none] };
9
+ }
10
+ const first = w.compare.find((c) => c.kind === "delegated") ?? w.compare[0];
11
+ const now = first ? verdictText(first, first.verdict, L) : L("No finished items to compare yet.", "還沒有完成的工作可以比。");
12
+ return {
13
+ attribution: [
14
+ L("Who a cost belongs to", "花費歸屬"),
15
+ L(`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.`, `子代理的花費是精確的:對到某項工作的子代理工作階段,每次回覆的費用全部加起來;這段期間 ${num(w.delegated)} 件交給子代理的工作共 ${usd(w.cost.child)}。主代理的花費是估算:主代理同時照顧好幾件事,所以它每次回覆的費用,平均分給當下進行中的工作(同時兩件就各算一半;有 ${num(w.shared)} 件和別件重疊),共 ${usd(w.cost.main)}。另有 ${usd(w.cost.unattributed)} 的主代理費用不在任何工作進行中,不算進任何一件。`),
16
+ ],
17
+ cheaper: [
18
+ L("When is one way cheaper?", "怎麼比才算比較省"),
19
+ L(`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}`, `三件事都要做到。一、只比同類:交給子代理的跟交給子代理的比,主代理自己做的跟自己做的比。二、看規模:用每百行改動的花費,這段期間 ${num(w.completed)} 件完成的工作裡有 ${num(w.withLines)} 件算得出行數。三、件數要夠:每組至少 ${w.minItems} 件。目前:${now}`),
20
+ ],
21
+ };
22
+ }
2
23
  export function concepts(m, week, c, L) {
3
24
  const i = c?.impact, n = num(week.reduce((s, r) => s + r.sessions, 0)), d = m.process.detectors.find((r) => r.name === "anchor_before_first_edit");
4
25
  return {
@@ -22,6 +43,7 @@ export function concepts(m, week, c, L) {
22
43
  ? L(`There were ${num(i.confounded)} other changes in these windows. If a rule and a package changed together, their effects cannot be separated here.`, `這段期間另有 ${num(i.confounded)} 筆調整。規則和套件若一起改,只比前後分不出哪一項影響了結果。`)
23
44
  : L(`There are ${num(m.changes.length)} changes on this timeline. Check what else changed before crediting a new version.`, `時間軸有 ${num(m.changes.length)} 筆調整。要把差異歸給某個版本,得先查同一期間還改了什麼。`),
24
45
  ],
46
+ ...workCards(m, L),
25
47
  check: [
26
48
  L("Code check", "程式檢查"),
27
49
  L(`In ${num(d?.passRate.n ?? 0)} eligible sessions, code checked whether the agent named a check before editing. It cannot judge whether that check tested the right thing.`, `程式在 ${num(d?.passRate.n ?? 0)} 段適用的工作裡查「改檔前有沒有先說怎麼驗證」。它看得出先後順序,判斷不了方法好不好。`),
@@ -34,7 +34,7 @@ export function verdict(c, rs, L) {
34
34
  notes.push(L(`less than ${i.window.days} days on one side`, `一側未滿 ${i.window.days} 天`));
35
35
  if (!rs.some(comparable))
36
36
  notes.push(L("no comparable readings", "沒有可比較的數字"));
37
- const other = i.confounded ? L(`${num(i.confounded)} other changes in the same period`, `同期還有 ${num(i.confounded)} 筆別的調整`) : "";
37
+ const other = i.confounded ? L(`${num(i.confounded)} other changes in the same period`, `同期還有 ${num(i.confounded)} 筆別的調整`) + L("; we cannot tell which change mattered", ",無法分辨是哪一筆造成的") : "";
38
38
  if (notes.length || other) {
39
39
  return [notes.length ? L(`Too early to tell: ${notes.join("; ")}`, `還看不出來(${notes.join("、")})`) : "", other].filter(Boolean)
40
40
  .join(" · ");
@@ -57,6 +57,17 @@ export function select(m) {
57
57
  const highlighted = all.filter((c) => c === lead || c === second);
58
58
  return { all, lead, highlighted, folded: all.filter((c) => !highlighted.includes(c)) };
59
59
  }
60
+ /** Editorial choices shared by the HTML timeline and the compact query. */
61
+ export function overview(m, lang) {
62
+ const selected = select(m), { lead, all } = selected, L = words(lang);
63
+ const rs = lead ? readings(lead, m, lang) : [];
64
+ const headline = lead ? finding(lead, rs, L) : all.length
65
+ ? L("Not enough sessions to compare changes yet", "這批調整的工作段數還不夠比較")
66
+ : L("No changes recorded in this period", "這段期間沒有調整紀錄");
67
+ const i = lead?.impact;
68
+ const trust = i?.incomplete && i.confounded && !i.smallSample ? L(`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.`, `同期還有 ${num(i.confounded)} 筆別的調整,一側的資料也未滿 ${i.window.days} 天;目前不能把差異歸給這次調整。`) : lead ? verdict(lead, rs, L) : L(`There are ${num(m.totals.sessions)} sessions in this report, but no eligible comparison.`, `報表收錄 ${num(m.totals.sessions)} 段工作,目前沒有適合放在首頁的比較。`);
69
+ return { ...selected, headline, trust };
70
+ }
60
71
  export function finding(c, rs, L) {
61
72
  const r = rs.find(comparable);
62
73
  if (!r)
@@ -1,5 +1,6 @@
1
1
  import { lesson, selfCheck } from "./concepts.js";
2
2
  import { duration, esc, num, pct, table, usd, words } from "./format.js";
3
+ import { workSection } from "./work.js";
3
4
  export function sections(m, lang, cards) {
4
5
  const L = words(lang), meta = m.meta.metrics;
5
6
  const label = (id) => meta[id].label[lang];
@@ -29,7 +30,7 @@ export function sections(m, lang, cards) {
29
30
  const monitors = section("monitors", L("Background jobs", "背景工作"), meta.monitor_outcomes.meaning[lang], `<p>${L("Started", "啟動")} ${num(mon.started)} / ${L("Ending recorded", "有結束紀錄")} ${num(mon.finished)} / ${label("monitor_duration_ms")} ${duration(mon.avgMs)}(${num(mon.durationN)})</p>${T([L("Outcome", "結果"), L("Count", "次數")], entries(mon.statuses))}<p class="muted">${esc(meta.monitor_outcomes.howComputed[lang])}</p>`);
30
31
  const sub = section("subagents", L("Work handed to other agents", "交給子代理的工作"), meta.subagent_launches.meaning[lang], T([L("Role", "角色"), L("Model", "模型"), L("Launches", "啟動次數")], s.launches.slice(0, 40).map((r) => [r.role, r.model, r.n])) +
31
32
  more(label("subagent_cost"), T([L("Role", "角色"), L("USD", "美元")], s.costByRole.map((r) => [r.role, usd(r.cost)]))) +
32
- `<p>${L("Linked to a parent across the index", "整份索引中能對回母工作階段的子代理")}:${num(s.linked)} / ${num(s.subagentTotal)}</p>`);
33
+ `<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>`);
33
34
  const process = section("process", L("Did the agent follow the steps?", "工作有沒有照說好的步驟走?"), L(`Only sessions starting from ${m.process.eraStart} are judged. Earlier work is not a failure.`, `只檢查 ${m.process.eraStart} 起的工作;更早的工作不算失敗。`), lesson(cards.check, L) + `<div class="pair checks">${m.process.detectors.map((d) => {
34
35
  const md = m.meta.detectors[d.name];
35
36
  return `<article class="panel"><p class="eyebrow">${L("Code check", "程式檢查")} / ${L("higher is better", "越高越好")}</p><h3>${esc(md.label[lang])}</h3><p class="big">${pct(d.passRate)} <small>${num(d.pass)} / ${num(d.passRate.n)} ${L("sessions", "段")}</small></p><p>${esc(md.howComputed[lang])}</p><p><b>${L("Pass", "通過")}</b> ${esc(md.example.pass[lang])}<br><b>${L("Fail", "未通過")}</b> ${esc(md.example.fail[lang])}</p>${more(L("By day and version", "查看每日與各版本的通過數"), T([L("Day", "日期"), L("Pass", "通過"), L("Fail", "未通過")], d.perDay.map((r) => [r.day, r.pass, r.fail])) +
@@ -41,12 +42,13 @@ export function sections(m, lang, cards) {
41
42
  more(L("Daily spend and model replies", "查看每日費用與各模型回覆數"), daily(m.series.cost) + T([L("Model", "模型"), L("Replies", "回覆數")], m.cost.byModel.map((r) => [r.model, r.replies]))));
42
43
  const cov = m.coverage;
43
44
  const coverage = section("coverage", L("When is cleanup safe?", "何時可以開啟清理?"), L("Only consider cleanup when all old files match the index, by both file count and bytes. This report never deletes a file.", "所有舊檔的大小和修改時間都要和索引相符,未建索引的檔案數和位元組數都歸零,才考慮開啟清理。報表不會刪檔。"), cov
44
- ? `<p>${L("Inactive days", "閒置天數")} &gt; ${cov.cutDays} / ${L("Files indexed", "已建索引")} ${num(cov.indexed.files)} / ${num(cov.old.files)}</p><p>${L("Not indexed", "未建索引")}:${num(cov.notIndexed.files)} ${L("files", "個檔案")} · ${num(cov.notIndexed.bytes)} bytes</p>`
45
+ ? `<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)} / ${num(cov.old.files)}</p><p>${L("Not indexed", "未建索引")}:${num(cov.notIndexed.files)} ${L("files", "個檔案")} · ${num(cov.notIndexed.bytes)} bytes</p>`
45
46
  : `<p>${L("Coverage not measured; keep cleanup off.", "沒有索引覆蓋資料,請勿開啟清理。")}</p>`);
46
- const labels = section("labels", L("Your labels", "你的標記"), meta.agreement.meaning[lang], m.labels.present && m.labels.n
47
- ? T([L("Check", "檢查"), L("Labelled", "已標記"), L("Agreement", "一致比例")], m.labels.agreement.map((r) => [m.meta.detectors[r.detector]?.label[lang] ?? r.detector, r.n, pct(r.rate)]))
47
+ const labels = section("labels", L("Your labels", "你的標記"), meta.agreement.meaning[lang], m.labels.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : m.labels.present && m.labels.n
48
+ ? T([L("Check", "檢查"), L("Labelled", "已標記"), L("Agreement", "一致比例"), L("Cannot tell", "看不出來")], m.labels.agreement.map((r) => [m.meta.detectors[r.detector]?.label[lang] ?? r.detector, r.n, pct(r.rate), r.unclear])) + `<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>`
48
49
  : `<p>${L("No labels yet. In phase 2 you will judge sessions yourself and compare your answers with the code checks.", "還沒有標記。第二階段會讓你親自判讀工作紀錄,再對照程式與你的判斷是否一致。")}</p>`);
49
50
  return [
51
+ workSection(m, lang, cards, lesson),
50
52
  skills,
51
53
  packages,
52
54
  ask,
@@ -56,6 +58,6 @@ export function sections(m, lang, cards) {
56
58
  cost,
57
59
  coverage,
58
60
  labels,
59
- section("concepts", L("Concepts", "概念"), L("Use these five ideas when you read the next report.", "下次讀報表時,可以用這五個概念判讀數字。"), `<div class="notes-grid">${Object.values(cards).map((c) => lesson(c, L)).join("")}</div>${selfCheck(L)}`),
61
+ section("concepts", L("Concepts", "概念"), L(`Use these ${Object.keys(cards).length} ideas when you read the next report.`, `下次讀報表時,可以用這 ${Object.keys(cards).length} 個概念判讀數字。`), `<div class="notes-grid">${Object.values(cards).map((c) => lesson(c, L)).join("")}</div>${selfCheck(L)}`),
60
62
  ].join("");
61
63
  }
@@ -0,0 +1,42 @@
1
+ import { esc, num, words } from "./format.js";
2
+ const KINDS = ["pin", "model-routing", "rule", "agent-role", "skill", "manual"];
3
+ /** Dense time slots get a count; every change still has its own mark and title. */
4
+ export function changeStrip(m, all, picks, ids, lang, range) {
5
+ const L = words(lang), label = (k) => m.meta.changeKinds[k][lang];
6
+ const period = typeof range === "number" ? L(`Last ${range} days`, `近 ${range} 天`) : range === "all" ? L("All time", "全部期間") : L("Selected dates", "選定期間");
7
+ const since = m.window.since ?? "", until = m.window.until ?? "", start = Date.parse(since), span = Date.parse(until) + 86400000 - start;
8
+ const x = (c) => 16 + Math.min(1, Math.max(0, (Date.parse(c.at) - start) / span)) * 968;
9
+ const bins = new Map(), counts = new Map();
10
+ for (const c of all) {
11
+ const slot = Math.floor((x(c) - 16) / 30), cells = bins.get(slot) ?? [];
12
+ cells.push(c);
13
+ bins.set(slot, cells);
14
+ counts.set(c.kind, (counts.get(c.kind) ?? 0) + 1);
15
+ }
16
+ const short = { pin: "版本", "model-routing": "模型路由", rule: "規則", "agent-role": "角色", skill: "skill", manual: "手動" };
17
+ const breakdown = KINDS.map(k => `${L(label(k), short[k])} ${num(counts.get(k) ?? 0)}`).join(L(", ", "、"));
18
+ const total = L(`${period}: ${num(all.length)} changes: ${breakdown}; ${picks.length} worth a closer look.`, `${period}共 ${num(all.length)} 筆調整:${breakdown};其中 ${picks.length} 筆值得回看。`);
19
+ const legend = KINDS.map(k => `<span><i class="key kind-${k}"></i>${esc(label(k))}: ${num(counts.get(k) ?? 0)}</span>`).join("");
20
+ const base = 64, marks = [], labeled = new Map();
21
+ for (const [slot, cells] of bins) {
22
+ cells.reverse(); // Earliest mark at the left of a dense slot.
23
+ const left = 16 + slot * 30, columns = Math.ceil(cells.length / 5);
24
+ cells.forEach((c, i) => {
25
+ const px = cells.length <= 5 ? x(c) : left + (Math.floor(i / 5) + .5) * 28 / columns;
26
+ const py = base - 6 - i % 5 * 5;
27
+ 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>`;
28
+ if (picks.includes(c))
29
+ labeled.set(c, { px, py, dot });
30
+ else
31
+ marks.push(dot);
32
+ });
33
+ if (cells.length > 5)
34
+ marks.push(`<text class="slot-count" x="${left + 14}" y="28" text-anchor="middle">×${cells.length}</text>`);
35
+ }
36
+ const links = picks.map((c, i) => {
37
+ 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", " ")}`;
38
+ const y = 87 + i * 23;
39
+ 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>`;
40
+ }).join("");
41
+ 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>`;
42
+ }
@@ -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,6 +1,7 @@
1
1
  import { concepts, lesson } from "./concepts.js";
2
- import { finding, readings, select, value, verdict } from "./findings.js";
2
+ import { overview, readings, value, verdict } from "./findings.js";
3
3
  import { esc, num, stamp, title, words } from "./format.js";
4
+ import { changeStrip } from "./strip.js";
4
5
  function card(c, id, rs, L) {
5
6
  const i = c.impact;
6
7
  return `<article class="card"><p class="eyebrow"><time datetime="${esc(c.at)}">${esc(stamp(c.at))} UTC</time></p><h3>${esc(title(c))}</h3>${rs.map((r) => `<div class="reading"><b>${esc(r.label)} ${value(r, "before")} → ${value(r, "after")}</b><small>${num(r.before?.n ?? 0)} → ${num(r.after?.n ?? 0)} ${r.unit}</small></div>`).join("")}<p class="muted">${rs[0].direction === rs[1].direction
@@ -49,8 +50,8 @@ ${i
49
50
  : ""}
50
51
  <div class="notes-grid">${lesson(lessons.sample, L)}${lesson(lessons.confounding, L)}${c.package === "pi-anchorloop" ? lesson(lessons.check, L) : ""}</div><p class="muted">${esc(c.repo)} ${esc(c.sha)} ${esc(c.subject)}</p><a href="#timeline">← ${L("Timeline", "回時間軸")}</a></section>`;
51
52
  }
52
- export function timeline(m, w, lang) {
53
- const L = words(lang), { all, lead, highlighted, folded } = select(m);
53
+ export function timeline(m, w, lang, range) {
54
+ const L = words(lang), { all, lead, highlighted, folded, headline, trust } = overview(m, lang);
54
55
  const ids = new Map(all.map((c, i) => [c, `change-${i + 1}`]));
55
56
  const metrics = new Map(all.map((c) => [c, readings(c, m, lang)]));
56
57
  const byDay = new Map(), byCommit = new Map();
@@ -68,21 +69,11 @@ export function timeline(m, w, lang) {
68
69
  byCommit.get(key).push(c);
69
70
  }
70
71
  }
71
- const headline = lead
72
- ? finding(lead, metrics.get(lead), L)
73
- : all.length
74
- ? L("Not enough sessions to compare changes yet", "這批調整的工作段數還不夠比較")
75
- : L("No changes recorded in this period", "這段期間沒有調整紀錄");
76
- const reason = lead?.impact;
77
- const trust = lead && reason?.incomplete && reason.confounded && !reason.smallSample
78
- ? L(`There were ${num(reason.confounded)} other changes, and one side has less than ${reason.window.days} days of data. We cannot credit this change alone.`, `同期還有 ${num(reason.confounded)} 筆別的調整,一側的資料也未滿 ${reason.window.days} 天;目前不能把差異歸給這次調整。`)
79
- : lead
80
- ? verdict(lead, metrics.get(lead), L)
81
- : L(`There are ${num(m.totals.sessions)} sessions in this report, but no eligible comparison.`, `報表收錄 ${num(m.totals.sessions)} 段工作,目前沒有適合放在首頁的比較。`);
82
72
  return {
83
73
  lead,
84
74
  headline,
85
75
  trust,
76
+ strip: changeStrip(m, all, highlighted, ids, lang, range),
86
77
  count: highlighted.length,
87
78
  cards: highlighted.map((c) => card(c, ids.get(c), metrics.get(c), L)).join(""),
88
79
  archive: [...byDay].map(([day, list]) => `<details class="day"><summary>${esc(day)} / ${num(list.length)} ${L("changes", "筆調整")}</summary><ul>${list.map((c) => `<li><time>${esc(c.at.slice(11, 16))}</time> <a href="#${ids.get(c)}">${esc(title(c))}</a></li>`).join("")}</ul></details>`).join(""),
@@ -1,36 +1,44 @@
1
1
  import { esc, num } from "./format.js";
2
- /** Last seven calendar days ending on the last complete UTC day in the selected period. */
3
- export function week(m) {
4
- const last = m.freshness.lastExtract?.slice(0, 10);
5
- if (!last || !m.window.until || !m.window.since)
2
+ /** Workload over the selected dates with records; the extraction day is partial. */
3
+ export function periodRows(m) {
4
+ if (!m.series.days.length || !m.window.until || !m.window.since)
6
5
  return [];
7
- const end = Math.min(Date.parse(last) - 86400000, Date.parse(m.window.until));
6
+ const end = Math.min(Date.parse(m.freshness.lastExtract?.slice(0, 10) ?? m.window.until), Date.parse(m.window.until));
7
+ const positions = new Map(m.series.days.map((d, i) => [d, i]));
8
+ const changes = new Map(), totals = new Map();
9
+ for (const c of m.changes) {
10
+ const day = c.at.slice(0, 10), kinds = changes.get(day) ?? new Set();
11
+ kinds.add(c.kind);
12
+ changes.set(day, kinds);
13
+ totals.set(day, (totals.get(day) ?? 0) + 1);
14
+ }
8
15
  const rows = [];
9
- for (let t = Math.max(end - 6 * 86400000, Date.parse(m.window.since)); t <= end; t += 86400000) {
10
- const day = new Date(t).toISOString().slice(0, 10), i = m.series.days.indexOf(day);
16
+ for (let t = Math.max(Date.parse(m.series.days[0]), Date.parse(m.window.since)); t <= end; t += 86400000) {
17
+ const day = new Date(t).toISOString().slice(0, 10), i = positions.get(day) ?? -1;
11
18
  rows.push({
12
19
  day,
13
20
  sessions: m.series.sessions[i] ?? 0,
14
21
  calls: m.series.toolCalls[i] ?? 0,
15
22
  loads: m.series.skillLoads[i] ?? 0,
16
- changes: m.changes.filter((c) => c.at.startsWith(day)).length,
23
+ changes: totals.get(day) ?? 0,
24
+ kinds: [...(changes.get(day) ?? [])],
17
25
  });
18
26
  }
19
27
  return rows;
20
28
  }
21
29
  export function workload(rows, L) {
22
- const heading = `<h2>${L("This week’s workload", "這週的工作量")}</h2>`;
30
+ const heading = `<h2>${L("Workload in this period", "這段期間的工作量")}</h2>`;
23
31
  if (!rows.length)
24
- return `<div class="panel">${heading}<p>${L("No complete recorded day yet.", "尚無完整一天的紀錄。")}</p></div>`;
32
+ return `<div class="panel">${heading}<p>${L("No records in this period.", "這段期間沒有紀錄。")}</p></div>`;
25
33
  const total = (key) => num(rows.reduce((n, r) => n + r[key], 0));
26
34
  const max = Math.max(1, ...rows.map((r) => r.sessions));
27
35
  const points = rows.map((r, i) => [5 + i * 348 / Math.max(1, rows.length - 1), 89 - 64 * r.sessions / max]);
28
36
  const line = points.map((p) => p.join(",")).join(" ");
29
37
  const md = (d) => d.slice(5).replace("-", ".");
30
38
  const desc = rows.map((r) => `${r.day}: ${num(r.sessions)} ${L("sessions", "段工作")} · ${r.changes} ${L("changes", "筆調整")}`).join("; ");
31
- return `<div class="panel workload">${heading}<p class="muted">${md(rows[0].day)}–${md(rows.at(-1).day)} / ${L("Volume is not quality", "多寡不代表好壞")}</p><h3>${total("sessions")} ${L("sessions", "段工作")}</h3><p class="muted">${L("Sessions per day · dashes mark changes", "每日工作段數 · 虛線表示當天有調整")}</p>
32
- <svg role="img" aria-label="${esc(desc)}" viewBox="0 0 358 96"><polygon points="5,89 ${line} ${points.at(-1)[0]},89" class="area"/><polyline points="${line}" class="trend"/>${points.map(([x, y], i) => rows[i].changes
33
- ? `<path d="M${x} 12V89" class="marker"/><circle cx="${x}" cy="${y}" r="3.5" class="dot"><title>${esc(rows[i].day)}: ${rows[i].changes} ${L("changes", "筆調整")}</title></circle>`
39
+ return `<div class="panel workload">${heading}<p class="muted">${md(rows[0].day)}–${md(rows.at(-1).day)} / ${L("Through the last extract", "統計至上次抽取")}</p><h3>${total("sessions")} ${L("sessions", "段工作")}</h3><p class="muted">${L("Sessions per day · colored dots mark changes", "每日工作段數 · 彩點表示當日調整類別")}</p>
40
+ <svg role="img" aria-label="${esc(desc)}" viewBox="0 0 358 96"><polygon points="5,89 ${line} ${points.at(-1)[0]},89" class="area"/><polyline points="${line}" class="trend"/>${points.map(([x], i) => rows[i].changes
41
+ ? `<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>`
34
42
  : "").join("")}</svg>
35
43
  <div class="ends"><span>${md(rows[0].day)} ${num(rows[0].sessions)}</span><span>${md(rows.at(-1).day)} ${num(rows.at(-1).sessions)}</span></div><p class="footline">${L("Tool calls", "工具呼叫")} ${total("calls")} / ${L("Skill loads", "讀取技能")} ${total("loads")}</p></div>`;
36
44
  }