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,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
|
+
}
|
package/dist/work/sb.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only views of pi-straw-boss state under `<agent dir>/straw-boss`: review threads, car records, and the
|
|
3
|
+
* append-only event ledger. Only ids, names, tags and times are taken; post text is never read past its tag.
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { safeName } from "../schema.js";
|
|
8
|
+
const obj = (v) => (v && typeof v === "object" ? v : {});
|
|
9
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
10
|
+
const iso = (ms) => (typeof ms === "number" && Number.isFinite(ms) ? new Date(ms).toISOString() : undefined);
|
|
11
|
+
function readJson(file) {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function readLines(file) {
|
|
20
|
+
try {
|
|
21
|
+
return readFileSync(file, "utf8")
|
|
22
|
+
.split("\n")
|
|
23
|
+
.flatMap((line) => {
|
|
24
|
+
if (!line)
|
|
25
|
+
return [];
|
|
26
|
+
try {
|
|
27
|
+
return [obj(JSON.parse(line))];
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const list = (dir) => {
|
|
39
|
+
try {
|
|
40
|
+
return readdirSync(dir);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/** Threads of the sessions whose first 8 characters are in `owners`. */
|
|
47
|
+
export function readThreads(sbDir, owners) {
|
|
48
|
+
const out = new Map();
|
|
49
|
+
const root = join(sbDir, "threads");
|
|
50
|
+
for (const owner8 of list(root)) {
|
|
51
|
+
if (!owners.has(owner8))
|
|
52
|
+
continue;
|
|
53
|
+
for (const name of list(join(root, owner8))) {
|
|
54
|
+
const m = name.match(/^(T\d+)\.json$/);
|
|
55
|
+
if (!m)
|
|
56
|
+
continue;
|
|
57
|
+
const meta = obj(readJson(join(root, owner8, name)));
|
|
58
|
+
const owner = str(meta.owner);
|
|
59
|
+
if (!owner)
|
|
60
|
+
continue;
|
|
61
|
+
const posts = readLines(join(root, owner8, `${m[1]}.jsonl`));
|
|
62
|
+
const last = posts.at(-1);
|
|
63
|
+
const lastTag = str(last?.tag);
|
|
64
|
+
const firstReview = posts.find((p) => p.tag === "review" && p.from === "worker");
|
|
65
|
+
const closedAs = str(meta.closedAs) ?? (lastTag === "done" || lastTag === "blocked" ? lastTag : undefined);
|
|
66
|
+
const thread = {
|
|
67
|
+
id: m[1],
|
|
68
|
+
owner: safeName(owner),
|
|
69
|
+
worker: str(meta.worker) ? safeName(meta.worker) : undefined,
|
|
70
|
+
reviewer: str(meta.reviewer) ? safeName(meta.reviewer) : undefined,
|
|
71
|
+
created: iso(meta.created),
|
|
72
|
+
item: str(meta.item) ? safeName(meta.item) : undefined,
|
|
73
|
+
closed: iso(meta.closed) ?? (closedAs && last ? iso(last.at) : undefined),
|
|
74
|
+
closedAs: iso(meta.closed) ? (closedAs ?? "done") : closedAs,
|
|
75
|
+
firstReview: firstReview ? iso(firstReview.at) : undefined,
|
|
76
|
+
rounds: posts.filter((p) => p.tag === "review").length,
|
|
77
|
+
};
|
|
78
|
+
const bucket = out.get(thread.owner) ?? [];
|
|
79
|
+
bucket.push(thread);
|
|
80
|
+
out.set(thread.owner, bucket);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/** Car records by coordinator session, with their ticket ids and the time they landed. */
|
|
86
|
+
export function readCars(sbDir) {
|
|
87
|
+
const out = new Map();
|
|
88
|
+
const root = join(sbDir, "trainboard");
|
|
89
|
+
for (const project of list(root)) {
|
|
90
|
+
const dir = join(root, project, "cars");
|
|
91
|
+
for (const name of list(dir)) {
|
|
92
|
+
if (!name.endsWith(".json") || name.endsWith(".notice.json"))
|
|
93
|
+
continue;
|
|
94
|
+
const rec = obj(readJson(join(dir, name)));
|
|
95
|
+
const states = Array.isArray(rec.states) ? rec.states.map(obj) : [];
|
|
96
|
+
const coordinator = str(rec.coordinator) ?? str(obj(obj(states[0]).by).session);
|
|
97
|
+
if (!coordinator)
|
|
98
|
+
continue;
|
|
99
|
+
const landed = states.findLast((s) => s.state === "landed");
|
|
100
|
+
const tickets = Array.isArray(obj(rec.car).tickets) ? obj(rec.car).tickets.filter((t) => typeof t === "string").map(safeName) : [];
|
|
101
|
+
const car = { coordinator: safeName(coordinator), tickets, landed: str(landed?.at) };
|
|
102
|
+
const bucket = out.get(car.coordinator) ?? [];
|
|
103
|
+
bucket.push(car);
|
|
104
|
+
out.set(car.coordinator, bucket);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
/** Ledger events (sb 0.94+) by session, oldest first; an absent ledger is an empty map. */
|
|
110
|
+
export function readLedger(sbDir) {
|
|
111
|
+
const out = new Map();
|
|
112
|
+
const dir = join(sbDir, "ledger");
|
|
113
|
+
if (!existsSync(dir))
|
|
114
|
+
return out;
|
|
115
|
+
for (const name of list(dir).filter((n) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n)).sort()) {
|
|
116
|
+
for (const row of readLines(join(dir, name))) {
|
|
117
|
+
const at = iso(row.at);
|
|
118
|
+
const session = str(row.session);
|
|
119
|
+
if (!at || !session || row.v !== 1)
|
|
120
|
+
continue;
|
|
121
|
+
const opt = (v) => (str(v) ? safeName(v) : undefined);
|
|
122
|
+
const event = { at, kind: safeName(str(row.kind) ?? "unknown"), id: opt(row.id), session: safeName(session), why: opt(row.why), item: opt(row.item), by: opt(row.by) };
|
|
123
|
+
const bucket = out.get(event.session) ?? [];
|
|
124
|
+
bucket.push(event);
|
|
125
|
+
out.set(event.session, bucket);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
for (const events of out.values())
|
|
129
|
+
events.sort((a, b) => a.at.localeCompare(b.at));
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Work items of one session, rebuilt from its `todo/v1` snapshots (pi-todo-ledger), plus the facts the join needs:
|
|
3
|
+
* the main's cost over time, its idle gaps and what woke it, and the subagents, review pairs and wraps it started.
|
|
4
|
+
*
|
|
5
|
+
* An item is one todo task from its `in_progress` transition to `completed`, `deleted` or the end of the session.
|
|
6
|
+
* Snapshots are diffed along the entry tree, so a `/tree` branch or a `clear` never merges two tasks that share an id:
|
|
7
|
+
* the branch that ends with the last snapshot in the file wins, and each task id gets a new item whenever it reappears.
|
|
8
|
+
* Only the subject leaves this module as text, cut to 80 characters (`titleOf`); every other string is a name.
|
|
9
|
+
*/
|
|
10
|
+
import { safeName, titleOf } from "../schema.js";
|
|
11
|
+
export { titleOf };
|
|
12
|
+
const obj = (v) => (v && typeof v === "object" ? v : {});
|
|
13
|
+
const str = (v) => (typeof v === "string" ? v : undefined);
|
|
14
|
+
/** A main idle this long or longer is a stall. */
|
|
15
|
+
export const STALL_MS = 120_000;
|
|
16
|
+
const CHILD_REF = /^child:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
17
|
+
const STATUSES = new Set(["pending", "in_progress", "completed", "deleted"]);
|
|
18
|
+
function liteOf(raw) {
|
|
19
|
+
const t = obj(raw);
|
|
20
|
+
if (typeof t.id !== "number" || !Number.isInteger(t.id))
|
|
21
|
+
return undefined;
|
|
22
|
+
const status = (STATUSES.has(String(t.status)) ? t.status : "pending");
|
|
23
|
+
const evidence = Array.isArray(t.evidence) ? t.evidence.map(obj) : [];
|
|
24
|
+
const shas = [];
|
|
25
|
+
for (const e of evidence) {
|
|
26
|
+
const sha = str(e.sha);
|
|
27
|
+
if (sha && /^[0-9a-f]{6,40}$/i.test(sha) && !shas.includes(sha))
|
|
28
|
+
shas.push(sha);
|
|
29
|
+
}
|
|
30
|
+
// Only a `child:<subagent id>` ref is kept: it joins the child to the item. A tool call id needs no storing.
|
|
31
|
+
const refs = evidence.map((e) => str(e.ref)).filter((r) => !!r && CHILD_REF.test(r));
|
|
32
|
+
// A uid or origin that is not name-shaped would become the shared key "redacted": drop it instead.
|
|
33
|
+
const named = (v) => (typeof v === "string" && v && safeName(v) === v ? v : undefined);
|
|
34
|
+
const uid = named(t.uid);
|
|
35
|
+
const origin = named(obj(t.origin).session);
|
|
36
|
+
return {
|
|
37
|
+
id: t.id,
|
|
38
|
+
status,
|
|
39
|
+
title: titleOf(t.subject),
|
|
40
|
+
owner: str(t.owner) ? safeName(t.owner) : undefined,
|
|
41
|
+
uid,
|
|
42
|
+
origin,
|
|
43
|
+
evidence: evidence.length,
|
|
44
|
+
shas,
|
|
45
|
+
refs,
|
|
46
|
+
blockedBy: Array.isArray(t.blockedBy) ? t.blockedBy.length : 0,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** The kind of stall a waking entry ends, or undefined when the entry does not start a turn. */
|
|
50
|
+
export function wakeOf(entry) {
|
|
51
|
+
const type = entry.type;
|
|
52
|
+
if (type === "thinking_level_change" || type === "model_change")
|
|
53
|
+
return { kind: "human" };
|
|
54
|
+
if (type === "message")
|
|
55
|
+
return obj(entry.message).role === "user" ? { kind: "human" } : undefined;
|
|
56
|
+
if (type !== "custom_message")
|
|
57
|
+
return undefined;
|
|
58
|
+
const details = obj(entry.details);
|
|
59
|
+
switch (entry.customType) {
|
|
60
|
+
case "better-show":
|
|
61
|
+
case "robot-hand-follow-up":
|
|
62
|
+
case "robot-hand-herdr":
|
|
63
|
+
return { kind: "human" };
|
|
64
|
+
case "intercom_message": {
|
|
65
|
+
const from = str(obj(details.from).id);
|
|
66
|
+
return { kind: "peer", on: from ? peerName(from) : undefined };
|
|
67
|
+
}
|
|
68
|
+
case "straw-tower":
|
|
69
|
+
return details.kind === "intercom" ? { kind: "peer", on: peerName(str(obj(details.from).id) ?? "") || undefined } : { kind: "timer" };
|
|
70
|
+
case "straw-link":
|
|
71
|
+
return { kind: "device" };
|
|
72
|
+
case "subagent_result":
|
|
73
|
+
case "subagent_ping":
|
|
74
|
+
case "subagent_status":
|
|
75
|
+
case "subagent_stop":
|
|
76
|
+
case "subagent-accept-check":
|
|
77
|
+
case "straw-boss-orphan-result":
|
|
78
|
+
case "straw-boss-child-revived": {
|
|
79
|
+
const name = str(details.name);
|
|
80
|
+
return { kind: "child", on: name ? safeName(name) : undefined };
|
|
81
|
+
}
|
|
82
|
+
case "pi-loop-monitor": {
|
|
83
|
+
if (details.deliveryGroup === "monitor-started")
|
|
84
|
+
return undefined;
|
|
85
|
+
const source = str(obj(details.trigger).source) ?? "";
|
|
86
|
+
return details.deliveryGroup === "monitor-terminal" || source.startsWith("monitor:") ? { kind: "ci" } : { kind: "timer" };
|
|
87
|
+
}
|
|
88
|
+
case "straw-auto":
|
|
89
|
+
case "straw-boss-wrap":
|
|
90
|
+
case "straw-boss-watch":
|
|
91
|
+
return { kind: "timer" };
|
|
92
|
+
default:
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const UUIDISH = /^[0-9a-f]{8}-[0-9a-f]{4}-/i;
|
|
97
|
+
/** A peer session by its first 13 characters: UUIDv7 sessions started within the same minute share the first 8. */
|
|
98
|
+
const peerName = (id) => (UUIDISH.test(id) ? id.slice(0, 13) : safeName(id));
|
|
99
|
+
export class WorkTracker {
|
|
100
|
+
snaps = [];
|
|
101
|
+
/** entry id → index of the newest todo snapshot on its path (or -1). */
|
|
102
|
+
todoAt = new Map();
|
|
103
|
+
costs = [];
|
|
104
|
+
gaps = [];
|
|
105
|
+
idleFrom;
|
|
106
|
+
launches = [];
|
|
107
|
+
childEvents = [];
|
|
108
|
+
pairs = [];
|
|
109
|
+
wraps = [];
|
|
110
|
+
last = "";
|
|
111
|
+
/** Every entry, in file order, before it is otherwise handled. */
|
|
112
|
+
entry(entry, ts) {
|
|
113
|
+
if (ts && ts > this.last)
|
|
114
|
+
this.last = ts;
|
|
115
|
+
const id = str(entry.id);
|
|
116
|
+
const parent = str(entry.parentId);
|
|
117
|
+
const inherited = parent !== undefined ? (this.todoAt.get(parent) ?? -1) : this.snaps.length - 1;
|
|
118
|
+
if (entry.type === "custom" && entry.customType === "todo/v1") {
|
|
119
|
+
const data = obj(entry.data);
|
|
120
|
+
if (Array.isArray(data.tasks)) {
|
|
121
|
+
const tasks = data.tasks.map(liteOf).filter((t) => !!t);
|
|
122
|
+
this.snaps.push({ entry: id ?? String(this.snaps.length), ts, pred: inherited, tasks });
|
|
123
|
+
if (id)
|
|
124
|
+
this.todoAt.set(id, this.snaps.length - 1);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (id)
|
|
129
|
+
this.todoAt.set(id, inherited);
|
|
130
|
+
if (this.idleFrom && ts) {
|
|
131
|
+
const wake = wakeOf(entry);
|
|
132
|
+
if (wake) {
|
|
133
|
+
this.gap(this.idleFrom, ts, wake.kind, wake.on, "idle");
|
|
134
|
+
this.idleFrom = undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
assistant(ts, cost, stopReason) {
|
|
139
|
+
if (cost)
|
|
140
|
+
this.costs.push([Date.parse(ts), cost]);
|
|
141
|
+
// A turn that started from an entry we do not classify: its idle time is not a stall of a known kind.
|
|
142
|
+
this.idleFrom = typeof stopReason === "string" && stopReason !== "toolUse" ? ts : undefined;
|
|
143
|
+
}
|
|
144
|
+
/** A question tool held the main for `start`..`end`. */
|
|
145
|
+
wait(start, end, kind) {
|
|
146
|
+
this.gap(start, end, kind, undefined, "ask");
|
|
147
|
+
}
|
|
148
|
+
launch(l) {
|
|
149
|
+
this.launches.push(l);
|
|
150
|
+
}
|
|
151
|
+
child(ts, name, what) {
|
|
152
|
+
this.childEvents.push([ts, safeName(name), what]);
|
|
153
|
+
}
|
|
154
|
+
pair(p) {
|
|
155
|
+
this.pairs.push(p);
|
|
156
|
+
}
|
|
157
|
+
wrap(at, wrapped) {
|
|
158
|
+
this.wraps.push({ at, wrapped });
|
|
159
|
+
}
|
|
160
|
+
gap(start, end, kind, on, via) {
|
|
161
|
+
if (Date.parse(end) - Date.parse(start) >= STALL_MS)
|
|
162
|
+
this.gaps.push({ start, end, kind, on, via });
|
|
163
|
+
}
|
|
164
|
+
finish(session, nested) {
|
|
165
|
+
const items = this.items(session, nested);
|
|
166
|
+
if (!items.length && !this.launches.length && !this.pairs.length)
|
|
167
|
+
return undefined;
|
|
168
|
+
const end = Date.parse(this.last);
|
|
169
|
+
const spans = items.map((it) => it.active.map(([a, b]) => [Date.parse(a), b ? Date.parse(b) : end + 1]));
|
|
170
|
+
let unattributed = 0;
|
|
171
|
+
for (const [t, cost] of this.costs) {
|
|
172
|
+
const on = spans.flatMap((s, i) => (s.some(([a, b]) => t >= a && t < b) ? [i] : []));
|
|
173
|
+
if (!on.length)
|
|
174
|
+
unattributed += cost;
|
|
175
|
+
for (const i of on)
|
|
176
|
+
items[i].mainCost += cost / on.length;
|
|
177
|
+
}
|
|
178
|
+
this.gaps.forEach((g, gi) => {
|
|
179
|
+
const a = Date.parse(g.start);
|
|
180
|
+
const b = Date.parse(g.end);
|
|
181
|
+
spans.forEach((s, i) => {
|
|
182
|
+
const ms = s.reduce((sum, [x, y]) => sum + Math.max(0, Math.min(b, y) - Math.max(a, x)), 0);
|
|
183
|
+
if (ms > 0)
|
|
184
|
+
items[i].stalls.push([gi, ms]);
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
for (const it of items)
|
|
188
|
+
it.mainCost = Math.round(it.mainCost * 1e6) / 1e6;
|
|
189
|
+
return {
|
|
190
|
+
items,
|
|
191
|
+
gaps: this.gaps,
|
|
192
|
+
launches: this.launches,
|
|
193
|
+
childEvents: this.childEvents,
|
|
194
|
+
pairs: this.pairs,
|
|
195
|
+
wraps: this.wraps,
|
|
196
|
+
idleSince: this.idleFrom,
|
|
197
|
+
lastActivity: this.last,
|
|
198
|
+
unattributed: Math.round(unattributed * 1e6) / 1e6,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/** Items along each branch's chain of snapshots, the branch holding the file's last snapshot first. */
|
|
202
|
+
items(session, nested) {
|
|
203
|
+
const n = this.snaps.length;
|
|
204
|
+
if (!n)
|
|
205
|
+
return [];
|
|
206
|
+
const hasChild = new Array(n).fill(false);
|
|
207
|
+
for (const s of this.snaps)
|
|
208
|
+
if (s.pred >= 0)
|
|
209
|
+
hasChild[s.pred] = true;
|
|
210
|
+
const leaves = [...Array(n).keys()].filter((i) => !hasChild[i]).sort((a, b) => b - a);
|
|
211
|
+
const main = new Set();
|
|
212
|
+
for (let i = leaves[0]; i >= 0; i = this.snaps[i].pred)
|
|
213
|
+
main.add(i);
|
|
214
|
+
const done = new Map();
|
|
215
|
+
const order = [];
|
|
216
|
+
const reuse = new Map();
|
|
217
|
+
for (const leaf of leaves) {
|
|
218
|
+
const chain = [];
|
|
219
|
+
for (let i = leaf; i >= 0; i = this.snaps[i].pred)
|
|
220
|
+
chain.unshift(i);
|
|
221
|
+
const live = new Map();
|
|
222
|
+
const leafTs = this.snaps[leaf].ts;
|
|
223
|
+
let prevSize = -1;
|
|
224
|
+
for (const si of chain) {
|
|
225
|
+
const snap = this.snaps[si];
|
|
226
|
+
const seen = new Set();
|
|
227
|
+
const fresh = prevSize <= 0;
|
|
228
|
+
prevSize = snap.tasks.length;
|
|
229
|
+
for (const task of snap.tasks) {
|
|
230
|
+
seen.add(task.id);
|
|
231
|
+
let cur = live.get(task.id);
|
|
232
|
+
if (!cur) {
|
|
233
|
+
const identity = `${si}:${task.id}`;
|
|
234
|
+
const known = done.get(identity);
|
|
235
|
+
cur = { identity, item: known ? undefined : this.newItem(session, nested, task, snap, si, main, reuse) };
|
|
236
|
+
if (cur.item && (task.status === "completed" || task.status === "deleted") && (fresh || task.origin))
|
|
237
|
+
cur.item.carried = true;
|
|
238
|
+
live.set(task.id, cur);
|
|
239
|
+
if (cur.item) {
|
|
240
|
+
done.set(identity, cur.item);
|
|
241
|
+
order.push(cur.item);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (cur.item)
|
|
245
|
+
this.step(cur.item, task, snap.ts);
|
|
246
|
+
}
|
|
247
|
+
for (const [id, cur] of live) {
|
|
248
|
+
if (seen.has(id))
|
|
249
|
+
continue;
|
|
250
|
+
// Removed from the list (a clear, or a handover that drops it) while not finished: it was dropped here.
|
|
251
|
+
if (cur.item && (cur.item.status === "pending" || cur.item.status === "in_progress"))
|
|
252
|
+
this.step(cur.item, { ...lastLite(cur.item), status: "deleted" }, snap.ts);
|
|
253
|
+
live.delete(id);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const sideEnd = main.has(leaf) ? null : leafTs;
|
|
257
|
+
for (const cur of live.values())
|
|
258
|
+
if (cur.item && sideEnd)
|
|
259
|
+
for (const span of cur.item.active)
|
|
260
|
+
if (span[1] === null)
|
|
261
|
+
span[1] = sideEnd;
|
|
262
|
+
}
|
|
263
|
+
return order;
|
|
264
|
+
}
|
|
265
|
+
newItem(session, nested, task, snap, si, main, reuse) {
|
|
266
|
+
let key;
|
|
267
|
+
if (task.uid)
|
|
268
|
+
key = task.uid;
|
|
269
|
+
else if (task.origin)
|
|
270
|
+
key = `${task.origin}#${task.id}`;
|
|
271
|
+
else if (main.has(si)) {
|
|
272
|
+
const count = (reuse.get(task.id) ?? 0) + 1;
|
|
273
|
+
reuse.set(task.id, count);
|
|
274
|
+
key = count === 1 ? `${session}#${task.id}` : `${session}#${task.id}.${count}`;
|
|
275
|
+
}
|
|
276
|
+
else
|
|
277
|
+
key = `${session}#${task.id}@${safeName(snap.entry).slice(0, 8)}`;
|
|
278
|
+
return {
|
|
279
|
+
key,
|
|
280
|
+
id: task.id,
|
|
281
|
+
title: task.title,
|
|
282
|
+
owner: task.owner,
|
|
283
|
+
uid: task.uid,
|
|
284
|
+
origin: task.origin,
|
|
285
|
+
level: nested ? "nested" : "top",
|
|
286
|
+
status: "pending",
|
|
287
|
+
created: snap.ts,
|
|
288
|
+
active: [],
|
|
289
|
+
evidence: 0,
|
|
290
|
+
shas: [],
|
|
291
|
+
refs: [],
|
|
292
|
+
blockedBy: 0,
|
|
293
|
+
mainCost: 0,
|
|
294
|
+
stalls: [],
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
step(item, task, ts) {
|
|
298
|
+
const was = item.status;
|
|
299
|
+
if (task.uid && item.uid !== task.uid)
|
|
300
|
+
item.key = item.uid = task.uid;
|
|
301
|
+
Object.assign(item, { title: task.title || item.title, owner: task.owner ?? item.owner, evidence: task.evidence, shas: task.shas, refs: task.refs, blockedBy: task.blockedBy });
|
|
302
|
+
if (task.status === was)
|
|
303
|
+
return;
|
|
304
|
+
item.status = task.status;
|
|
305
|
+
if (task.status === "in_progress" && was !== "in_progress") {
|
|
306
|
+
item.start ??= ts;
|
|
307
|
+
item.close = undefined;
|
|
308
|
+
item.active.push([ts, null]);
|
|
309
|
+
}
|
|
310
|
+
else if (task.status !== "in_progress" && was === "in_progress") {
|
|
311
|
+
const open = item.active.at(-1);
|
|
312
|
+
if (open && open[1] === null)
|
|
313
|
+
open[1] = ts;
|
|
314
|
+
}
|
|
315
|
+
if (task.status === "completed" || task.status === "deleted")
|
|
316
|
+
item.close = ts;
|
|
317
|
+
else if (task.status === "pending")
|
|
318
|
+
item.close = undefined;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function lastLite(item) {
|
|
322
|
+
return { id: item.id, status: item.status, title: item.title, owner: item.owner, uid: item.uid, origin: item.origin, evidence: item.evidence, shas: item.shas, refs: item.refs, blockedBy: item.blockedBy };
|
|
323
|
+
}
|