pi-evals 0.2.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.
@@ -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)
@@ -29,7 +29,7 @@ export function sections(m, lang, cards) {
29
29
  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
30
  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
31
  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>`);
32
+ `<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
33
  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
34
  const md = m.meta.detectors[d.name];
35
35
  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,9 +41,9 @@ export function sections(m, lang, cards) {
41
41
  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
42
  const cov = m.coverage;
43
43
  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>`
44
+ ? `<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
45
  : `<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
46
+ 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
47
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)]))
48
48
  : `<p>${L("No labels yet. In phase 2 you will judge sessions yourself and compare your answers with the code checks.", "還沒有標記。第二階段會讓你親自判讀工作紀錄,再對照程式與你的判斷是否一致。")}</p>`);
49
49
  return [
@@ -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}
@@ -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
  }
package/dist/trends.js ADDED
@@ -0,0 +1,58 @@
1
+ import { ownerFor, sumDays } from "./model.js";
2
+ const DAY = 86_400_000;
3
+ /** Counts by event date; session counts by skill in the index use session start date. */
4
+ export function recentDays(index, project) {
5
+ if (!index.lastExtract || !index.range.start)
6
+ return [];
7
+ const end = Date.parse(index.lastExtract.slice(0, 10));
8
+ const dates = Array.from({ length: 14 }, (_, i) => new Date(end - (14 - i) * DAY).toISOString().slice(0, 10));
9
+ const rows = new Map(sumDays(index, { project, since: dates[0], until: dates[13] }).perDay);
10
+ return dates.filter(d => d >= index.range.start.slice(0, 10)).map(day => ({ day, agg: rows.get(day) }));
11
+ }
12
+ export function trendPair(r) {
13
+ const side = (c) => `${c.errors}/${c.calls} (${(100 * c.errors / c.calls).toFixed(1)}%)`;
14
+ return `${side(r.before)} → ${side(r.after)}`;
15
+ }
16
+ const zero = () => ({ errors: 0, calls: 0 });
17
+ function add(into, from) { into.errors += from.errors; into.calls += from.calls; }
18
+ export function packageCounts(index, day) {
19
+ const by = new Map();
20
+ for (const [tool, count] of Object.entries(day?.tools ?? {})) {
21
+ const owner = ownerFor(index, tool), total = by.get(owner) ?? zero();
22
+ add(total, count);
23
+ by.set(owner, total);
24
+ }
25
+ return by;
26
+ }
27
+ function week(index, rows) {
28
+ const packages = new Map(), monitors = zero();
29
+ for (const { agg } of rows) {
30
+ for (const [owner, count] of packageCounts(index, agg)) {
31
+ const total = packages.get(owner) ?? zero();
32
+ add(total, count);
33
+ packages.set(owner, total);
34
+ }
35
+ if (agg)
36
+ add(monitors, { errors: agg.monitors.statuses.error ?? 0, calls: agg.monitors.finished });
37
+ }
38
+ return { packages, monitors };
39
+ }
40
+ function rise(before, after) {
41
+ if (!before || Math.min(before.calls, after.calls) < 20)
42
+ return;
43
+ // Compare integer counts before rounding the displayed rates (threshold: five percentage points).
44
+ const diff = after.errors * before.calls - before.errors * after.calls;
45
+ if (20 * diff >= before.calls * after.calls)
46
+ return { before, after, delta: diff / before.calls / after.calls };
47
+ }
48
+ export function weeklyRises(index, since, project) {
49
+ const rows = recentDays(index, project);
50
+ if (rows.length !== 14 || (since && Date.parse(rows[0].day) < Date.parse(since) - 86400000))
51
+ return;
52
+ const prev = week(index, rows.slice(0, 7)), curr = week(index, rows.slice(7));
53
+ const packages = [...curr.packages].flatMap(([name, count]) => {
54
+ const r = rise(prev.packages.get(name), count);
55
+ return r ? [{ name, ...r }] : [];
56
+ }).sort((a, b) => b.delta - a.delta || b.after.calls - a.after.calls || a.name.localeCompare(b.name));
57
+ return { start: rows[0].day, end: rows[13].day, packages, monitors: rise(prev.monitors, curr.monitors) };
58
+ }
package/docs/design.md CHANGED
@@ -93,6 +93,21 @@ The renderer makes the following editorial choices from the model, without consu
93
93
  - The workload chart covers the last seven complete UTC dates in the report period (or fewer if the filter starts later), not seven nonempty days. Each marker means at least one change that day. Session and tool totals in the other sections still cover the selected report period.
94
94
  - Each detail uses the model’s actual window and session counts. Dates with records may exceed seven in a seven-day window that starts mid-day. The ruler shows the last extract only when it falls inside the after window, and its segments are not to scale.
95
95
 
96
+ ### Date ranges and findings (0.3.0)
97
+
98
+ The 30-day page opens first; the other pages cover 14 days, 90 days or all indexed dates.
99
+ The last day is the UTC date of extraction, even when the extract is old, so a stale index does not become an apparently quiet month.
100
+ The chart now covers the selected period including the partial last day.
101
+ The report reads the index and checks file coverage once, then reuses the same change comparisons in each narrower period.
102
+ The set of currently offered skills is the reference list; “never loaded” means no loads in the selected dates and project, not that the skill has never been used.
103
+ Coverage counts files modified in the chosen dates and separately shows the cleanup gate across all dates and projects.
104
+
105
+ `findings` uses the timeline’s headline, trust line, selection and verdicts, without copying the text of a commit or manual note.
106
+ For error trends it compares the two seven-day periods immediately before the extraction date, excluding the partial day, only if both weeks fit inside the selection and the index extends to the first date.
107
+ It counts tool errors over calls per package and job endings marked `error` over all recorded endings; both weeks need at least 20 observations and a rise of at least five percentage points.
108
+ If several packages qualify, the largest rise wins, then the larger recent call count, then the package name.
109
+ No flag means no rise met that rule, not proof that nothing went wrong.
110
+
96
111
  ### Storage choices
97
112
 
98
113
  JSON lines and JSON files, no database: the index is rebuilt from per-session summaries in about a second, and the reader needs no service (research §4: everything reduces to files plus one static page).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-evals",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Usage and process records for pi: how skills, packages, ask-user, monitors and subagents are used, back-filled from past sessions, with a static report and an evals_query tool",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,6 +27,8 @@
27
27
  "src",
28
28
  "dist",
29
29
  "docs",
30
+ "scripts",
31
+ "skills",
30
32
  "README.md",
31
33
  "CHANGELOG.md",
32
34
  "LICENSE"
@@ -34,7 +36,8 @@
34
36
  "pi": {
35
37
  "extensions": [
36
38
  "./src/index.ts"
37
- ]
39
+ ],
40
+ "skills": ["./skills"]
38
41
  },
39
42
  "scripts": {
40
43
  "build": "tsc -p tsconfig.build.json",
@@ -0,0 +1,18 @@
1
+ import { QueryError, report, run, safeName } from './query-lib.mjs';
2
+
3
+ const usage = 'node change-impact.mjs UTC_TIMESTAMP_OR_SHA [PACKAGE_OR_KIND]';
4
+ run(usage, args => {
5
+ if (args.length > 2) throw new QueryError(usage);
6
+ const [id, which] = args, m = report();
7
+ const hits = m.changes.filter(c => (c.at === id || c.sha === id) && (!which || c.package === which || c.kind === which));
8
+ if (hits.length !== 1) throw new QueryError(hits.length ? 'Multiple entries match; specify a package or change kind.' : 'No such change in the saved report.');
9
+ const { at, impact: i } = hits[0];
10
+ const header = `${at}; extract ${m.freshness.lastExtract ?? 'never'}; ${m.window.project ? safeName(m.window.project) : 'all projects'}`;
11
+ if (!i) return [header, 'No earlier records.'];
12
+ const rows = [header, `${i.window.days} days each side; sessions ${i.before.sessions} → ${i.after.sessions}`, `Too few sessions: ${i.smallSample}; incomplete window: ${i.incomplete}; other changes: ${i.confounded}. A difference does not prove cause.`];
13
+ for (const key of ['tool_error_rate', 'package_error_rate', 'ask_cancel_rate', 'cost_per_session', 'skill_loads_per_session', 'notices_per_session', 'anchor_before_first_edit', 'check_after_last_edit', 'todo_evidence']) {
14
+ const format = r => !r || r.value == null ? 'n/a (n=0)' : `${r.value.toFixed(4)} (n=${r.n})`;
15
+ rows.push(`${key}: ${format(i.before[key])} → ${format(i.after[key])}`);
16
+ }
17
+ return rows;
18
+ });
@@ -0,0 +1,10 @@
1
+ import { daily, packageCounts, QueryError, run } from './query-lib.mjs';
2
+
3
+ const usage = 'node package-errors.mjs PACKAGE [PROJECT]';
4
+ run(usage, args => {
5
+ if (args.length > 2) throw new QueryError(usage);
6
+ const [pkg, project] = args, { rows, index, header } = daily(project);
7
+ const counts = rows.map(({ day, agg }) => ({ day, count: packageCounts(index, agg).get(pkg) }));
8
+ if (!counts.some(x => x.count)) throw new QueryError('No calls for this package in the selected days and project.');
9
+ return [header, `${pkg}: tool errors/calls`, ...counts.map(({ day, count }) => `${day} ${count?.errors ?? 0}/${count?.calls ?? 0} ${count?.calls ? (100 * count.errors / count.calls).toFixed(1) + '%' : 'n/a'}`)];
10
+ });
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ // Node strips types in checkouts but forbids it under node_modules. npm ships dist there.
4
+ const installed = new URL(import.meta.url).pathname.split('/').includes('node_modules');
5
+ const load = name => import(installed ? `../dist/${name}.js` : `../src/${name}.ts`);
6
+ const [{ layout }, { loadIndex }, { recentDays, packageCounts }, { safeName }] = await Promise.all(
7
+ ['paths', 'build', 'trends', 'schema'].map(load),
8
+ );
9
+ export { packageCounts, safeName };
10
+
11
+ export function run(usage, fn) {
12
+ try {
13
+ const args = process.argv.slice(2);
14
+ if (!args.length || args.some(x => !x || safeName(x) !== x)) throw new Error(usage);
15
+ const text = fn(args).join('\n') + '\n';
16
+ if (Buffer.byteLength(text) > 2000) throw new Error('Result exceeds the output limit.');
17
+ process.stdout.write(text);
18
+ } catch (error) {
19
+ // Never echo unknown arguments, local paths or JSON parse excerpts.
20
+ console.error(error instanceof QueryError ? error.message : `Cannot read query. ${usage}`);
21
+ process.exitCode = 1;
22
+ }
23
+ }
24
+ export class QueryError extends Error {}
25
+ export function daily(project) {
26
+ const index = loadIndex(layout());
27
+ if (!index) throw new QueryError('No index. Run /evals extract first.');
28
+ return { rows: recentDays(index, project), index, header: `Extract ${index.lastExtract ?? 'never'}; complete UTC dates${project ? `; project ${project}` : '; all projects'}` };
29
+ }
30
+ export function report() {
31
+ const range = process.env.PI_EVALS_REPORT_RANGE ?? '30';
32
+ const files = new Map([['14', 'model-14d.json'], ['30', 'model.json'], ['90', 'model-90d.json'], ['all', 'model-all.json'], ['custom', 'model-custom.json']]);
33
+ if (!files.has(range)) throw new QueryError('Choose PI_EVALS_REPORT_RANGE=14, 30, 90, all or custom.');
34
+ try { return JSON.parse(readFileSync(join(layout().reports, files.get(range)), 'utf8')); }
35
+ catch { throw new QueryError('No readable report model. Run /evals report first.'); }
36
+ }
@@ -0,0 +1,9 @@
1
+ import { daily, QueryError, run } from './query-lib.mjs';
2
+
3
+ const usage = 'node skill-days.mjs SKILL [PROJECT]';
4
+ run(usage, args => {
5
+ if (args.length > 2) throw new QueryError(usage);
6
+ const [skill, project] = args, { rows, index, header } = daily(project);
7
+ if (!index.offeredSkills.includes(skill) && !Object.values(index.days).some(projects => Object.values(projects).some(a => Object.hasOwn(a.skillSessions, skill)))) throw new QueryError('Skill not found in index.');
8
+ return [header, `${skill}: sessions that loaded the skill, by session start date`, ...rows.map(({ day, agg }) => `${day} ${agg && Object.hasOwn(agg.skillSessions, skill) ? agg.skillSessions[skill] : 0}`)];
9
+ });
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: analyzing-evals
3
+ description: Use when the user asks how their agents, skills or packages are doing, what a setup change did, or how to read the pi-evals report.
4
+ ---
5
+
6
+ # Analyze agent activity
7
+
8
+ 1. Call `evals_query` with `view: "findings"` first. Check the dates and last extraction; default is the latest 30 UTC dates in the index. Use `since` or `project` when the question specifies a narrower scope.
9
+ 2. Follow **one** pointer that answers the question. For a weekly change in tool errors use `packages`; for a rule about editing use `process`. Keep the same filters. Stop when the numbers answer the question.
10
+ 3. If one detail is still missing, run one script below. Set `SCRIPTS` to the absolute path on the `Scripts:` line or in `details.scriptsDir`. For a default npm install, the fallback is `SCRIPTS="$HOME/.pi/agent/npm/node_modules/pi-evals/scripts"`. Check `test -f "$SCRIPTS/query-lib.mjs"` before running a query; if it fails, stop rather than guessing another path. Use exact identifiers returned by the view; none of these commands reads a transcript.
11
+
12
+ ```sh
13
+ node "$SCRIPTS/change-impact.mjs" UTC_TIMESTAMP_OR_SHA [PACKAGE_OR_KIND]
14
+ node "$SCRIPTS/skill-days.mjs" SKILL [PROJECT]
15
+ node "$SCRIPTS/package-errors.mjs" PACKAGE [PROJECT]
16
+ ```
17
+
18
+ The first reads the saved `reports/model.json`: check its extract time and project before using the comparison. For a different saved page, prefix the command with `PI_EVALS_REPORT_RANGE=14`, `90`, `all` or `custom`. If the file is missing or out of date, say so; `/evals report` rebuilds the preset pages.
19
+ The other two read the last 14 complete UTC dates in the index. Skill sessions count on their start date; package errors count on the date of the call. Neither script treats zero calls as a 0% error rate.
20
+
21
+ Lead with what rose, fell or held steady, and give the counts behind the rates. Say “too early to tell” when a side is short or too small; when other changes landed nearby, say “we cannot tell which change mattered.” Even a clear difference is not proof of cause. More sessions or skill loads measure activity, not better work.
package/src/aggregate.ts CHANGED
@@ -164,6 +164,9 @@ export interface SessionSummary {
164
164
  * version split read, so a change at 16:00 splits a day's sessions at 16:00 rather than at midnight.
165
165
  */
166
166
  export interface SessionRow {
167
+ /** Used for the date/project-scoped labels join. Older indices lack these two fields. */
168
+ id?: string;
169
+ linked?: boolean;
167
170
  /** Start, ISO. */
168
171
  s: string;
169
172
  p: string;
package/src/build.ts CHANGED
@@ -10,7 +10,7 @@ import { addLabel, bucketOf, bump, type DayAgg, emptyDay, mergeDay, rowOf, type
10
10
  import { buildChanges, type Change, versionAt, writeChanges } from "./changes.ts";
11
11
  import type { Checkpoint } from "./extract/run.ts";
12
12
  import { dayOf, type Layout, type Settings } from "./paths.ts";
13
- import { type EvalRecord, NAMES } from "./schema.ts";
13
+ import { type EvalRecord, NAMES, traceId } from "./schema.ts";
14
14
  import { liveFiles, readRecords } from "./store.ts";
15
15
 
16
16
  export interface DaysIndex {
@@ -200,7 +200,8 @@ export function buildIndex(options: { layout: Layout; settings: Settings; checkp
200
200
  }
201
201
  if (Object.keys(labels).length) sessionEvals[s.sessionId] = labels;
202
202
  add(s.project, days);
203
- rows.push(rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals));
203
+ rows.push({ ...rowOf(s.start, s.project, s.kind === "subagent", s.cost, days, s.evals), id: traceId(s.sessionId, "labels"),
204
+ linked: s.kind === "subagent" ? Boolean(s.parentId || (s.logicalId && links.has(s.logicalId))) : undefined });
204
205
  }
205
206
  let liveOnly = 0;
206
207
  for (const [id, records] of bySession) {
@@ -208,7 +209,7 @@ export function buildIndex(options: { layout: Layout; settings: Settings; checkp
208
209
  liveOnly += 1;
209
210
  const summary = liveSummary(records);
210
211
  add(summary.project, summary.days);
211
- rows.push(rowOf(summary.start, summary.project, records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent"), 0, summary.days));
212
+ rows.push({ ...rowOf(summary.start, summary.project, records.some((r) => r.name === NAMES.session && r.attrs["pi.session.kind"] === "subagent"), 0, summary.days), id: traceId(id, "labels"), linked: false });
212
213
  }
213
214
 
214
215
  const owners: DaysIndex["owners"] = {};
package/src/cli.ts CHANGED
@@ -5,7 +5,7 @@ import { query, type View, VIEWS } from "./query.ts";
5
5
 
6
6
  const USAGE = `usage:
7
7
  pi-evals extract [--root <dir>]... [--workers <n>] [--json]
8
- pi-evals report [--out <dir>] [--since YYYY-MM-DD] [--project <key>] [--lang zh|en]
8
+ pi-evals report [--out <dir>] [--since YYYY-MM-DD | --days N] [--project <key>] [--lang zh|en]
9
9
  pi-evals status
10
10
  pi-evals query <${VIEWS.join("|")}> [--since YYYY-MM-DD] [--project <key>]
11
11
  pi-evals mark <note>`;
@@ -49,7 +49,7 @@ async function main(argv: string[]): Promise<number> {
49
49
  }
50
50
  if (cmd === "report") {
51
51
  const lang = flag(args, "--lang") === "en" ? "en" : "zh";
52
- const out = runReport({ outDir: flag(args, "--out"), filter: { since: flag(args, "--since"), project: flag(args, "--project") }, lang });
52
+ const out = runReport({ outDir: flag(args, "--out"), filter: { since: flag(args, "--since"), days: args.includes("--days") ? Number(flag(args, "--days")) : undefined, project: flag(args, "--project") }, lang });
53
53
  if (!out) {
54
54
  console.error("nothing extracted yet: run pi-evals extract");
55
55
  return 1;
package/src/coverage.ts CHANGED
@@ -3,6 +3,8 @@ import type { Checkpoint } from "./extract/run.ts";
3
3
  import { listSessionFiles } from "./extract/run.ts";
4
4
 
5
5
  export interface Coverage {
6
+ /** Files whose modification date falls in the selected report dates (all projects). */
7
+ inRange?: { files: number; indexed: number };
6
8
  cutDays: number;
7
9
  cutoff: string;
8
10
  old: { files: number; bytes: number };
@@ -13,7 +15,7 @@ export interface Coverage {
13
15
  retainedGone: number;
14
16
  }
15
17
 
16
- export function coverage(roots: string[], checkpoint: Checkpoint, cutDays: number, now = Date.now()): Coverage {
18
+ export function coverage(roots: string[], checkpoint: Checkpoint, cutDays: number, now = Date.now(), activity?: Map<string, { files: number; indexed: number }>): Coverage {
17
19
  const cutoff = now - cutDays * 86_400_000;
18
20
  const files = listSessionFiles(roots);
19
21
  const result: Coverage = {
@@ -32,6 +34,11 @@ export function coverage(roots: string[], checkpoint: Checkpoint, cutDays: numbe
32
34
  const known = checkpoint.files[f.path];
33
35
  const fresh = !!known && known.size === f.size && known.mtimeMs === f.mtimeMs;
34
36
  if (fresh) result.all.indexedFiles += 1;
37
+ if (activity) {
38
+ const day = new Date(f.mtimeMs).toISOString().slice(0, 10), row = activity.get(day) ?? { files: 0, indexed: 0 };
39
+ row.files++; if (fresh) row.indexed++;
40
+ activity.set(day, row);
41
+ }
35
42
  if (f.mtimeMs >= cutoff) continue;
36
43
  result.old.files += 1;
37
44
  result.old.bytes += f.size;
@@ -0,0 +1,49 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import type { ReportModel } from "./model.ts";
3
+ import { overview, readings, value, verdict } from "./report/findings.ts";
4
+ import { words } from "./report/format.ts";
5
+ import { safeName } from "./schema.ts";
6
+ import { trendPair } from "./trends.ts";
7
+
8
+ export const scriptsDir = fileURLToPath(new URL("../scripts", import.meta.url));
9
+
10
+ /** Shorten only identifiers, never a verdict or its drill-down pointer. */
11
+ function name(s: string) {
12
+ const chars = Array.from(safeName(s));
13
+ if (Buffer.byteLength(chars.join("")) <= 72) return chars.join("");
14
+ while (Buffer.byteLength(chars.join("")) > 69) chars.pop();
15
+ return chars.join("") + "…";
16
+ }
17
+ export function findings(m: ReportModel) {
18
+ const { headline, trust, highlighted } = overview(m, "en"), L = words("en");
19
+ const lines = [
20
+ `${m.window.since ?? "?"}..${m.window.until ?? "?"} UTC${m.window.project ? ` · ${name(m.window.project)}` : ""} · ${m.freshness.stale ? "STALE: " : ""}last extract ${m.freshness.lastExtract ?? "never"} → coverage`,
21
+ `Scripts: ${scriptsDir}`, `${headline} → changes`, `${trust} → changes`,
22
+ ];
23
+ const extras: { line: number; prefix: string; metric: string }[] = [];
24
+ for (const c of highlighted) {
25
+ const id = c.package ? `${name(c.package)} ${name(c.to ?? "unknown")}` : c.kind;
26
+ const rs = readings(c, m, "en"), r = rs.find(row => row.before?.value != null && row.after?.value != null);
27
+ const metric = r ? `${r.label} ${value(r, "before")} → ${value(r, "after")}; ` : "";
28
+ const prefix = `${c.at} ${id}: `;
29
+ extras.push({ line: lines.length, prefix, metric });
30
+ lines.push(`${prefix}${verdict(c, rs, L)} → changes`);
31
+ }
32
+ const unseen = m.skills.neverLoaded.length;
33
+ lines.push(`${unseen}/${m.skills.offered} offered skills never loaded in range → skills`);
34
+ const cov = m.coverage;
35
+ const gate = !cov ? "not measured" : !cov.old.files ? "no old files" : cov.notIndexed.files || cov.notIndexed.bytes
36
+ ? `blocked: ${cov.notIndexed.files}/${cov.old.files} old files not indexed` : `all ${cov.old.files} old files indexed`;
37
+ lines.push(`Cleanup (all projects/dates): ${gate} → coverage`);
38
+ const w = m.weekly;
39
+ if (!w) lines.push("Need two weeks in range for error trends → packages / monitors");
40
+ else {
41
+ const p = w.packages[0];
42
+ lines.push(`${w.start}..${w.end} UTC, earlier week vs later: ${p ? `${p.name === "unknown" ? "tools with no known package" : name(p.name)} errors/calls ${trendPair(p)}` : "no package rise flagged"} → packages`);
43
+ lines.push(`Same weeks: ${w.monitors ? `failed/finished jobs ${trendPair(w.monitors)}` : "no job error rise flagged"} → monitors`);
44
+ }
45
+ for (const { line, prefix, metric } of extras) {
46
+ if (Buffer.byteLength(lines.join("\n") + metric) <= 1499) lines[line] = prefix + metric + lines[line].slice(prefix.length);
47
+ }
48
+ return lines.join("\n");
49
+ }