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.
- package/CHANGELOG.md +15 -0
- package/README.md +23 -9
- package/dist/build.js +14 -4
- package/dist/cli.js +2 -2
- package/dist/coverage.js +8 -1
- package/dist/extract/run.js +1 -1
- package/dist/extract/session.js +43 -3
- package/dist/findings.js +54 -0
- package/dist/index.js +14 -7
- package/dist/meta.js +43 -1
- package/dist/model.js +35 -14
- package/dist/ops.js +53 -22
- package/dist/paths.js +3 -0
- package/dist/query.js +36 -13
- package/dist/ranges.js +14 -0
- package/dist/render.js +15 -5
- package/dist/report/concepts.js +23 -1
- package/dist/report/findings.js +12 -1
- package/dist/report/sections.js +7 -5
- package/dist/report/strip.js +42 -0
- package/dist/report/style.js +14 -1
- package/dist/report/timeline.js +5 -14
- package/dist/report/week.js +21 -13
- package/dist/report/work.js +59 -0
- package/dist/schema.js +16 -1
- package/dist/trends.js +58 -0
- package/dist/work/join.js +429 -0
- package/dist/work/model.js +145 -0
- package/dist/work/query.js +59 -0
- package/dist/work/sb.js +131 -0
- package/dist/work/track.js +323 -0
- package/docs/design.md +15 -0
- package/docs/schema.md +8 -2
- package/package.json +5 -2
- package/scripts/change-impact.mjs +18 -0
- package/scripts/package-errors.mjs +10 -0
- package/scripts/query-lib.mjs +36 -0
- package/scripts/skill-days.mjs +9 -0
- package/skills/analyzing-evals/SKILL.md +23 -0
- package/src/aggregate.ts +14 -2
- package/src/build.ts +13 -4
- package/src/cli.ts +2 -2
- package/src/coverage.ts +8 -1
- package/src/extract/run.ts +1 -1
- package/src/extract/session.ts +36 -2
- package/src/findings.ts +52 -0
- package/src/index.ts +14 -9
- package/src/meta.ts +45 -1
- package/src/model.ts +40 -15
- package/src/ops.ts +50 -22
- package/src/paths.ts +7 -0
- package/src/query.ts +32 -13
- package/src/ranges.ts +15 -0
- package/src/render.ts +15 -5
- package/src/report/concepts.ts +30 -1
- package/src/report/findings.ts +19 -1
- package/src/report/sections.ts +9 -9
- package/src/report/strip.ts +40 -0
- package/src/report/style.ts +14 -1
- package/src/report/timeline.ts +6 -22
- package/src/report/week.ts +21 -17
- package/src/report/work.ts +87 -0
- package/src/schema.ts +16 -1
- package/src/trends.ts +61 -0
- package/src/work/join.ts +476 -0
- package/src/work/model.ts +179 -0
- package/src/work/query.ts +53 -0
- package/src/work/sb.ts +158 -0
- package/src/work/track.ts +397 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { esc, num, usd, words } from "./format.js";
|
|
2
|
+
const SHOWN = 15;
|
|
3
|
+
export function span(minutes, L) {
|
|
4
|
+
if (minutes < 90)
|
|
5
|
+
return L(`${Math.round(minutes)} min`, `${Math.round(minutes)} 分`);
|
|
6
|
+
if (minutes < 48 * 60)
|
|
7
|
+
return L(`${(minutes / 60).toFixed(1)} h`, `${(minutes / 60).toFixed(1)} 小時`);
|
|
8
|
+
return L(`${(minutes / 1440).toFixed(1)} days`, `${(minutes / 1440).toFixed(1)} 天`);
|
|
9
|
+
}
|
|
10
|
+
const pct = (v) => `${Math.round(v * 100)}%`;
|
|
11
|
+
export function verdictText(c, v, L, lines = false) {
|
|
12
|
+
const g = (value) => c.groups.find((x) => x.value === value);
|
|
13
|
+
const n = (value) => (lines ? g(value)?.nLines : g(value)?.n) ?? 0;
|
|
14
|
+
const what = lines ? L("per 100 changed lines", "每百行") : L("per item", "每件");
|
|
15
|
+
if (v.kind === "single")
|
|
16
|
+
return v.a ? L(`Only one group (${v.a}): nothing to compare it with.`, `只有一組(${v.a}),沒有可比的對象。`) : L("No items with a line count.", "沒有算得出行數的工作。");
|
|
17
|
+
if (v.kind === "few")
|
|
18
|
+
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 件)。`);
|
|
19
|
+
if (v.kind === "same")
|
|
20
|
+
return L(`${v.a} and ${v.b} cost about the same ${what} (less than 20% apart).`, `${v.a} 和 ${v.b} ${what}花費差不到兩成,看不出差別。`);
|
|
21
|
+
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)} 件)。這是差異,不是原因。`);
|
|
22
|
+
}
|
|
23
|
+
function stallText(stalls, m, lang) {
|
|
24
|
+
const L = words(lang);
|
|
25
|
+
const parts = Object.entries(stalls)
|
|
26
|
+
.sort((a, b) => b[1] - a[1])
|
|
27
|
+
.map(([k, v]) => `${m.meta.stallKinds[k]?.[lang] ?? k} ${span(v, L)}`);
|
|
28
|
+
return parts.join(L(", ", "、")) || "—";
|
|
29
|
+
}
|
|
30
|
+
export function workSection(m, lang, cards, lesson) {
|
|
31
|
+
const L = words(lang);
|
|
32
|
+
const w = m.work;
|
|
33
|
+
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>`;
|
|
34
|
+
if (!w)
|
|
35
|
+
return `${head}<p class="intro">${L("Run /evals extract to build the work items.", "請執行 /evals extract 建立工作項目。")}</p></section>`;
|
|
36
|
+
const meta = m.meta.metrics;
|
|
37
|
+
const close = (k) => m.meta.closeKinds[k]?.[lang] ?? k;
|
|
38
|
+
const dims = { role: L("role", "角色"), model: L("model", "模型"), anchorloop: L("anchorloop version", "anchorloop 版本") };
|
|
39
|
+
const kinds = { delegated: L("Work handed to subagents", "交給子代理做的工作"), self: L("Work the main agent did itself", "主代理自己做的工作") };
|
|
40
|
+
const stallTotal = Object.values(w.stallMs).reduce((s, v) => s + v, 0);
|
|
41
|
+
const row = (r) => `<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>`;
|
|
42
|
+
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>`;
|
|
43
|
+
const list = w.list.length
|
|
44
|
+
? `<div class="scroll"><table class="items">${listHead}<tbody>${w.list.slice(0, SHOWN).map(row).join("")}</tbody></table></div>${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>` : ""}`
|
|
45
|
+
: `<p class="muted">${L("No item closed in this period.", "這段期間沒有收尾的工作。")}</p>`;
|
|
46
|
+
const compare = w.compare.length
|
|
47
|
+
? w.compare
|
|
48
|
+
.map((c) => `<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>${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("")}</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>`)
|
|
49
|
+
.join("")
|
|
50
|
+
: `<p class="muted">${L("No finished items to compare.", "沒有可比較的已完成工作。")}</p>`;
|
|
51
|
+
const open = w.open.length
|
|
52
|
+
? `<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>${w.open
|
|
53
|
+
.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>`)
|
|
54
|
+
.join("")}</tbody></table></div>`
|
|
55
|
+
: `<p class="muted">${L("Nothing open in this period.", "這段期間沒有還開著的工作。")}</p>`;
|
|
56
|
+
const tile = (label, big, note) => `<article class="panel"><p class="eyebrow">${esc(label)}</p><p class="big">${big}</p><p class="muted">${note}</p></article>`;
|
|
57
|
+
const kindRows = Object.entries(w.closeKinds).filter(([, n]) => n > 0).map(([k, n]) => `${esc(close(k))} ${num(n)}`).join(L(", ", "、"));
|
|
58
|
+
return `${head}<p class="intro">${L("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.", "一項工作就是待辦清單上的一列:從它被切到「進行中」開始,到標成完成或刪除為止。開始前排隊的時間不算。")}</p><div class="tiles">${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)}`))}${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)}(估算)`))}${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)}`))}${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)))}</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">${L("Each panel compares only items of the same kind; a group needs at least 5 items.", "每一格只比同一類的工作;每組至少 5 件才下結論。")}</p><div class="pair">${compare}</div><h3>${L("Still open: stopped where, waiting on whom, for how long", "還開著的工作:停在哪、等誰、多久")}</h3>${open}</section>`;
|
|
59
|
+
}
|
package/dist/schema.js
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
|
export const SCHEMA_VERSION = 1;
|
|
@@ -14,12 +15,24 @@ export function safeName(value) {
|
|
|
14
15
|
return "unknown";
|
|
15
16
|
return NAME.test(value) ? value : "redacted";
|
|
16
17
|
}
|
|
18
|
+
export const TITLE_MAX = 80;
|
|
19
|
+
/** The one attribute that may hold source text: a work item's todo subject, as one line of at most 80 characters. */
|
|
20
|
+
export const TITLE_ATTR = "pi.item.title";
|
|
21
|
+
/** The todo subject as a one-line title of at most 80 characters (the boss's rule: 「顯示,最多 80 字」). */
|
|
22
|
+
export function titleOf(subject) {
|
|
23
|
+
if (typeof subject !== "string")
|
|
24
|
+
return "";
|
|
25
|
+
const line = subject.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
|
|
26
|
+
return Array.from(line).slice(0, TITLE_MAX).join("");
|
|
27
|
+
}
|
|
17
28
|
function clean(attrs) {
|
|
18
29
|
const out = {};
|
|
19
30
|
for (const [key, value] of Object.entries(attrs)) {
|
|
20
31
|
if (value === undefined)
|
|
21
32
|
continue;
|
|
22
|
-
if (
|
|
33
|
+
if (key === TITLE_ATTR)
|
|
34
|
+
out[key] = titleOf(value);
|
|
35
|
+
else if (typeof value === "string")
|
|
23
36
|
out[key] = safeName(value);
|
|
24
37
|
else if (Array.isArray(value))
|
|
25
38
|
out[key] = value.slice(0, 200).map(safeName);
|
|
@@ -62,4 +75,6 @@ export const NAMES = {
|
|
|
62
75
|
tools: "pi.tools.snapshot",
|
|
63
76
|
skills: "pi.skills.available",
|
|
64
77
|
compaction: "pi.compaction",
|
|
78
|
+
workitem: "pi.workitem",
|
|
79
|
+
stall: "pi.stall",
|
|
65
80
|
};
|
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
|
+
}
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Joins each session's rebuilt work items with what other records know about them: the exact cost of the subagents
|
|
3
|
+
* that did the work, the review thread and car that closed it, the sb ledger's waits, and the size of the change.
|
|
4
|
+
* Writes `index/items.json` (what the report reads) and `pi.workitem` / `pi.stall` records (docs/schema.md).
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from "node:child_process";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { versionAt } from "../changes.js";
|
|
10
|
+
import { NAMES, record, spanId } from "../schema.js";
|
|
11
|
+
import { readCars, readLedger, readThreads } from "./sb.js";
|
|
12
|
+
export const ANCHORLOOP = ["pi-anchorloop", "pi-aaaav", "aaaav"];
|
|
13
|
+
export const CLOSE_KINDS = ["review_done", "landed", "wrap", "evidence", "unproven", "deleted", "open"];
|
|
14
|
+
export const STALL_KINDS = ["human", "peer", "child", "timer", "ci", "device"];
|
|
15
|
+
const round = (v) => Math.round(v * 1e6) / 1e6;
|
|
16
|
+
const ms = (iso) => (iso ? Date.parse(iso) : Number.NaN);
|
|
17
|
+
const TICKET = /\b[A-Z][A-Z0-9]+-\d+\b/g;
|
|
18
|
+
const prefixOf = (owner) => (owner && owner.includes("-") ? owner.slice(0, owner.lastIndexOf("-")) : undefined);
|
|
19
|
+
const short = (session) => session.slice(0, 8);
|
|
20
|
+
function atomicWrite(file, text) {
|
|
21
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
22
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
23
|
+
writeFileSync(tmp, text);
|
|
24
|
+
renameSync(tmp, file);
|
|
25
|
+
}
|
|
26
|
+
/** Lines changed between two commits, by `git diff --numstat`, cached on disk; numbers only. */
|
|
27
|
+
export class Lines {
|
|
28
|
+
cache;
|
|
29
|
+
file;
|
|
30
|
+
now;
|
|
31
|
+
constructor(file, now) {
|
|
32
|
+
this.file = file;
|
|
33
|
+
this.now = now;
|
|
34
|
+
const raw = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
|
35
|
+
this.cache = { repo: raw.repo ?? {}, miss: raw.miss ?? {}, diff: raw.diff ?? {} };
|
|
36
|
+
}
|
|
37
|
+
git(dir, args) {
|
|
38
|
+
return spawnSync("git", ["-C", dir, ...args], { encoding: "utf8", maxBuffer: 64 << 20 });
|
|
39
|
+
}
|
|
40
|
+
/** The first candidate repository holding `sha`. Misses are re-checked after a day. */
|
|
41
|
+
repoOf(sha, dirs) {
|
|
42
|
+
const hit = this.cache.repo[sha];
|
|
43
|
+
if (hit)
|
|
44
|
+
return hit;
|
|
45
|
+
const missed = this.cache.miss[sha];
|
|
46
|
+
if (missed && this.now.getTime() - Date.parse(missed) < 86_400_000)
|
|
47
|
+
return undefined;
|
|
48
|
+
for (const dir of dirs) {
|
|
49
|
+
if (!existsSync(dir))
|
|
50
|
+
continue;
|
|
51
|
+
if (this.git(dir, ["cat-file", "-e", `${sha}^{commit}`]).status === 0) {
|
|
52
|
+
this.cache.repo[sha] = dir;
|
|
53
|
+
return dir;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
this.cache.miss[sha] = this.now.toISOString();
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Added plus deleted lines from `base` to `head`, or undefined when `base` is not an ancestor of `head`. */
|
|
60
|
+
between(dir, base, head) {
|
|
61
|
+
const key = `${dir}|${base}|${head}`;
|
|
62
|
+
if (key in this.cache.diff)
|
|
63
|
+
return this.cache.diff[key] ?? undefined;
|
|
64
|
+
let n = null;
|
|
65
|
+
if (this.git(dir, ["merge-base", "--is-ancestor", base, head]).status === 0) {
|
|
66
|
+
const res = this.git(dir, ["diff", "--numstat", base, head]);
|
|
67
|
+
if (res.status === 0) {
|
|
68
|
+
n = 0;
|
|
69
|
+
for (const line of res.stdout.split("\n")) {
|
|
70
|
+
const [a, d] = line.split("\t");
|
|
71
|
+
if (/^\d+$/.test(a ?? "") && /^\d+$/.test(d ?? ""))
|
|
72
|
+
n += Number(a) + Number(d);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
this.cache.diff[key] = n;
|
|
77
|
+
return n ?? undefined;
|
|
78
|
+
}
|
|
79
|
+
save() {
|
|
80
|
+
atomicWrite(this.file, JSON.stringify(this.cache));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function refineGap(gap, events) {
|
|
84
|
+
if (!events?.length)
|
|
85
|
+
return { kind: gap.kind, on: gap.on };
|
|
86
|
+
const lo = ms(gap.start) - 2000;
|
|
87
|
+
const hi = ms(gap.end) + 5000;
|
|
88
|
+
const kinds = {
|
|
89
|
+
wait_answered: ["human", "W"],
|
|
90
|
+
wait_returned: ["human", "W"],
|
|
91
|
+
wait_parked: ["human", "W"],
|
|
92
|
+
link_wait_done: ["device", "L"],
|
|
93
|
+
thread_close: ["child", "T"],
|
|
94
|
+
};
|
|
95
|
+
let best;
|
|
96
|
+
for (const e of events) {
|
|
97
|
+
const t = ms(e.at);
|
|
98
|
+
if (t >= lo && t <= hi && kinds[e.kind])
|
|
99
|
+
best = e;
|
|
100
|
+
}
|
|
101
|
+
if (!best)
|
|
102
|
+
return { kind: gap.kind, on: gap.on };
|
|
103
|
+
const [kind, prefix] = kinds[best.kind];
|
|
104
|
+
const id = best.id ?? "";
|
|
105
|
+
return { kind, on: id ? (/^\d+$/.test(id) ? `${prefix}${id}` : id) : gap.on };
|
|
106
|
+
}
|
|
107
|
+
/** An open wait in the ledger for this session at its end: a wait card, a link wait, or a review thread. */
|
|
108
|
+
function openWait(events) {
|
|
109
|
+
if (!events?.length)
|
|
110
|
+
return undefined;
|
|
111
|
+
const open = new Map();
|
|
112
|
+
const pairs = { wait_raised: ["W", "human"], link_wait_open: ["L", "device"], thread_open: ["T", "child"] };
|
|
113
|
+
const ends = new Set(["wait_answered", "wait_returned", "wait_parked", "link_wait_done", "thread_close"]);
|
|
114
|
+
for (const e of events) {
|
|
115
|
+
const id = e.id ?? "";
|
|
116
|
+
const open_ = pairs[e.kind];
|
|
117
|
+
if (open_)
|
|
118
|
+
open.set(`${open_[0]}:${id}`, { kind: open_[1], on: /^\d+$/.test(id) ? `${open_[0]}${id}` : id || undefined });
|
|
119
|
+
else if (ends.has(e.kind))
|
|
120
|
+
for (const k of [...open.keys()])
|
|
121
|
+
if (k.endsWith(`:${id}`))
|
|
122
|
+
open.delete(k);
|
|
123
|
+
}
|
|
124
|
+
return [...open.values()].at(-1);
|
|
125
|
+
}
|
|
126
|
+
/** Picks one item for a child among candidates: the one whose window holds the launch, else the closest start before it. */
|
|
127
|
+
function byTime(items, at, end) {
|
|
128
|
+
const t = ms(at);
|
|
129
|
+
const inside = items.filter((it) => t >= ms(it.created) && t <= ms(it.close ?? end));
|
|
130
|
+
if (inside.length)
|
|
131
|
+
return inside.at(-1);
|
|
132
|
+
const before = items.filter((it) => ms(it.created) <= t).sort((a, b) => ms(b.created) - ms(a.created));
|
|
133
|
+
return before[0] ?? items[0];
|
|
134
|
+
}
|
|
135
|
+
/** The children of one session: each child belongs to one parent, the one its brief names, else the one that spawned it. */
|
|
136
|
+
function childrenOf(s, parentOf, byLogical) {
|
|
137
|
+
const launches = new Map((s.work?.launches ?? []).map((l) => [l.id, l]));
|
|
138
|
+
const ids = new Set([...s.spawned.map((sp) => sp.id), ...[...parentOf].filter(([, p]) => p === s.sessionId).map(([id]) => id)]);
|
|
139
|
+
const out = [];
|
|
140
|
+
for (const id of ids) {
|
|
141
|
+
if (parentOf.get(id) !== s.sessionId)
|
|
142
|
+
continue;
|
|
143
|
+
const c = byLogical.get(id);
|
|
144
|
+
const l = launches.get(id);
|
|
145
|
+
out.push({ id, name: c?.childName ?? l?.name, cost: c?.cost ?? 0, role: l?.role ?? "unknown", model: c?.model ?? l?.model ?? "unknown", at: l?.at ?? c?.start ?? s.start, cwd: c?.cwd });
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
export function joinWork(options) {
|
|
150
|
+
const { summaries, changes } = options;
|
|
151
|
+
const withWork = summaries.filter((s) => s.work?.items.length);
|
|
152
|
+
const parentOf = new Map();
|
|
153
|
+
const byLogical = new Map();
|
|
154
|
+
for (const s of summaries)
|
|
155
|
+
for (const sp of s.spawned)
|
|
156
|
+
parentOf.set(sp.id, s.sessionId);
|
|
157
|
+
for (const s of summaries) {
|
|
158
|
+
if (s.kind !== "subagent")
|
|
159
|
+
continue;
|
|
160
|
+
if (s.logicalId)
|
|
161
|
+
byLogical.set(s.logicalId, s);
|
|
162
|
+
if (s.logicalId && s.parentId)
|
|
163
|
+
parentOf.set(s.logicalId, s.parentId);
|
|
164
|
+
}
|
|
165
|
+
const threads = readThreads(options.sbDir, new Set(withWork.map((s) => short(s.sessionId))));
|
|
166
|
+
const cars = readCars(options.sbDir);
|
|
167
|
+
const ledger = readLedger(options.sbDir);
|
|
168
|
+
const out = [];
|
|
169
|
+
const sessions = [];
|
|
170
|
+
for (const s of withWork) {
|
|
171
|
+
const work = s.work;
|
|
172
|
+
const end = work.lastActivity;
|
|
173
|
+
sessions.push({ id: s.sessionId, project: s.project, last: end, unattributed: work.unattributed });
|
|
174
|
+
// A task carried in already done is no item here, so it must not win a thread or a child either.
|
|
175
|
+
const top = work.items.filter((it) => it.level === "top" && !it.carried);
|
|
176
|
+
const children = childrenOf(s, parentOf, byLogical);
|
|
177
|
+
const sessionThreads = threads.get(s.sessionId) ?? [];
|
|
178
|
+
const pairs = new Map(work.pairs.map((p) => [p.thread, p]));
|
|
179
|
+
const itemOf = (it) => new Set([it.key, it.uid, `${short(s.sessionId)}#${it.id}`].filter(Boolean));
|
|
180
|
+
// Threads: the producer's item link, else the worker named as the item's owner.
|
|
181
|
+
const threadOf = new Map();
|
|
182
|
+
for (const th of sessionThreads) {
|
|
183
|
+
const item = th.item ?? pairs.get(th.id)?.item;
|
|
184
|
+
let target = item ? top.find((it) => itemOf(it).has(item)) : undefined;
|
|
185
|
+
if (!target && th.worker) {
|
|
186
|
+
const owned = top.filter((it) => it.owner === th.worker);
|
|
187
|
+
target = owned.length ? byTime(owned, th.created ?? end, end) : undefined;
|
|
188
|
+
}
|
|
189
|
+
if (target && !threadOf.has(target))
|
|
190
|
+
threadOf.set(target, th);
|
|
191
|
+
}
|
|
192
|
+
// Children: the strongest link wins (launch item, evidence ref, thread pair, owner name, reviewer prefix).
|
|
193
|
+
const childCost = new Map();
|
|
194
|
+
for (const c of children) {
|
|
195
|
+
const launchItem = work.launches.find((l) => l.id === c.id)?.item;
|
|
196
|
+
const levels = [
|
|
197
|
+
(it) => (!!launchItem && itemOf(it).has(launchItem)) || it.refs.includes(`child:${c.id}`),
|
|
198
|
+
(it) => {
|
|
199
|
+
const th = threadOf.get(it);
|
|
200
|
+
return !!th && !!c.name && (th.reviewer === c.name || th.worker === c.name);
|
|
201
|
+
},
|
|
202
|
+
(it) => !!c.name && it.owner === c.name,
|
|
203
|
+
(it) => {
|
|
204
|
+
const p = prefixOf(it.owner);
|
|
205
|
+
return !!p && !!c.name && new RegExp(`^${p.replace(/[.+]/g, "\\$&")}-review\\d*$`).test(c.name);
|
|
206
|
+
},
|
|
207
|
+
];
|
|
208
|
+
let target;
|
|
209
|
+
for (const match of levels) {
|
|
210
|
+
const hits = top.filter(match);
|
|
211
|
+
if (hits.length) {
|
|
212
|
+
target = byTime(hits, c.at, end);
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!target)
|
|
217
|
+
continue;
|
|
218
|
+
const row = childCost.get(target) ?? { cost: 0, names: [] };
|
|
219
|
+
row.cost += c.cost;
|
|
220
|
+
if (c.name && !row.names.includes(c.name))
|
|
221
|
+
row.names.push(c.name);
|
|
222
|
+
if (c.name && c.name === target.owner)
|
|
223
|
+
row.owner = c;
|
|
224
|
+
else
|
|
225
|
+
row.owner ??= c;
|
|
226
|
+
childCost.set(target, row);
|
|
227
|
+
}
|
|
228
|
+
// Size: lines from the last evidence commit of the item before (same repository) to this item's last.
|
|
229
|
+
const repos = [s.cwd, ...children.map((c) => c.cwd), ...options.repos].filter((d) => !!d).filter((d, i, a) => a.indexOf(d) === i);
|
|
230
|
+
const lines = new Map();
|
|
231
|
+
if (options.lines) {
|
|
232
|
+
const prev = new Map();
|
|
233
|
+
for (const it of [...top].filter((i) => i.shas.length).sort((a, b) => ms(a.close ?? end) - ms(b.close ?? end))) {
|
|
234
|
+
const located = it.shas.map((sha) => [sha, options.lines.repoOf(sha, repos)]);
|
|
235
|
+
const head = located.findLast(([, repo]) => repo);
|
|
236
|
+
if (head) {
|
|
237
|
+
const repo = head[1];
|
|
238
|
+
const own = located.filter(([, r]) => r === repo).map(([sha]) => sha);
|
|
239
|
+
const base = prev.get(repo) ?? (own.length > 1 ? own[0] : undefined);
|
|
240
|
+
if (base && base !== head[0]) {
|
|
241
|
+
const n = options.lines.between(repo, base, head[0]);
|
|
242
|
+
if (n !== undefined)
|
|
243
|
+
lines.set(it, n);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
for (const [sha, repo] of located)
|
|
247
|
+
if (repo)
|
|
248
|
+
prev.set(repo, sha);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const carsHere = cars.get(s.sessionId) ?? [];
|
|
252
|
+
const events = ledger.get(s.sessionId);
|
|
253
|
+
const pendingChildren = (names) => names.filter((name) => {
|
|
254
|
+
const evs = work.childEvents.filter((e) => e[1] === name);
|
|
255
|
+
const launched = work.launches.filter((l) => l.name === name).map((l) => l.at);
|
|
256
|
+
const lastStart = [...launched, ...evs.filter((e) => e[2] === "resume").map((e) => e[0])].sort().at(-1);
|
|
257
|
+
const lastResult = evs.filter((e) => e[2] === "result").map((e) => e[0]).sort().at(-1);
|
|
258
|
+
return !!lastStart && (!lastResult || lastResult < lastStart);
|
|
259
|
+
});
|
|
260
|
+
for (const it of work.items) {
|
|
261
|
+
// Closed before this session saw it: its close belongs to the session (or tool) that closed it.
|
|
262
|
+
if (it.carried)
|
|
263
|
+
continue;
|
|
264
|
+
const kids = it.level === "top" ? childCost.get(it) : undefined;
|
|
265
|
+
const th = threadOf.get(it);
|
|
266
|
+
const activeMs = it.active.reduce((sum, [a, b]) => sum + Math.max(0, ms(b ?? end) - ms(a)), 0);
|
|
267
|
+
let closeKind = it.status === "deleted" ? "deleted" : it.status === "completed" ? "unproven" : "open";
|
|
268
|
+
let closeAt;
|
|
269
|
+
if (it.status === "completed" && it.close) {
|
|
270
|
+
const close = ms(it.close);
|
|
271
|
+
const from = ms(it.start ?? it.created);
|
|
272
|
+
const tickets = new Set(it.title.match(TICKET) ?? []);
|
|
273
|
+
const landed = carsHere.find((c) => c.landed && ms(c.landed) >= from && ms(c.landed) <= close + 300_000 && (!tickets.size || c.tickets.some((t) => tickets.has(t))));
|
|
274
|
+
const wrap = work.wraps.find((w) => w.wrapped && ms(w.at) >= close - 120_000 && ms(w.at) <= close + 600_000) ?? events?.find((e) => e.kind === "wrap" && e.why === "wrapped" && ms(e.at) >= close - 120_000 && ms(e.at) <= close + 600_000);
|
|
275
|
+
if (th?.closedAs === "done" && th.closed && ms(th.closed) <= close + 300_000) {
|
|
276
|
+
closeKind = "review_done";
|
|
277
|
+
closeAt = th.closed;
|
|
278
|
+
}
|
|
279
|
+
else if (landed) {
|
|
280
|
+
closeKind = "landed";
|
|
281
|
+
closeAt = landed.landed;
|
|
282
|
+
}
|
|
283
|
+
else if (wrap) {
|
|
284
|
+
closeKind = "wrap";
|
|
285
|
+
closeAt = wrap.at;
|
|
286
|
+
}
|
|
287
|
+
else if (it.evidence > 0)
|
|
288
|
+
closeKind = "evidence";
|
|
289
|
+
}
|
|
290
|
+
const stalls = it.stalls.map(([gi, n]) => {
|
|
291
|
+
const gap = work.gaps[gi];
|
|
292
|
+
return { ...refineGap(gap, events), start: gap.start, end: gap.end, ms: n, via: gap.via };
|
|
293
|
+
});
|
|
294
|
+
const stallMs = {};
|
|
295
|
+
for (const st of stalls)
|
|
296
|
+
stallMs[st.kind] = (stallMs[st.kind] ?? 0) + st.ms;
|
|
297
|
+
let open;
|
|
298
|
+
if (it.status === "in_progress") {
|
|
299
|
+
const pending = pendingChildren(kids?.names ?? []);
|
|
300
|
+
const ledgerWait = openWait(events);
|
|
301
|
+
const since = work.idleSince ?? end;
|
|
302
|
+
if (pending.length)
|
|
303
|
+
open = { since, kind: "child", on: pending.at(-1) };
|
|
304
|
+
else if (ledgerWait)
|
|
305
|
+
open = { since, ...ledgerWait };
|
|
306
|
+
else
|
|
307
|
+
open = work.idleSince ? { since, kind: "human" } : { since, kind: "working" };
|
|
308
|
+
}
|
|
309
|
+
const ownerChild = kids?.owner;
|
|
310
|
+
out.push({
|
|
311
|
+
key: it.key,
|
|
312
|
+
title: it.title,
|
|
313
|
+
owner: it.owner,
|
|
314
|
+
project: s.project,
|
|
315
|
+
session: s.sessionId,
|
|
316
|
+
sessions: [s.sessionId],
|
|
317
|
+
level: it.level,
|
|
318
|
+
status: it.status,
|
|
319
|
+
created: it.created,
|
|
320
|
+
start: it.start,
|
|
321
|
+
close: it.close,
|
|
322
|
+
activeMs,
|
|
323
|
+
closeKind,
|
|
324
|
+
closeAt,
|
|
325
|
+
thread: th?.id,
|
|
326
|
+
evidence: it.evidence,
|
|
327
|
+
blockedBy: it.blockedBy,
|
|
328
|
+
mainCost: it.mainCost,
|
|
329
|
+
childCost: round(kids?.cost ?? 0),
|
|
330
|
+
children: kids?.names ?? [],
|
|
331
|
+
kind: kids?.names.length ? "delegated" : "self",
|
|
332
|
+
role: ownerChild ? ownerChild.role : "self",
|
|
333
|
+
model: ownerChild ? ownerChild.model : s.model,
|
|
334
|
+
anchorloop: versionAt(changes, ANCHORLOOP, it.start ?? it.created),
|
|
335
|
+
lines: lines.get(it),
|
|
336
|
+
stalls,
|
|
337
|
+
stallMs,
|
|
338
|
+
open,
|
|
339
|
+
lastActivity: end,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
options.lines?.save();
|
|
344
|
+
return { v: 1, built: options.now.toISOString(), items: mergeByKey(out), sessions };
|
|
345
|
+
}
|
|
346
|
+
/** One item per key: a uid or an import carries the same item into another session. */
|
|
347
|
+
function mergeByKey(items) {
|
|
348
|
+
const by = new Map();
|
|
349
|
+
for (const it of items)
|
|
350
|
+
by.set(it.key, [...(by.get(it.key) ?? []), it]);
|
|
351
|
+
const out = [];
|
|
352
|
+
for (const group of by.values()) {
|
|
353
|
+
if (group.length === 1) {
|
|
354
|
+
out.push(group[0]);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
group.sort((a, b) => a.lastActivity.localeCompare(b.lastActivity));
|
|
358
|
+
// The close, its kind, signal and thread come from the copy that closed the item, not from the newest copy.
|
|
359
|
+
const closing = group.filter((g) => g.status === "completed" || g.status === "deleted").sort((a, b) => (a.close ?? "").localeCompare(b.close ?? "")).at(-1);
|
|
360
|
+
const newest = group.at(-1);
|
|
361
|
+
const reopened = closing && newest.status === "in_progress" && (newest.start ?? "") > (closing.close ?? "");
|
|
362
|
+
const last = closing && !reopened ? closing : newest;
|
|
363
|
+
const starts = group.map((g) => g.start).filter((x) => !!x).sort();
|
|
364
|
+
const stallMs = {};
|
|
365
|
+
for (const g of group)
|
|
366
|
+
for (const [k, v] of Object.entries(g.stallMs))
|
|
367
|
+
stallMs[k] = (stallMs[k] ?? 0) + v;
|
|
368
|
+
out.push({
|
|
369
|
+
...last,
|
|
370
|
+
sessions: group.map((g) => g.session),
|
|
371
|
+
created: group.map((g) => g.created).sort()[0],
|
|
372
|
+
start: starts[0],
|
|
373
|
+
activeMs: group.reduce((s, g) => s + g.activeMs, 0),
|
|
374
|
+
mainCost: round(group.reduce((s, g) => s + g.mainCost, 0)),
|
|
375
|
+
childCost: round(group.reduce((s, g) => s + g.childCost, 0)),
|
|
376
|
+
children: [...new Set(group.flatMap((g) => g.children))],
|
|
377
|
+
kind: group.some((g) => g.kind === "delegated") ? "delegated" : "self",
|
|
378
|
+
stalls: group.flatMap((g) => g.stalls),
|
|
379
|
+
stallMs,
|
|
380
|
+
evidence: Math.max(...group.map((g) => g.evidence)),
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
return out.sort((a, b) => (a.start ?? a.created).localeCompare(b.start ?? b.created));
|
|
384
|
+
}
|
|
385
|
+
/** `pi.workitem` and `pi.stall` records for the joined items. */
|
|
386
|
+
export function workRecords(file) {
|
|
387
|
+
const out = [];
|
|
388
|
+
for (const it of file.items) {
|
|
389
|
+
const base = { "session.id": it.session, "pi.project": it.project, "pi.item.key": it.key };
|
|
390
|
+
out.push(record({
|
|
391
|
+
name: NAMES.workitem,
|
|
392
|
+
kind: "span",
|
|
393
|
+
ts: it.start ?? it.created,
|
|
394
|
+
end_ts: it.close,
|
|
395
|
+
duration_ms: it.activeMs,
|
|
396
|
+
source: "backfill",
|
|
397
|
+
span_id: spanId(it.session, `item:${it.key}`),
|
|
398
|
+
attrs: {
|
|
399
|
+
...base,
|
|
400
|
+
"pi.item.title": it.title,
|
|
401
|
+
"pi.item.owner": it.owner,
|
|
402
|
+
"pi.item.level": it.level,
|
|
403
|
+
"pi.item.status": it.status,
|
|
404
|
+
"pi.item.created": it.created,
|
|
405
|
+
"pi.item.close_kind": it.closeKind,
|
|
406
|
+
"pi.item.thread": it.thread,
|
|
407
|
+
"pi.item.evidence_n": it.evidence,
|
|
408
|
+
"pi.item.blocked_by_n": it.blockedBy,
|
|
409
|
+
"pi.usage.cost_usd": it.mainCost,
|
|
410
|
+
"pi.item.child_cost_usd": it.childCost,
|
|
411
|
+
"pi.item.children": it.children,
|
|
412
|
+
"pi.item.lines_changed": it.lines,
|
|
413
|
+
"pi.item.sessions": it.sessions.length > 1 ? it.sessions : undefined,
|
|
414
|
+
},
|
|
415
|
+
}));
|
|
416
|
+
for (const st of it.stalls) {
|
|
417
|
+
out.push(record({ name: NAMES.stall, kind: "span", ts: st.start, end_ts: st.end, duration_ms: st.ms, source: "backfill", attrs: { ...base, "pi.stall.kind": st.kind, "pi.stall.on": st.on, "pi.stall.via": st.via } }));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return out;
|
|
421
|
+
}
|
|
422
|
+
export function writeWork(layout, file) {
|
|
423
|
+
atomicWrite(layout.items, JSON.stringify(file));
|
|
424
|
+
atomicWrite(layout.itemRecords, workRecords(file).map((r) => `${JSON.stringify(r)}\n`).join(""));
|
|
425
|
+
}
|
|
426
|
+
export function loadWork(layout) {
|
|
427
|
+
return existsSync(layout.items) ? JSON.parse(readFileSync(layout.items, "utf8")) : undefined;
|
|
428
|
+
}
|
|
429
|
+
export const sbDirOf = (agentDir) => join(agentDir, "straw-boss");
|