pi-evals 0.3.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 +9 -0
- package/README.md +7 -3
- package/dist/build.js +10 -1
- package/dist/extract/run.js +1 -1
- package/dist/extract/session.js +43 -3
- package/dist/findings.js +4 -0
- package/dist/meta.js +43 -1
- package/dist/model.js +15 -5
- package/dist/ops.js +3 -2
- package/dist/paths.js +3 -0
- package/dist/query.js +5 -1
- package/dist/render.js +1 -0
- package/dist/report/concepts.js +23 -1
- package/dist/report/sections.js +4 -2
- package/dist/report/style.js +5 -0
- package/dist/report/work.js +59 -0
- package/dist/schema.js +16 -1
- 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/schema.md +8 -2
- package/package.json +1 -1
- package/skills/analyzing-evals/SKILL.md +3 -1
- package/src/aggregate.ts +11 -2
- package/src/build.ts +9 -1
- package/src/extract/run.ts +1 -1
- package/src/extract/session.ts +36 -2
- package/src/findings.ts +3 -0
- package/src/meta.ts +45 -1
- package/src/model.ts +19 -6
- package/src/ops.ts +3 -2
- package/src/paths.ts +7 -0
- package/src/query.ts +4 -1
- package/src/render.ts +1 -0
- package/src/report/concepts.ts +30 -1
- package/src/report/sections.ts +6 -4
- package/src/report/style.ts +5 -0
- package/src/report/work.ts +87 -0
- package/src/schema.ts +16 -1
- 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
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
|
};
|
|
@@ -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");
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { CLOSE_KINDS, STALL_KINDS } from "./join.js";
|
|
2
|
+
/** A group needs at least this many items before the report compares it. */
|
|
3
|
+
export const MIN_ITEMS = 5;
|
|
4
|
+
/** Medians closer than this share are reported as no clear difference. */
|
|
5
|
+
export const SAME_WITHIN = 0.2;
|
|
6
|
+
const LIST_MAX = 60;
|
|
7
|
+
const OPEN_MAX = 15;
|
|
8
|
+
const round = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
|
|
9
|
+
const day = (iso) => iso?.slice(0, 10) ?? "";
|
|
10
|
+
const roundOrNull = (v, d = 2) => (v === null ? null : round(v, d));
|
|
11
|
+
const minutes = (ms) => round(ms / 60_000, 1);
|
|
12
|
+
const total = (it) => it.mainCost + it.childCost;
|
|
13
|
+
export function median(values) {
|
|
14
|
+
if (!values.length)
|
|
15
|
+
return null;
|
|
16
|
+
const v = [...values].sort((a, b) => a - b);
|
|
17
|
+
const mid = v.length >> 1;
|
|
18
|
+
return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
|
|
19
|
+
}
|
|
20
|
+
function verdictOf(groups, pick, count) {
|
|
21
|
+
const usable = groups.filter((g) => count(g) > 0).sort((x, y) => count(y) - count(x));
|
|
22
|
+
if (usable.length < 2)
|
|
23
|
+
return { kind: "single", a: usable[0]?.value };
|
|
24
|
+
const [x, y] = usable;
|
|
25
|
+
if (count(x) < MIN_ITEMS || count(y) < MIN_ITEMS)
|
|
26
|
+
return { kind: "few", a: x.value, b: y.value };
|
|
27
|
+
const mx = pick(x) ?? 0;
|
|
28
|
+
const my = pick(y) ?? 0;
|
|
29
|
+
const [lo, hi] = mx <= my ? [x, y] : [y, x];
|
|
30
|
+
const by = Math.max(mx, my) ? (Math.max(mx, my) - Math.min(mx, my)) / Math.max(mx, my) : 0;
|
|
31
|
+
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) };
|
|
32
|
+
}
|
|
33
|
+
function compare(items) {
|
|
34
|
+
const out = [];
|
|
35
|
+
for (const kind of ["delegated", "self"]) {
|
|
36
|
+
const pool = items.filter((it) => it.kind === kind);
|
|
37
|
+
if (!pool.length)
|
|
38
|
+
continue;
|
|
39
|
+
// Model first: a role split mixes kinds of work (planning and building), so it is the weakest like-with-like.
|
|
40
|
+
const dims = kind === "delegated" ? ["model", "anchorloop", "role"] : ["model", "anchorloop"];
|
|
41
|
+
for (const dimension of dims) {
|
|
42
|
+
const by = new Map();
|
|
43
|
+
for (const it of pool) {
|
|
44
|
+
const value = (dimension === "role" ? it.role : dimension === "model" ? it.model : it.anchorloop) ?? "unknown";
|
|
45
|
+
by.set(value, [...(by.get(value) ?? []), it]);
|
|
46
|
+
}
|
|
47
|
+
const groups = [...by]
|
|
48
|
+
.map(([value, list]) => {
|
|
49
|
+
const sized = list.filter((it) => it.lines);
|
|
50
|
+
const per = median(sized.map((it) => (100 * total(it)) / it.lines));
|
|
51
|
+
const med = median(list.map(total));
|
|
52
|
+
return { value, n: list.length, median: med === null ? null : round(med), nLines: sized.length, per100: per === null ? null : round(per) };
|
|
53
|
+
})
|
|
54
|
+
.sort((a, b) => b.n - a.n)
|
|
55
|
+
.slice(0, 4);
|
|
56
|
+
out.push({ dimension, kind, groups, verdict: verdictOf(groups, (g) => g.median, (g) => g.n), verdictLines: verdictOf(groups, (g) => g.per100, (g) => g.nLines) });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
export function workModel(file, filter) {
|
|
62
|
+
if (!file)
|
|
63
|
+
return null;
|
|
64
|
+
const since = filter.since ?? "";
|
|
65
|
+
const until = filter.until ?? "9999";
|
|
66
|
+
const top = file.items.filter((it) => it.level === "top" && (!filter.project || it.project === filter.project));
|
|
67
|
+
const ended = top.filter((it) => (it.status === "completed" || it.status === "deleted") && day(it.close) >= since && day(it.close) <= until);
|
|
68
|
+
const open = top.filter((it) => (it.status === "in_progress" || it.status === "pending") && day(it.lastActivity) >= since && day(it.created) <= until);
|
|
69
|
+
const done = ended.filter((it) => it.status === "completed");
|
|
70
|
+
const all = [...ended, ...open];
|
|
71
|
+
const closeKinds = Object.fromEntries(CLOSE_KINDS.map((k) => [k, 0]));
|
|
72
|
+
for (const it of all)
|
|
73
|
+
closeKinds[it.closeKind] += 1;
|
|
74
|
+
const stallMs = Object.fromEntries(STALL_KINDS.map((k) => [k, 0]));
|
|
75
|
+
for (const it of done)
|
|
76
|
+
for (const [k, v] of Object.entries(it.stallMs))
|
|
77
|
+
stallMs[k] += v;
|
|
78
|
+
const activeMs = done.reduce((s, it) => s + it.activeMs, 0);
|
|
79
|
+
const sessions = new Set(all.map((it) => it.session));
|
|
80
|
+
const unattributed = file.sessions.filter((s) => sessions.has(s.id)).reduce((sum, s) => sum + s.unattributed, 0);
|
|
81
|
+
// Items whose windows overlapped another item of the same session: their main cost was split.
|
|
82
|
+
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;
|
|
83
|
+
const costed = done.filter((it) => it.activeMs > 0);
|
|
84
|
+
const list = [...done].sort((a, b) => (b.close ?? "").localeCompare(a.close ?? "")).slice(0, LIST_MAX);
|
|
85
|
+
return {
|
|
86
|
+
present: true,
|
|
87
|
+
built: file.built,
|
|
88
|
+
n: all.length,
|
|
89
|
+
completed: done.length,
|
|
90
|
+
deleted: ended.length - done.length,
|
|
91
|
+
inProgress: open.filter((it) => it.status === "in_progress").length,
|
|
92
|
+
pending: open.filter((it) => it.status === "pending").length,
|
|
93
|
+
delegated: done.filter((it) => it.kind === "delegated").length,
|
|
94
|
+
withLines: done.filter((it) => it.lines).length,
|
|
95
|
+
shared,
|
|
96
|
+
cost: {
|
|
97
|
+
main: round(done.reduce((s, it) => s + it.mainCost, 0)),
|
|
98
|
+
child: round(done.reduce((s, it) => s + it.childCost, 0)),
|
|
99
|
+
unattributed: round(unattributed),
|
|
100
|
+
median: roundOrNull(median(costed.map(total))),
|
|
101
|
+
medianMinutes: roundOrNull(median(costed.map((it) => minutes(it.activeMs))), 1),
|
|
102
|
+
},
|
|
103
|
+
closeKinds,
|
|
104
|
+
stallMs,
|
|
105
|
+
activeMs,
|
|
106
|
+
list: list.map((it) => ({
|
|
107
|
+
key: it.key,
|
|
108
|
+
title: it.title,
|
|
109
|
+
owner: it.owner ?? null,
|
|
110
|
+
project: it.project,
|
|
111
|
+
kind: it.kind,
|
|
112
|
+
start: it.start ?? null,
|
|
113
|
+
close: it.close ?? null,
|
|
114
|
+
minutes: minutes(it.activeMs),
|
|
115
|
+
main: round(it.mainCost),
|
|
116
|
+
child: round(it.childCost),
|
|
117
|
+
children: it.children.length,
|
|
118
|
+
closeKind: it.closeKind,
|
|
119
|
+
thread: it.thread ?? null,
|
|
120
|
+
lines: it.lines ?? null,
|
|
121
|
+
stalls: Object.fromEntries(Object.entries(it.stallMs).filter(([, v]) => v > 0).map(([k, v]) => [k, minutes(v)])),
|
|
122
|
+
})),
|
|
123
|
+
open: open
|
|
124
|
+
.filter((it) => it.status === "in_progress" && it.open)
|
|
125
|
+
.sort((a, b) => b.lastActivity.localeCompare(a.lastActivity))
|
|
126
|
+
.slice(0, OPEN_MAX)
|
|
127
|
+
.map((it) => ({
|
|
128
|
+
key: it.key,
|
|
129
|
+
title: it.title,
|
|
130
|
+
owner: it.owner ?? null,
|
|
131
|
+
project: it.project,
|
|
132
|
+
session: it.session.slice(0, 13),
|
|
133
|
+
start: it.start ?? null,
|
|
134
|
+
since: it.open.since,
|
|
135
|
+
kind: it.open.kind,
|
|
136
|
+
on: it.open.on ?? null,
|
|
137
|
+
/** Minutes from the start of the wait to when the items were built (the extract). */
|
|
138
|
+
waitMinutes: minutes(Math.max(0, Date.parse(file.built) - Date.parse(it.open.since))),
|
|
139
|
+
childCost: round(it.childCost),
|
|
140
|
+
mainCost: round(it.mainCost),
|
|
141
|
+
})),
|
|
142
|
+
compare: compare(done.filter((it) => it.activeMs > 0)),
|
|
143
|
+
minItems: MIN_ITEMS,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const usd = (v) => (v === null ? "n/a" : `$${v.toFixed(2)}`);
|
|
2
|
+
const mins = (m) => (m < 90 ? `${Math.round(m)}m` : m < 2880 ? `${(m / 60).toFixed(1)}h` : `${(m / 1440).toFixed(1)}d`);
|
|
3
|
+
/** A title for agent output: quoted, inner quotes swapped, at most 50 characters. */
|
|
4
|
+
const quote = (title) => `"${Array.from(title.replace(/"/g, "'")).slice(0, 50).join("")}"`;
|
|
5
|
+
function verdict(c, v, lines = false) {
|
|
6
|
+
const n = (value) => {
|
|
7
|
+
const g = c.groups.find((x) => x.value === value);
|
|
8
|
+
return (lines ? g?.nLines : g?.n) ?? 0;
|
|
9
|
+
};
|
|
10
|
+
if (v.kind === "single")
|
|
11
|
+
return "one group only";
|
|
12
|
+
if (v.kind === "few")
|
|
13
|
+
return `too few items to tell (${n(v.a)}/${n(v.b)}, need 5 each)`;
|
|
14
|
+
if (v.kind === "same")
|
|
15
|
+
return "no clear difference (<20%)";
|
|
16
|
+
return `${v.a} ${Math.round((v.by ?? 0) * 100)}% less than ${v.b} (n ${n(v.a)}/${n(v.b)})`;
|
|
17
|
+
}
|
|
18
|
+
export function itemsView(w) {
|
|
19
|
+
if (!w)
|
|
20
|
+
return ["no work items yet: the user can run /evals extract"];
|
|
21
|
+
const kinds = Object.entries(w.closeKinds).filter(([, n]) => n).map(([k, n]) => `${k} ${n}`).join(", ");
|
|
22
|
+
const stalls = Object.entries(w.stallMs).filter(([, v]) => v).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${mins(v / 60_000)}`).join(", ");
|
|
23
|
+
const out = [
|
|
24
|
+
"item = one todo task, in_progress to completed/deleted (main sessions)",
|
|
25
|
+
`finished ${w.completed} (handed to subagents ${w.delegated}), in progress ${w.inProgress}, not started ${w.pending}, deleted ${w.deleted}`,
|
|
26
|
+
`finished cost ${usd(w.cost.main + w.cost.child)} = subagents ${usd(w.cost.child)} exact + main ${usd(w.cost.main)} estimated (even split among items open at once; ${usd(w.cost.unattributed)} outside any item)`,
|
|
27
|
+
`median item ${usd(w.cost.median)}, ${w.cost.medianMinutes ?? "n/a"} min in progress`,
|
|
28
|
+
`closed by: ${kinds || "none"}`,
|
|
29
|
+
`stall time in finished items, by what woke the main: ${stalls || "none"}`,
|
|
30
|
+
"cheaper? same kind only, per item (per 100 changed lines):",
|
|
31
|
+
];
|
|
32
|
+
for (const c of w.compare)
|
|
33
|
+
out.push(` ${c.kind} by ${c.dimension}: ${verdict(c, c.verdict)} (${verdict(c, c.verdictLines, true)})`);
|
|
34
|
+
if (w.open.length)
|
|
35
|
+
out.push("open, stopped where / waiting on / how long:");
|
|
36
|
+
for (const o of w.open.slice(0, 4))
|
|
37
|
+
out.push(`- ${quote(o.title || o.key)} ${o.kind}${o.on ? ` on ${o.on}` : ""}, ${mins(o.waitMinutes)}`);
|
|
38
|
+
const costly = [...w.list].sort((a, b) => b.main + b.child - (a.main + a.child)).slice(0, 3);
|
|
39
|
+
if (costly.length)
|
|
40
|
+
out.push("costliest finished:");
|
|
41
|
+
for (const r of costly)
|
|
42
|
+
out.push(`- ${quote(r.title || r.key)} ${usd(r.main + r.child)} (main ${usd(r.main)} + sub ${usd(r.child)}), ${mins(r.minutes)}, ${r.closeKind}`);
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
/** One findings line when something stands out: a like-with-like difference with enough items, or a long wait on others. */
|
|
46
|
+
export function itemsFinding(w) {
|
|
47
|
+
if (!w)
|
|
48
|
+
return undefined;
|
|
49
|
+
// Model first: a role split mixes kinds of work (planning vs building), and versions overlap other changes.
|
|
50
|
+
const order = ["model", "anchorloop", "role"];
|
|
51
|
+
const cheaper = w.compare.filter((c) => c.verdict.kind === "cheaper").sort((a, b) => (a.kind === b.kind ? 0 : a.kind === "delegated" ? -1 : 1) || order.indexOf(a.dimension) - order.indexOf(b.dimension))[0];
|
|
52
|
+
const waits = w.open.filter((o) => o.kind !== "human" && o.kind !== "working" && o.waitMinutes >= 60);
|
|
53
|
+
const parts = [];
|
|
54
|
+
if (cheaper)
|
|
55
|
+
parts.push(`${cheaper.kind} items by ${cheaper.dimension}: ${verdict(cheaper, cheaper.verdict)}`);
|
|
56
|
+
if (waits.length)
|
|
57
|
+
parts.push(`${waits.length} open item(s) waiting over 1h, longest ${mins(Math.max(...waits.map((o) => o.waitMinutes)))} on ${waits.sort((a, b) => b.waitMinutes - a.waitMinutes)[0].on ?? waits[0].kind}`);
|
|
58
|
+
return parts.length ? `Work items: ${parts.join("; ")} → items` : undefined;
|
|
59
|
+
}
|