pi-evals 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +23 -9
  3. package/dist/build.js +14 -4
  4. package/dist/cli.js +2 -2
  5. package/dist/coverage.js +8 -1
  6. package/dist/extract/run.js +1 -1
  7. package/dist/extract/session.js +43 -3
  8. package/dist/findings.js +54 -0
  9. package/dist/index.js +14 -7
  10. package/dist/meta.js +43 -1
  11. package/dist/model.js +35 -14
  12. package/dist/ops.js +53 -22
  13. package/dist/paths.js +3 -0
  14. package/dist/query.js +36 -13
  15. package/dist/ranges.js +14 -0
  16. package/dist/render.js +15 -5
  17. package/dist/report/concepts.js +23 -1
  18. package/dist/report/findings.js +12 -1
  19. package/dist/report/sections.js +7 -5
  20. package/dist/report/strip.js +42 -0
  21. package/dist/report/style.js +14 -1
  22. package/dist/report/timeline.js +5 -14
  23. package/dist/report/week.js +21 -13
  24. package/dist/report/work.js +59 -0
  25. package/dist/schema.js +16 -1
  26. package/dist/trends.js +58 -0
  27. package/dist/work/join.js +429 -0
  28. package/dist/work/model.js +145 -0
  29. package/dist/work/query.js +59 -0
  30. package/dist/work/sb.js +131 -0
  31. package/dist/work/track.js +323 -0
  32. package/docs/design.md +15 -0
  33. package/docs/schema.md +8 -2
  34. package/package.json +5 -2
  35. package/scripts/change-impact.mjs +18 -0
  36. package/scripts/package-errors.mjs +10 -0
  37. package/scripts/query-lib.mjs +36 -0
  38. package/scripts/skill-days.mjs +9 -0
  39. package/skills/analyzing-evals/SKILL.md +23 -0
  40. package/src/aggregate.ts +14 -2
  41. package/src/build.ts +13 -4
  42. package/src/cli.ts +2 -2
  43. package/src/coverage.ts +8 -1
  44. package/src/extract/run.ts +1 -1
  45. package/src/extract/session.ts +36 -2
  46. package/src/findings.ts +52 -0
  47. package/src/index.ts +14 -9
  48. package/src/meta.ts +45 -1
  49. package/src/model.ts +40 -15
  50. package/src/ops.ts +50 -22
  51. package/src/paths.ts +7 -0
  52. package/src/query.ts +32 -13
  53. package/src/ranges.ts +15 -0
  54. package/src/render.ts +15 -5
  55. package/src/report/concepts.ts +30 -1
  56. package/src/report/findings.ts +19 -1
  57. package/src/report/sections.ts +9 -9
  58. package/src/report/strip.ts +40 -0
  59. package/src/report/style.ts +14 -1
  60. package/src/report/timeline.ts +6 -22
  61. package/src/report/week.ts +21 -17
  62. package/src/report/work.ts +87 -0
  63. package/src/schema.ts +16 -1
  64. package/src/trends.ts +61 -0
  65. package/src/work/join.ts +476 -0
  66. package/src/work/model.ts +179 -0
  67. package/src/work/query.ts +53 -0
  68. package/src/work/sb.ts +158 -0
  69. package/src/work/track.ts +397 -0
@@ -0,0 +1,476 @@
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 type { SessionSummary } from "../aggregate.ts";
10
+ import { type Change, versionAt } from "../changes.ts";
11
+ import type { Layout } from "../paths.ts";
12
+ import { type EvalRecord, NAMES, record, spanId } from "../schema.ts";
13
+ import { type Car, type LedgerEvent, readCars, readLedger, readThreads, type Thread } from "./sb.ts";
14
+ import type { Gap, ItemRaw, SessionWork, StallKind } from "./track.ts";
15
+
16
+ export const ANCHORLOOP = ["pi-anchorloop", "pi-aaaav", "aaaav"];
17
+ export type CloseKind = "review_done" | "landed" | "wrap" | "evidence" | "unproven" | "deleted" | "open";
18
+ export const CLOSE_KINDS: CloseKind[] = ["review_done", "landed", "wrap", "evidence", "unproven", "deleted", "open"];
19
+ export const STALL_KINDS: StallKind[] = ["human", "peer", "child", "timer", "ci", "device"];
20
+
21
+ export interface Stall {
22
+ kind: StallKind;
23
+ on?: string;
24
+ start: string;
25
+ end: string;
26
+ /** Milliseconds of this gap inside the item's active window. */
27
+ ms: number;
28
+ via: Gap["via"];
29
+ }
30
+
31
+ export interface WorkItem {
32
+ key: string;
33
+ title: string;
34
+ owner?: string;
35
+ project: string;
36
+ session: string;
37
+ /** Every session the item ran in (one, unless a uid or an import carried it on). */
38
+ sessions: string[];
39
+ level: "top" | "nested";
40
+ status: ItemRaw["status"];
41
+ created: string;
42
+ start?: string;
43
+ close?: string;
44
+ activeMs: number;
45
+ closeKind: CloseKind;
46
+ /** When the closing signal happened: the reviewer's `done`, the car landing, or the wrap. */
47
+ closeAt?: string;
48
+ thread?: string;
49
+ evidence: number;
50
+ blockedBy: number;
51
+ /** Estimated: the main's cost in the window, split evenly among items active at the same moment. */
52
+ mainCost: number;
53
+ /** Exact: the whole cost of every subagent session joined to the item. */
54
+ childCost: number;
55
+ children: string[];
56
+ /** `delegated` when a subagent did (part of) the work, else `self`. */
57
+ kind: "delegated" | "self";
58
+ role: string;
59
+ model?: string;
60
+ anchorloop?: string;
61
+ lines?: number;
62
+ stalls: Stall[];
63
+ stallMs: Partial<Record<StallKind, number>>;
64
+ /** For an item still open when its session file ends: since when it waits, and on what. */
65
+ open?: { since: string; kind: StallKind | "working"; on?: string };
66
+ lastActivity: string;
67
+ }
68
+
69
+ export interface ItemsFile {
70
+ v: 1;
71
+ built: string;
72
+ items: WorkItem[];
73
+ /** Main cost outside every item window, per session (for the attribution card). */
74
+ sessions: { id: string; project: string; last: string; unattributed: number }[];
75
+ }
76
+
77
+ interface Child {
78
+ id: string;
79
+ name?: string;
80
+ cost: number;
81
+ role: string;
82
+ model: string;
83
+ at: string;
84
+ cwd?: string;
85
+ }
86
+
87
+ const round = (v: number) => Math.round(v * 1e6) / 1e6;
88
+ const ms = (iso?: string) => (iso ? Date.parse(iso) : Number.NaN);
89
+ const TICKET = /\b[A-Z][A-Z0-9]+-\d+\b/g;
90
+ const prefixOf = (owner?: string) => (owner && owner.includes("-") ? owner.slice(0, owner.lastIndexOf("-")) : undefined);
91
+ const short = (session: string) => session.slice(0, 8);
92
+
93
+ function atomicWrite(file: string, text: string) {
94
+ mkdirSync(dirname(file), { recursive: true });
95
+ const tmp = `${file}.${process.pid}.tmp`;
96
+ writeFileSync(tmp, text);
97
+ renameSync(tmp, file);
98
+ }
99
+
100
+ /** Lines changed between two commits, by `git diff --numstat`, cached on disk; numbers only. */
101
+ export class Lines {
102
+ private cache: { repo: Record<string, string>; miss: Record<string, string>; diff: Record<string, number | null> };
103
+ private file: string;
104
+ private now: Date;
105
+ constructor(file: string, now: Date) {
106
+ this.file = file;
107
+ this.now = now;
108
+ const raw = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as Partial<Lines["cache"]>) : {};
109
+ this.cache = { repo: raw.repo ?? {}, miss: raw.miss ?? {}, diff: raw.diff ?? {} };
110
+ }
111
+ private git(dir: string, args: string[]) {
112
+ return spawnSync("git", ["-C", dir, ...args], { encoding: "utf8", maxBuffer: 64 << 20 });
113
+ }
114
+ /** The first candidate repository holding `sha`. Misses are re-checked after a day. */
115
+ repoOf(sha: string, dirs: string[]): string | undefined {
116
+ const hit = this.cache.repo[sha];
117
+ if (hit) return hit;
118
+ const missed = this.cache.miss[sha];
119
+ if (missed && this.now.getTime() - Date.parse(missed) < 86_400_000) return undefined;
120
+ for (const dir of dirs) {
121
+ if (!existsSync(dir)) continue;
122
+ if (this.git(dir, ["cat-file", "-e", `${sha}^{commit}`]).status === 0) {
123
+ this.cache.repo[sha] = dir;
124
+ return dir;
125
+ }
126
+ }
127
+ this.cache.miss[sha] = this.now.toISOString();
128
+ return undefined;
129
+ }
130
+ /** Added plus deleted lines from `base` to `head`, or undefined when `base` is not an ancestor of `head`. */
131
+ between(dir: string, base: string, head: string): number | undefined {
132
+ const key = `${dir}|${base}|${head}`;
133
+ if (key in this.cache.diff) return this.cache.diff[key] ?? undefined;
134
+ let n: number | null = null;
135
+ if (this.git(dir, ["merge-base", "--is-ancestor", base, head]).status === 0) {
136
+ const res = this.git(dir, ["diff", "--numstat", base, head]);
137
+ if (res.status === 0) {
138
+ n = 0;
139
+ for (const line of res.stdout.split("\n")) {
140
+ const [a, d] = line.split("\t");
141
+ if (/^\d+$/.test(a ?? "") && /^\d+$/.test(d ?? "")) n += Number(a) + Number(d);
142
+ }
143
+ }
144
+ }
145
+ this.cache.diff[key] = n;
146
+ return n ?? undefined;
147
+ }
148
+ save() {
149
+ atomicWrite(this.file, JSON.stringify(this.cache));
150
+ }
151
+ }
152
+
153
+ function refineGap(gap: Gap, events: LedgerEvent[] | undefined): { kind: StallKind; on?: string } {
154
+ if (!events?.length) return { kind: gap.kind, on: gap.on };
155
+ const lo = ms(gap.start) - 2000;
156
+ const hi = ms(gap.end) + 5000;
157
+ const kinds: Record<string, [StallKind, string]> = {
158
+ wait_answered: ["human", "W"],
159
+ wait_returned: ["human", "W"],
160
+ wait_parked: ["human", "W"],
161
+ link_wait_done: ["device", "L"],
162
+ thread_close: ["child", "T"],
163
+ };
164
+ let best: LedgerEvent | undefined;
165
+ for (const e of events) {
166
+ const t = ms(e.at);
167
+ if (t >= lo && t <= hi && kinds[e.kind]) best = e;
168
+ }
169
+ if (!best) return { kind: gap.kind, on: gap.on };
170
+ const [kind, prefix] = kinds[best.kind];
171
+ const id = best.id ?? "";
172
+ return { kind, on: id ? (/^\d+$/.test(id) ? `${prefix}${id}` : id) : gap.on };
173
+ }
174
+
175
+ /** An open wait in the ledger for this session at its end: a wait card, a link wait, or a review thread. */
176
+ function openWait(events: LedgerEvent[] | undefined): { kind: StallKind; on?: string } | undefined {
177
+ if (!events?.length) return undefined;
178
+ const open = new Map<string, { kind: StallKind; on?: string }>();
179
+ const pairs: Record<string, [string, StallKind] | undefined> = { wait_raised: ["W", "human"], link_wait_open: ["L", "device"], thread_open: ["T", "child"] };
180
+ const ends = new Set(["wait_answered", "wait_returned", "wait_parked", "link_wait_done", "thread_close"]);
181
+ for (const e of events) {
182
+ const id = e.id ?? "";
183
+ const open_ = pairs[e.kind];
184
+ if (open_) open.set(`${open_[0]}:${id}`, { kind: open_[1], on: /^\d+$/.test(id) ? `${open_[0]}${id}` : id || undefined });
185
+ else if (ends.has(e.kind)) for (const k of [...open.keys()]) if (k.endsWith(`:${id}`)) open.delete(k);
186
+ }
187
+ return [...open.values()].at(-1);
188
+ }
189
+
190
+ /** Picks one item for a child among candidates: the one whose window holds the launch, else the closest start before it. */
191
+ function byTime(items: ItemRaw[], at: string, end: string): ItemRaw | undefined {
192
+ const t = ms(at);
193
+ const inside = items.filter((it) => t >= ms(it.created) && t <= ms(it.close ?? end));
194
+ if (inside.length) return inside.at(-1);
195
+ const before = items.filter((it) => ms(it.created) <= t).sort((a, b) => ms(b.created) - ms(a.created));
196
+ return before[0] ?? items[0];
197
+ }
198
+
199
+ /** The children of one session: each child belongs to one parent, the one its brief names, else the one that spawned it. */
200
+ function childrenOf(s: SessionSummary, parentOf: Map<string, string>, byLogical: Map<string, SessionSummary>): Child[] {
201
+ const launches = new Map((s.work?.launches ?? []).map((l) => [l.id, l]));
202
+ const ids = new Set([...s.spawned.map((sp) => sp.id), ...[...parentOf].filter(([, p]) => p === s.sessionId).map(([id]) => id)]);
203
+ const out: Child[] = [];
204
+ for (const id of ids) {
205
+ if (parentOf.get(id) !== s.sessionId) continue;
206
+ const c = byLogical.get(id);
207
+ const l = launches.get(id);
208
+ 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 });
209
+ }
210
+ return out;
211
+ }
212
+
213
+ export function joinWork(options: { summaries: SessionSummary[]; changes: Change[]; sbDir: string; repos: string[]; lines?: Lines; now: Date }): ItemsFile {
214
+ const { summaries, changes } = options;
215
+ const withWork = summaries.filter((s) => s.work?.items.length);
216
+ const parentOf = new Map<string, string>();
217
+ const byLogical = new Map<string, SessionSummary>();
218
+ for (const s of summaries) for (const sp of s.spawned) parentOf.set(sp.id, s.sessionId);
219
+ for (const s of summaries) {
220
+ if (s.kind !== "subagent") continue;
221
+ if (s.logicalId) byLogical.set(s.logicalId, s);
222
+ if (s.logicalId && s.parentId) parentOf.set(s.logicalId, s.parentId);
223
+ }
224
+ const threads = readThreads(options.sbDir, new Set(withWork.map((s) => short(s.sessionId))));
225
+ const cars = readCars(options.sbDir);
226
+ const ledger = readLedger(options.sbDir);
227
+ const out: WorkItem[] = [];
228
+ const sessions: ItemsFile["sessions"] = [];
229
+ for (const s of withWork) {
230
+ const work = s.work as SessionWork;
231
+ const end = work.lastActivity;
232
+ sessions.push({ id: s.sessionId, project: s.project, last: end, unattributed: work.unattributed });
233
+ // A task carried in already done is no item here, so it must not win a thread or a child either.
234
+ const top = work.items.filter((it) => it.level === "top" && !it.carried);
235
+ const children = childrenOf(s, parentOf, byLogical);
236
+ const sessionThreads = threads.get(s.sessionId) ?? [];
237
+ const pairs = new Map(work.pairs.map((p) => [p.thread, p]));
238
+ const itemOf = (it: ItemRaw) => new Set([it.key, it.uid, `${short(s.sessionId)}#${it.id}`].filter(Boolean) as string[]);
239
+ // Threads: the producer's item link, else the worker named as the item's owner.
240
+ const threadOf = new Map<ItemRaw, Thread>();
241
+ for (const th of sessionThreads) {
242
+ const item = th.item ?? pairs.get(th.id)?.item;
243
+ let target = item ? top.find((it) => itemOf(it).has(item)) : undefined;
244
+ if (!target && th.worker) {
245
+ const owned = top.filter((it) => it.owner === th.worker);
246
+ target = owned.length ? byTime(owned, th.created ?? end, end) : undefined;
247
+ }
248
+ if (target && !threadOf.has(target)) threadOf.set(target, th);
249
+ }
250
+ // Children: the strongest link wins (launch item, evidence ref, thread pair, owner name, reviewer prefix).
251
+ const childCost = new Map<ItemRaw, { cost: number; names: string[]; owner?: Child }>();
252
+ for (const c of children) {
253
+ const launchItem = work.launches.find((l) => l.id === c.id)?.item;
254
+ const levels: ((it: ItemRaw) => boolean)[] = [
255
+ (it) => (!!launchItem && itemOf(it).has(launchItem)) || it.refs.includes(`child:${c.id}`),
256
+ (it) => {
257
+ const th = threadOf.get(it);
258
+ return !!th && !!c.name && (th.reviewer === c.name || th.worker === c.name);
259
+ },
260
+ (it) => !!c.name && it.owner === c.name,
261
+ (it) => {
262
+ const p = prefixOf(it.owner);
263
+ return !!p && !!c.name && new RegExp(`^${p.replace(/[.+]/g, "\\$&")}-review\\d*$`).test(c.name);
264
+ },
265
+ ];
266
+ let target: ItemRaw | undefined;
267
+ for (const match of levels) {
268
+ const hits = top.filter(match);
269
+ if (hits.length) {
270
+ target = byTime(hits, c.at, end);
271
+ break;
272
+ }
273
+ }
274
+ if (!target) continue;
275
+ const row = childCost.get(target) ?? { cost: 0, names: [] };
276
+ row.cost += c.cost;
277
+ if (c.name && !row.names.includes(c.name)) row.names.push(c.name);
278
+ if (c.name && c.name === target.owner) row.owner = c;
279
+ else row.owner ??= c;
280
+ childCost.set(target, row);
281
+ }
282
+ // Size: lines from the last evidence commit of the item before (same repository) to this item's last.
283
+ const repos = [s.cwd, ...children.map((c) => c.cwd), ...options.repos].filter((d): d is string => !!d).filter((d, i, a) => a.indexOf(d) === i);
284
+ const lines = new Map<ItemRaw, number>();
285
+ if (options.lines) {
286
+ const prev = new Map<string, string>();
287
+ for (const it of [...top].filter((i) => i.shas.length).sort((a, b) => ms(a.close ?? end) - ms(b.close ?? end))) {
288
+ const located = it.shas.map((sha) => [sha, options.lines!.repoOf(sha, repos)] as const);
289
+ const head = located.findLast(([, repo]) => repo);
290
+ if (head) {
291
+ const repo = head[1]!;
292
+ const own = located.filter(([, r]) => r === repo).map(([sha]) => sha);
293
+ const base = prev.get(repo) ?? (own.length > 1 ? own[0] : undefined);
294
+ if (base && base !== head[0]) {
295
+ const n = options.lines.between(repo, base, head[0]);
296
+ if (n !== undefined) lines.set(it, n);
297
+ }
298
+ }
299
+ for (const [sha, repo] of located) if (repo) prev.set(repo, sha);
300
+ }
301
+ }
302
+ const carsHere = cars.get(s.sessionId) ?? [];
303
+ const events = ledger.get(s.sessionId);
304
+ const pendingChildren = (names: string[]) =>
305
+ names.filter((name) => {
306
+ const evs = work.childEvents.filter((e) => e[1] === name);
307
+ const launched = work.launches.filter((l) => l.name === name).map((l) => l.at);
308
+ const lastStart = [...launched, ...evs.filter((e) => e[2] === "resume").map((e) => e[0])].sort().at(-1);
309
+ const lastResult = evs.filter((e) => e[2] === "result").map((e) => e[0]).sort().at(-1);
310
+ return !!lastStart && (!lastResult || lastResult < lastStart);
311
+ });
312
+ for (const it of work.items) {
313
+ // Closed before this session saw it: its close belongs to the session (or tool) that closed it.
314
+ if (it.carried) continue;
315
+ const kids = it.level === "top" ? childCost.get(it) : undefined;
316
+ const th = threadOf.get(it);
317
+ const activeMs = it.active.reduce((sum, [a, b]) => sum + Math.max(0, ms(b ?? end) - ms(a)), 0);
318
+ let closeKind: CloseKind = it.status === "deleted" ? "deleted" : it.status === "completed" ? "unproven" : "open";
319
+ let closeAt: string | undefined;
320
+ if (it.status === "completed" && it.close) {
321
+ const close = ms(it.close);
322
+ const from = ms(it.start ?? it.created);
323
+ const tickets = new Set(it.title.match(TICKET) ?? []);
324
+ 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))));
325
+ 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);
326
+ if (th?.closedAs === "done" && th.closed && ms(th.closed) <= close + 300_000) {
327
+ closeKind = "review_done";
328
+ closeAt = th.closed;
329
+ } else if (landed) {
330
+ closeKind = "landed";
331
+ closeAt = landed.landed;
332
+ } else if (wrap) {
333
+ closeKind = "wrap";
334
+ closeAt = wrap.at;
335
+ } else if (it.evidence > 0) closeKind = "evidence";
336
+ }
337
+ const stalls: Stall[] = it.stalls.map(([gi, n]) => {
338
+ const gap = work.gaps[gi];
339
+ return { ...refineGap(gap, events), start: gap.start, end: gap.end, ms: n, via: gap.via };
340
+ });
341
+ const stallMs: WorkItem["stallMs"] = {};
342
+ for (const st of stalls) stallMs[st.kind] = (stallMs[st.kind] ?? 0) + st.ms;
343
+ let open: WorkItem["open"];
344
+ if (it.status === "in_progress") {
345
+ const pending = pendingChildren(kids?.names ?? []);
346
+ const ledgerWait = openWait(events);
347
+ const since = work.idleSince ?? end;
348
+ if (pending.length) open = { since, kind: "child", on: pending.at(-1) };
349
+ else if (ledgerWait) open = { since, ...ledgerWait };
350
+ else open = work.idleSince ? { since, kind: "human" } : { since, kind: "working" };
351
+ }
352
+ const ownerChild = kids?.owner;
353
+ out.push({
354
+ key: it.key,
355
+ title: it.title,
356
+ owner: it.owner,
357
+ project: s.project,
358
+ session: s.sessionId,
359
+ sessions: [s.sessionId],
360
+ level: it.level,
361
+ status: it.status,
362
+ created: it.created,
363
+ start: it.start,
364
+ close: it.close,
365
+ activeMs,
366
+ closeKind,
367
+ closeAt,
368
+ thread: th?.id,
369
+ evidence: it.evidence,
370
+ blockedBy: it.blockedBy,
371
+ mainCost: it.mainCost,
372
+ childCost: round(kids?.cost ?? 0),
373
+ children: kids?.names ?? [],
374
+ kind: kids?.names.length ? "delegated" : "self",
375
+ role: ownerChild ? ownerChild.role : "self",
376
+ model: ownerChild ? ownerChild.model : s.model,
377
+ anchorloop: versionAt(changes, ANCHORLOOP, it.start ?? it.created),
378
+ lines: lines.get(it),
379
+ stalls,
380
+ stallMs,
381
+ open,
382
+ lastActivity: end,
383
+ });
384
+ }
385
+ }
386
+ options.lines?.save();
387
+ return { v: 1, built: options.now.toISOString(), items: mergeByKey(out), sessions };
388
+ }
389
+
390
+ /** One item per key: a uid or an import carries the same item into another session. */
391
+ function mergeByKey(items: WorkItem[]): WorkItem[] {
392
+ const by = new Map<string, WorkItem[]>();
393
+ for (const it of items) by.set(it.key, [...(by.get(it.key) ?? []), it]);
394
+ const out: WorkItem[] = [];
395
+ for (const group of by.values()) {
396
+ if (group.length === 1) {
397
+ out.push(group[0]);
398
+ continue;
399
+ }
400
+ group.sort((a, b) => a.lastActivity.localeCompare(b.lastActivity));
401
+ // The close, its kind, signal and thread come from the copy that closed the item, not from the newest copy.
402
+ const closing = group.filter((g) => g.status === "completed" || g.status === "deleted").sort((a, b) => (a.close ?? "").localeCompare(b.close ?? "")).at(-1);
403
+ const newest = group.at(-1)!;
404
+ const reopened = closing && newest.status === "in_progress" && (newest.start ?? "") > (closing.close ?? "");
405
+ const last = closing && !reopened ? closing : newest;
406
+ const starts = group.map((g) => g.start).filter((x): x is string => !!x).sort();
407
+ const stallMs: WorkItem["stallMs"] = {};
408
+ for (const g of group) for (const [k, v] of Object.entries(g.stallMs) as [StallKind, number][]) stallMs[k] = (stallMs[k] ?? 0) + v;
409
+ out.push({
410
+ ...last,
411
+ sessions: group.map((g) => g.session),
412
+ created: group.map((g) => g.created).sort()[0],
413
+ start: starts[0],
414
+ activeMs: group.reduce((s, g) => s + g.activeMs, 0),
415
+ mainCost: round(group.reduce((s, g) => s + g.mainCost, 0)),
416
+ childCost: round(group.reduce((s, g) => s + g.childCost, 0)),
417
+ children: [...new Set(group.flatMap((g) => g.children))],
418
+ kind: group.some((g) => g.kind === "delegated") ? "delegated" : "self",
419
+ stalls: group.flatMap((g) => g.stalls),
420
+ stallMs,
421
+ evidence: Math.max(...group.map((g) => g.evidence)),
422
+ });
423
+ }
424
+ return out.sort((a, b) => (a.start ?? a.created).localeCompare(b.start ?? b.created));
425
+ }
426
+
427
+ /** `pi.workitem` and `pi.stall` records for the joined items. */
428
+ export function workRecords(file: ItemsFile): EvalRecord[] {
429
+ const out: EvalRecord[] = [];
430
+ for (const it of file.items) {
431
+ const base = { "session.id": it.session, "pi.project": it.project, "pi.item.key": it.key };
432
+ out.push(
433
+ record({
434
+ name: NAMES.workitem,
435
+ kind: "span",
436
+ ts: it.start ?? it.created,
437
+ end_ts: it.close,
438
+ duration_ms: it.activeMs,
439
+ source: "backfill",
440
+ span_id: spanId(it.session, `item:${it.key}`),
441
+ attrs: {
442
+ ...base,
443
+ "pi.item.title": it.title,
444
+ "pi.item.owner": it.owner,
445
+ "pi.item.level": it.level,
446
+ "pi.item.status": it.status,
447
+ "pi.item.created": it.created,
448
+ "pi.item.close_kind": it.closeKind,
449
+ "pi.item.thread": it.thread,
450
+ "pi.item.evidence_n": it.evidence,
451
+ "pi.item.blocked_by_n": it.blockedBy,
452
+ "pi.usage.cost_usd": it.mainCost,
453
+ "pi.item.child_cost_usd": it.childCost,
454
+ "pi.item.children": it.children,
455
+ "pi.item.lines_changed": it.lines,
456
+ "pi.item.sessions": it.sessions.length > 1 ? it.sessions : undefined,
457
+ },
458
+ }),
459
+ );
460
+ for (const st of it.stalls) {
461
+ 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 } }));
462
+ }
463
+ }
464
+ return out;
465
+ }
466
+
467
+ export function writeWork(layout: Layout, file: ItemsFile): void {
468
+ atomicWrite(layout.items, JSON.stringify(file));
469
+ atomicWrite(layout.itemRecords, workRecords(file).map((r) => `${JSON.stringify(r)}\n`).join(""));
470
+ }
471
+
472
+ export function loadWork(layout: Layout): ItemsFile | undefined {
473
+ return existsSync(layout.items) ? (JSON.parse(readFileSync(layout.items, "utf8")) as ItemsFile) : undefined;
474
+ }
475
+
476
+ export const sbDirOf = (agentDir: string) => join(agentDir, "straw-boss");
@@ -0,0 +1,179 @@
1
+ /**
2
+ * The report's 「工作」 numbers for one date range: the items, what they cost and where they closed or stalled, the
3
+ * open items and what they wait on, and a like-with-like comparison that says plainly when there are too few items.
4
+ */
5
+ import type { Filter } from "../model.ts";
6
+ import { CLOSE_KINDS, type CloseKind, type ItemsFile, STALL_KINDS, type WorkItem } from "./join.ts";
7
+ import type { StallKind } from "./track.ts";
8
+
9
+ /** A group needs at least this many items before the report compares it. */
10
+ export const MIN_ITEMS = 5;
11
+ /** Medians closer than this share are reported as no clear difference. */
12
+ export const SAME_WITHIN = 0.2;
13
+ const LIST_MAX = 60;
14
+ const OPEN_MAX = 15;
15
+
16
+ const round = (v: number, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
17
+ const day = (iso?: string) => iso?.slice(0, 10) ?? "";
18
+ const roundOrNull = (v: number | null, d = 2) => (v === null ? null : round(v, d));
19
+ const minutes = (ms: number) => round(ms / 60_000, 1);
20
+ const total = (it: WorkItem) => it.mainCost + it.childCost;
21
+
22
+ export function median(values: number[]): number | null {
23
+ if (!values.length) return null;
24
+ const v = [...values].sort((a, b) => a - b);
25
+ const mid = v.length >> 1;
26
+ return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
27
+ }
28
+
29
+ export interface Group {
30
+ value: string;
31
+ n: number;
32
+ /** Median cost per item, USD. */
33
+ median: number | null;
34
+ nLines: number;
35
+ /** Median cost per 100 changed lines, over the items with a line count. */
36
+ per100: number | null;
37
+ }
38
+
39
+ export interface Verdict {
40
+ /** `few`: a compared group has fewer than MIN_ITEMS; `same`: medians within 20%; `cheaper`: `a` costs less than `b`. */
41
+ kind: "few" | "same" | "cheaper" | "single";
42
+ a?: string;
43
+ b?: string;
44
+ /** How much less `a` costs than `b`, as a share of `b`. */
45
+ by?: number;
46
+ }
47
+
48
+ export interface Comparison {
49
+ dimension: "role" | "model" | "anchorloop";
50
+ kind: "delegated" | "self";
51
+ groups: Group[];
52
+ verdict: Verdict;
53
+ /** The same, per 100 changed lines, over items with a line count. */
54
+ verdictLines: Verdict;
55
+ }
56
+
57
+ function verdictOf(groups: Group[], pick: (g: Group) => number | null, count: (g: Group) => number): Verdict {
58
+ const usable = groups.filter((g) => count(g) > 0).sort((x, y) => count(y) - count(x));
59
+ if (usable.length < 2) return { kind: "single", a: usable[0]?.value };
60
+ const [x, y] = usable;
61
+ if (count(x) < MIN_ITEMS || count(y) < MIN_ITEMS) return { kind: "few", a: x.value, b: y.value };
62
+ const mx = pick(x) ?? 0;
63
+ const my = pick(y) ?? 0;
64
+ const [lo, hi] = mx <= my ? [x, y] : [y, x];
65
+ const by = Math.max(mx, my) ? (Math.max(mx, my) - Math.min(mx, my)) / Math.max(mx, my) : 0;
66
+ return by < SAME_WITHIN ? { kind: "same", a: x.value, b: y.value, by: round(by, 3) } : { kind: "cheaper", a: lo.value, b: hi.value, by: round(by, 3) };
67
+ }
68
+
69
+ function compare(items: WorkItem[]): Comparison[] {
70
+ const out: Comparison[] = [];
71
+ for (const kind of ["delegated", "self"] as const) {
72
+ const pool = items.filter((it) => it.kind === kind);
73
+ if (!pool.length) continue;
74
+ // Model first: a role split mixes kinds of work (planning and building), so it is the weakest like-with-like.
75
+ const dims: Comparison["dimension"][] = kind === "delegated" ? ["model", "anchorloop", "role"] : ["model", "anchorloop"];
76
+ for (const dimension of dims) {
77
+ const by = new Map<string, WorkItem[]>();
78
+ for (const it of pool) {
79
+ const value = (dimension === "role" ? it.role : dimension === "model" ? it.model : it.anchorloop) ?? "unknown";
80
+ by.set(value, [...(by.get(value) ?? []), it]);
81
+ }
82
+ const groups: Group[] = [...by]
83
+ .map(([value, list]) => {
84
+ const sized = list.filter((it) => it.lines);
85
+ const per = median(sized.map((it) => (100 * total(it)) / (it.lines as number)));
86
+ const med = median(list.map(total));
87
+ return { value, n: list.length, median: med === null ? null : round(med), nLines: sized.length, per100: per === null ? null : round(per) };
88
+ })
89
+ .sort((a, b) => b.n - a.n)
90
+ .slice(0, 4);
91
+ out.push({ dimension, kind, groups, verdict: verdictOf(groups, (g) => g.median, (g) => g.n), verdictLines: verdictOf(groups, (g) => g.per100, (g) => g.nLines) });
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+
97
+ export function workModel(file: ItemsFile | undefined, filter: Filter) {
98
+ if (!file) return null;
99
+ const since = filter.since ?? "";
100
+ const until = filter.until ?? "9999";
101
+ const top = file.items.filter((it) => it.level === "top" && (!filter.project || it.project === filter.project));
102
+ const ended = top.filter((it) => (it.status === "completed" || it.status === "deleted") && day(it.close) >= since && day(it.close) <= until);
103
+ const open = top.filter((it) => (it.status === "in_progress" || it.status === "pending") && day(it.lastActivity) >= since && day(it.created) <= until);
104
+ const done = ended.filter((it) => it.status === "completed");
105
+ const all = [...ended, ...open];
106
+ const closeKinds = Object.fromEntries(CLOSE_KINDS.map((k) => [k, 0])) as Record<CloseKind, number>;
107
+ for (const it of all) closeKinds[it.closeKind] += 1;
108
+ const stallMs = Object.fromEntries(STALL_KINDS.map((k) => [k, 0])) as Record<StallKind, number>;
109
+ for (const it of done) for (const [k, v] of Object.entries(it.stallMs) as [StallKind, number][]) stallMs[k] += v;
110
+ const activeMs = done.reduce((s, it) => s + it.activeMs, 0);
111
+ const sessions = new Set(all.map((it) => it.session));
112
+ const unattributed = file.sessions.filter((s) => sessions.has(s.id)).reduce((sum, s) => sum + s.unattributed, 0);
113
+ // Items whose windows overlapped another item of the same session: their main cost was split.
114
+ const shared = done.filter((it) => it.start && done.some((o) => o !== it && o.session === it.session && o.start && o.start < (it.close ?? "") && it.start! < (o.close ?? ""))).length;
115
+ const costed = done.filter((it) => it.activeMs > 0);
116
+ const list = [...done].sort((a, b) => (b.close ?? "").localeCompare(a.close ?? "")).slice(0, LIST_MAX);
117
+ return {
118
+ present: true as const,
119
+ built: file.built,
120
+ n: all.length,
121
+ completed: done.length,
122
+ deleted: ended.length - done.length,
123
+ inProgress: open.filter((it) => it.status === "in_progress").length,
124
+ pending: open.filter((it) => it.status === "pending").length,
125
+ delegated: done.filter((it) => it.kind === "delegated").length,
126
+ withLines: done.filter((it) => it.lines).length,
127
+ shared,
128
+ cost: {
129
+ main: round(done.reduce((s, it) => s + it.mainCost, 0)),
130
+ child: round(done.reduce((s, it) => s + it.childCost, 0)),
131
+ unattributed: round(unattributed),
132
+ median: roundOrNull(median(costed.map(total))),
133
+ medianMinutes: roundOrNull(median(costed.map((it) => minutes(it.activeMs))), 1),
134
+ },
135
+ closeKinds,
136
+ stallMs,
137
+ activeMs,
138
+ list: list.map((it) => ({
139
+ key: it.key,
140
+ title: it.title,
141
+ owner: it.owner ?? null,
142
+ project: it.project,
143
+ kind: it.kind,
144
+ start: it.start ?? null,
145
+ close: it.close ?? null,
146
+ minutes: minutes(it.activeMs),
147
+ main: round(it.mainCost),
148
+ child: round(it.childCost),
149
+ children: it.children.length,
150
+ closeKind: it.closeKind,
151
+ thread: it.thread ?? null,
152
+ lines: it.lines ?? null,
153
+ stalls: Object.fromEntries((Object.entries(it.stallMs) as [StallKind, number][]).filter(([, v]) => v > 0).map(([k, v]) => [k, minutes(v)])),
154
+ })),
155
+ open: open
156
+ .filter((it) => it.status === "in_progress" && it.open)
157
+ .sort((a, b) => b.lastActivity.localeCompare(a.lastActivity))
158
+ .slice(0, OPEN_MAX)
159
+ .map((it) => ({
160
+ key: it.key,
161
+ title: it.title,
162
+ owner: it.owner ?? null,
163
+ project: it.project,
164
+ session: it.session.slice(0, 13),
165
+ start: it.start ?? null,
166
+ since: it.open!.since,
167
+ kind: it.open!.kind,
168
+ on: it.open!.on ?? null,
169
+ /** Minutes from the start of the wait to when the items were built (the extract). */
170
+ waitMinutes: minutes(Math.max(0, Date.parse(file.built) - Date.parse(it.open!.since))),
171
+ childCost: round(it.childCost),
172
+ mainCost: round(it.mainCost),
173
+ })),
174
+ compare: compare(done.filter((it) => it.activeMs > 0)),
175
+ minItems: MIN_ITEMS,
176
+ };
177
+ }
178
+
179
+ export type WorkModel = NonNullable<ReturnType<typeof workModel>>;