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,53 @@
1
+ /** The `items` view of `evals_query` and its line in `findings`: numbers, names, and titles in double quotes. */
2
+ import type { Comparison, Verdict, WorkModel } from "./model.ts";
3
+
4
+ const usd = (v: number | null) => (v === null ? "n/a" : `$${v.toFixed(2)}`);
5
+ const mins = (m: number) => (m < 90 ? `${Math.round(m)}m` : m < 2880 ? `${(m / 60).toFixed(1)}h` : `${(m / 1440).toFixed(1)}d`);
6
+ /** A title for agent output: quoted, inner quotes swapped, at most 50 characters. */
7
+ const quote = (title: string) => `"${Array.from(title.replace(/"/g, "'")).slice(0, 50).join("")}"`;
8
+
9
+ function verdict(c: Comparison, v: Verdict, lines = false): string {
10
+ const n = (value?: string) => {
11
+ const g = c.groups.find((x) => x.value === value);
12
+ return (lines ? g?.nLines : g?.n) ?? 0;
13
+ };
14
+ if (v.kind === "single") return "one group only";
15
+ if (v.kind === "few") return `too few items to tell (${n(v.a)}/${n(v.b)}, need 5 each)`;
16
+ if (v.kind === "same") return "no clear difference (<20%)";
17
+ return `${v.a} ${Math.round((v.by ?? 0) * 100)}% less than ${v.b} (n ${n(v.a)}/${n(v.b)})`;
18
+ }
19
+
20
+ export function itemsView(w: WorkModel | null): string[] {
21
+ if (!w) return ["no work items yet: the user can run /evals extract"];
22
+ const kinds = Object.entries(w.closeKinds).filter(([, n]) => n).map(([k, n]) => `${k} ${n}`).join(", ");
23
+ 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(", ");
24
+ const out = [
25
+ "item = one todo task, in_progress to completed/deleted (main sessions)",
26
+ `finished ${w.completed} (handed to subagents ${w.delegated}), in progress ${w.inProgress}, not started ${w.pending}, deleted ${w.deleted}`,
27
+ `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)`,
28
+ `median item ${usd(w.cost.median)}, ${w.cost.medianMinutes ?? "n/a"} min in progress`,
29
+ `closed by: ${kinds || "none"}`,
30
+ `stall time in finished items, by what woke the main: ${stalls || "none"}`,
31
+ "cheaper? same kind only, per item (per 100 changed lines):",
32
+ ];
33
+ for (const c of w.compare) out.push(` ${c.kind} by ${c.dimension}: ${verdict(c, c.verdict)} (${verdict(c, c.verdictLines, true)})`);
34
+ if (w.open.length) out.push("open, stopped where / waiting on / how long:");
35
+ for (const o of w.open.slice(0, 4)) out.push(`- ${quote(o.title || o.key)} ${o.kind}${o.on ? ` on ${o.on}` : ""}, ${mins(o.waitMinutes)}`);
36
+ const costly = [...w.list].sort((a, b) => b.main + b.child - (a.main + a.child)).slice(0, 3);
37
+ if (costly.length) out.push("costliest finished:");
38
+ for (const r of costly) 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}`);
39
+ return out;
40
+ }
41
+
42
+ /** One findings line when something stands out: a like-with-like difference with enough items, or a long wait on others. */
43
+ export function itemsFinding(w: WorkModel | null): string | undefined {
44
+ if (!w) return undefined;
45
+ // Model first: a role split mixes kinds of work (planning vs building), and versions overlap other changes.
46
+ const order = ["model", "anchorloop", "role"];
47
+ 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];
48
+ const waits = w.open.filter((o) => o.kind !== "human" && o.kind !== "working" && o.waitMinutes >= 60);
49
+ const parts: string[] = [];
50
+ if (cheaper) parts.push(`${cheaper.kind} items by ${cheaper.dimension}: ${verdict(cheaper, cheaper.verdict)}`);
51
+ if (waits.length) 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}`);
52
+ return parts.length ? `Work items: ${parts.join("; ")} → items` : undefined;
53
+ }
package/src/work/sb.ts ADDED
@@ -0,0 +1,158 @@
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.ts";
8
+
9
+ type Obj = Record<string, unknown>;
10
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
11
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
12
+ const iso = (ms: unknown) => (typeof ms === "number" && Number.isFinite(ms) ? new Date(ms).toISOString() : undefined);
13
+
14
+ export interface Thread {
15
+ id: string;
16
+ owner: string;
17
+ worker?: string;
18
+ reviewer?: string;
19
+ created?: string;
20
+ /** Producer field (sb 0.94+): the todo uid or `<session8>#<id>` the pair works on. */
21
+ item?: string;
22
+ /** When the thread closed: the producer's `closed`, else the last post when it is `done` or `blocked`. */
23
+ closed?: string;
24
+ closedAs?: "done" | "blocked" | "abandoned";
25
+ /** First `review` post from the worker. */
26
+ firstReview?: string;
27
+ rounds: number;
28
+ }
29
+
30
+ export interface Car {
31
+ coordinator?: string;
32
+ tickets: string[];
33
+ landed?: string;
34
+ }
35
+
36
+ export interface LedgerEvent {
37
+ at: string;
38
+ kind: string;
39
+ id?: string;
40
+ session?: string;
41
+ why?: string;
42
+ item?: string;
43
+ by?: string;
44
+ }
45
+
46
+ function readJson(file: string): unknown {
47
+ try {
48
+ return JSON.parse(readFileSync(file, "utf8"));
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ function readLines(file: string): Obj[] {
55
+ try {
56
+ return readFileSync(file, "utf8")
57
+ .split("\n")
58
+ .flatMap((line) => {
59
+ if (!line) return [];
60
+ try {
61
+ return [obj(JSON.parse(line))];
62
+ } catch {
63
+ return [];
64
+ }
65
+ });
66
+ } catch {
67
+ return [];
68
+ }
69
+ }
70
+
71
+ const list = (dir: string) => {
72
+ try {
73
+ return readdirSync(dir);
74
+ } catch {
75
+ return [];
76
+ }
77
+ };
78
+
79
+ /** Threads of the sessions whose first 8 characters are in `owners`. */
80
+ export function readThreads(sbDir: string, owners: Set<string>): Map<string, Thread[]> {
81
+ const out = new Map<string, Thread[]>();
82
+ const root = join(sbDir, "threads");
83
+ for (const owner8 of list(root)) {
84
+ if (!owners.has(owner8)) continue;
85
+ for (const name of list(join(root, owner8))) {
86
+ const m = name.match(/^(T\d+)\.json$/);
87
+ if (!m) continue;
88
+ const meta = obj(readJson(join(root, owner8, name)));
89
+ const owner = str(meta.owner);
90
+ if (!owner) continue;
91
+ const posts = readLines(join(root, owner8, `${m[1]}.jsonl`));
92
+ const last = posts.at(-1);
93
+ const lastTag = str(last?.tag);
94
+ const firstReview = posts.find((p) => p.tag === "review" && p.from === "worker");
95
+ const closedAs = (str(meta.closedAs) as Thread["closedAs"]) ?? (lastTag === "done" || lastTag === "blocked" ? lastTag : undefined);
96
+ const thread: Thread = {
97
+ id: m[1],
98
+ owner: safeName(owner),
99
+ worker: str(meta.worker) ? safeName(meta.worker) : undefined,
100
+ reviewer: str(meta.reviewer) ? safeName(meta.reviewer) : undefined,
101
+ created: iso(meta.created),
102
+ item: str(meta.item) ? safeName(meta.item) : undefined,
103
+ closed: iso(meta.closed) ?? (closedAs && last ? iso(last.at) : undefined),
104
+ closedAs: iso(meta.closed) ? (closedAs ?? "done") : closedAs,
105
+ firstReview: firstReview ? iso(firstReview.at) : undefined,
106
+ rounds: posts.filter((p) => p.tag === "review").length,
107
+ };
108
+ const bucket = out.get(thread.owner) ?? [];
109
+ bucket.push(thread);
110
+ out.set(thread.owner, bucket);
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+
116
+ /** Car records by coordinator session, with their ticket ids and the time they landed. */
117
+ export function readCars(sbDir: string): Map<string, Car[]> {
118
+ const out = new Map<string, Car[]>();
119
+ const root = join(sbDir, "trainboard");
120
+ for (const project of list(root)) {
121
+ const dir = join(root, project, "cars");
122
+ for (const name of list(dir)) {
123
+ if (!name.endsWith(".json") || name.endsWith(".notice.json")) continue;
124
+ const rec = obj(readJson(join(dir, name)));
125
+ const states = Array.isArray(rec.states) ? rec.states.map(obj) : [];
126
+ const coordinator = str(rec.coordinator) ?? str(obj(obj(states[0]).by).session);
127
+ if (!coordinator) continue;
128
+ const landed = states.findLast((s) => s.state === "landed");
129
+ const tickets = Array.isArray(obj(rec.car).tickets) ? (obj(rec.car).tickets as unknown[]).filter((t): t is string => typeof t === "string").map(safeName) : [];
130
+ const car: Car = { coordinator: safeName(coordinator), tickets, landed: str(landed?.at) };
131
+ const bucket = out.get(car.coordinator!) ?? [];
132
+ bucket.push(car);
133
+ out.set(car.coordinator!, bucket);
134
+ }
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /** Ledger events (sb 0.94+) by session, oldest first; an absent ledger is an empty map. */
140
+ export function readLedger(sbDir: string): Map<string, LedgerEvent[]> {
141
+ const out = new Map<string, LedgerEvent[]>();
142
+ const dir = join(sbDir, "ledger");
143
+ if (!existsSync(dir)) return out;
144
+ for (const name of list(dir).filter((n) => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(n)).sort()) {
145
+ for (const row of readLines(join(dir, name))) {
146
+ const at = iso(row.at);
147
+ const session = str(row.session);
148
+ if (!at || !session || row.v !== 1) continue;
149
+ const opt = (v: unknown) => (str(v) ? safeName(v) : undefined);
150
+ const event: LedgerEvent = { 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) };
151
+ const bucket = out.get(event.session!) ?? [];
152
+ bucket.push(event);
153
+ out.set(event.session!, bucket);
154
+ }
155
+ }
156
+ for (const events of out.values()) events.sort((a, b) => a.at.localeCompare(b.at));
157
+ return out;
158
+ }
@@ -0,0 +1,397 @@
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.ts";
11
+
12
+ export { titleOf };
13
+
14
+ type Obj = Record<string, unknown>;
15
+ const obj = (v: unknown): Obj => (v && typeof v === "object" ? (v as Obj) : {});
16
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
17
+
18
+ /** A main idle this long or longer is a stall. */
19
+ export const STALL_MS = 120_000;
20
+
21
+ export type StallKind = "human" | "peer" | "child" | "timer" | "ci" | "device";
22
+ export type ItemStatus = "pending" | "in_progress" | "completed" | "deleted";
23
+
24
+ export interface Gap {
25
+ /** ISO start (the main's turn ended, or a blocking question was asked) and end (what woke it). */
26
+ start: string;
27
+ end: string;
28
+ kind: StallKind;
29
+ /** Who or what, when the waking entry names it: a subagent name, a peer's session (first 13 characters), or (from the sb ledger) `W12`, `L340`, `T5`. */
30
+ on?: string;
31
+ /** `ask` when the main sat inside a question tool, else `idle`. */
32
+ via: "idle" | "ask";
33
+ }
34
+
35
+ export interface ItemRaw {
36
+ key: string;
37
+ id: number;
38
+ title: string;
39
+ owner?: string;
40
+ uid?: string;
41
+ /** Session the task was imported from (todo `origin.session`). */
42
+ origin?: string;
43
+ /**
44
+ * Already completed or deleted when this session first saw it: in the branch's first snapshot (a list carried over
45
+ * from another tool or session), imported into an empty list, or with an `origin`. It was not closed here.
46
+ */
47
+ carried?: true;
48
+ /** `nested` when the session is itself a subagent: a sub-item of the parent's item, not counted on its own. */
49
+ level: "top" | "nested";
50
+ status: ItemStatus;
51
+ created: string;
52
+ start?: string;
53
+ close?: string;
54
+ /** Intervals in `in_progress`; an open end is null (still active when the session file ends). */
55
+ active: [string, string | null][];
56
+ evidence: number;
57
+ /** Distinct evidence commit shas, in order. */
58
+ shas: string[];
59
+ /** Evidence `ref` values of the form `child:<subagent id>`. */
60
+ refs: string[];
61
+ blockedBy: number;
62
+ /** Main cost inside the active window, split evenly among the items active at the same moment. */
63
+ mainCost: number;
64
+ /** Gap index → milliseconds of that gap inside this item's active window. */
65
+ stalls: [number, number][];
66
+ }
67
+
68
+ export interface Launch {
69
+ id: string;
70
+ name?: string;
71
+ role: string;
72
+ model: string;
73
+ item?: string;
74
+ at: string;
75
+ }
76
+
77
+ export interface SessionWork {
78
+ items: ItemRaw[];
79
+ gaps: Gap[];
80
+ launches: Launch[];
81
+ /** Subagent results and resumes by name: [ts, "result" | "resume"]. */
82
+ childEvents: [string, string, "result" | "resume"][];
83
+ pairs: { thread: string; worker?: string; reviewer?: string; item?: string; at: string }[];
84
+ wraps: { at: string; wrapped: boolean }[];
85
+ /** The main ended its last turn here and nothing woke it before the file ends. */
86
+ idleSince?: string;
87
+ lastActivity: string;
88
+ /** Main cost outside every item window. */
89
+ unattributed: number;
90
+ }
91
+
92
+ interface TaskLite {
93
+ id: number;
94
+ status: ItemStatus;
95
+ title: string;
96
+ owner?: string;
97
+ uid?: string;
98
+ origin?: string;
99
+ evidence: number;
100
+ shas: string[];
101
+ refs: string[];
102
+ blockedBy: number;
103
+ }
104
+
105
+ interface Snapshot {
106
+ entry: string;
107
+ ts: string;
108
+ pred: number;
109
+ tasks: TaskLite[];
110
+ }
111
+
112
+ const CHILD_REF = /^child:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
113
+ const STATUSES = new Set(["pending", "in_progress", "completed", "deleted"]);
114
+
115
+ function liteOf(raw: unknown): TaskLite | undefined {
116
+ const t = obj(raw);
117
+ if (typeof t.id !== "number" || !Number.isInteger(t.id)) return undefined;
118
+ const status = (STATUSES.has(String(t.status)) ? t.status : "pending") as ItemStatus;
119
+ const evidence = Array.isArray(t.evidence) ? t.evidence.map(obj) : [];
120
+ const shas: string[] = [];
121
+ for (const e of evidence) {
122
+ const sha = str(e.sha);
123
+ if (sha && /^[0-9a-f]{6,40}$/i.test(sha) && !shas.includes(sha)) shas.push(sha);
124
+ }
125
+ // Only a `child:<subagent id>` ref is kept: it joins the child to the item. A tool call id needs no storing.
126
+ const refs = evidence.map((e) => str(e.ref)).filter((r): r is string => !!r && CHILD_REF.test(r));
127
+ // A uid or origin that is not name-shaped would become the shared key "redacted": drop it instead.
128
+ const named = (v: unknown) => (typeof v === "string" && v && safeName(v) === v ? v : undefined);
129
+ const uid = named(t.uid);
130
+ const origin = named(obj(t.origin).session);
131
+ return {
132
+ id: t.id,
133
+ status,
134
+ title: titleOf(t.subject),
135
+ owner: str(t.owner) ? safeName(t.owner) : undefined,
136
+ uid,
137
+ origin,
138
+ evidence: evidence.length,
139
+ shas,
140
+ refs,
141
+ blockedBy: Array.isArray(t.blockedBy) ? t.blockedBy.length : 0,
142
+ };
143
+ }
144
+
145
+ /** The kind of stall a waking entry ends, or undefined when the entry does not start a turn. */
146
+ export function wakeOf(entry: Obj): { kind: StallKind; on?: string } | undefined {
147
+ const type = entry.type;
148
+ if (type === "thinking_level_change" || type === "model_change") return { kind: "human" };
149
+ if (type === "message") return obj(entry.message).role === "user" ? { kind: "human" } : undefined;
150
+ if (type !== "custom_message") return undefined;
151
+ const details = obj(entry.details);
152
+ switch (entry.customType) {
153
+ case "better-show":
154
+ case "robot-hand-follow-up":
155
+ case "robot-hand-herdr":
156
+ return { kind: "human" };
157
+ case "intercom_message": {
158
+ const from = str(obj(details.from).id);
159
+ return { kind: "peer", on: from ? peerName(from) : undefined };
160
+ }
161
+ case "straw-tower":
162
+ return details.kind === "intercom" ? { kind: "peer", on: peerName(str(obj(details.from).id) ?? "") || undefined } : { kind: "timer" };
163
+ case "straw-link":
164
+ return { kind: "device" };
165
+ case "subagent_result":
166
+ case "subagent_ping":
167
+ case "subagent_status":
168
+ case "subagent_stop":
169
+ case "subagent-accept-check":
170
+ case "straw-boss-orphan-result":
171
+ case "straw-boss-child-revived": {
172
+ const name = str(details.name);
173
+ return { kind: "child", on: name ? safeName(name) : undefined };
174
+ }
175
+ case "pi-loop-monitor": {
176
+ if (details.deliveryGroup === "monitor-started") return undefined;
177
+ const source = str(obj(details.trigger).source) ?? "";
178
+ return details.deliveryGroup === "monitor-terminal" || source.startsWith("monitor:") ? { kind: "ci" } : { kind: "timer" };
179
+ }
180
+ case "straw-auto":
181
+ case "straw-boss-wrap":
182
+ case "straw-boss-watch":
183
+ return { kind: "timer" };
184
+ default:
185
+ return undefined;
186
+ }
187
+ }
188
+
189
+ const UUIDISH = /^[0-9a-f]{8}-[0-9a-f]{4}-/i;
190
+ /** A peer session by its first 13 characters: UUIDv7 sessions started within the same minute share the first 8. */
191
+ const peerName = (id: string) => (UUIDISH.test(id) ? id.slice(0, 13) : safeName(id));
192
+
193
+ export class WorkTracker {
194
+ private snaps: Snapshot[] = [];
195
+ /** entry id → index of the newest todo snapshot on its path (or -1). */
196
+ private todoAt = new Map<string, number>();
197
+ private costs: [number, number][] = [];
198
+ private gaps: Gap[] = [];
199
+ private idleFrom?: string;
200
+ private launches: Launch[] = [];
201
+ private childEvents: SessionWork["childEvents"] = [];
202
+ private pairs: SessionWork["pairs"] = [];
203
+ private wraps: SessionWork["wraps"] = [];
204
+ private last = "";
205
+
206
+ /** Every entry, in file order, before it is otherwise handled. */
207
+ entry(entry: Obj, ts: string): void {
208
+ if (ts && ts > this.last) this.last = ts;
209
+ const id = str(entry.id);
210
+ const parent = str(entry.parentId);
211
+ const inherited = parent !== undefined ? (this.todoAt.get(parent) ?? -1) : this.snaps.length - 1;
212
+ if (entry.type === "custom" && entry.customType === "todo/v1") {
213
+ const data = obj(entry.data);
214
+ if (Array.isArray(data.tasks)) {
215
+ const tasks = data.tasks.map(liteOf).filter((t): t is TaskLite => !!t);
216
+ this.snaps.push({ entry: id ?? String(this.snaps.length), ts, pred: inherited, tasks });
217
+ if (id) this.todoAt.set(id, this.snaps.length - 1);
218
+ return;
219
+ }
220
+ }
221
+ if (id) this.todoAt.set(id, inherited);
222
+ if (this.idleFrom && ts) {
223
+ const wake = wakeOf(entry);
224
+ if (wake) {
225
+ this.gap(this.idleFrom, ts, wake.kind, wake.on, "idle");
226
+ this.idleFrom = undefined;
227
+ }
228
+ }
229
+ }
230
+
231
+ assistant(ts: string, cost: number, stopReason: unknown): void {
232
+ if (cost) this.costs.push([Date.parse(ts), cost]);
233
+ // A turn that started from an entry we do not classify: its idle time is not a stall of a known kind.
234
+ this.idleFrom = typeof stopReason === "string" && stopReason !== "toolUse" ? ts : undefined;
235
+ }
236
+
237
+ /** A question tool held the main for `start`..`end`. */
238
+ wait(start: string, end: string, kind: StallKind): void {
239
+ this.gap(start, end, kind, undefined, "ask");
240
+ }
241
+
242
+ launch(l: Launch): void {
243
+ this.launches.push(l);
244
+ }
245
+
246
+ child(ts: string, name: string, what: "result" | "resume"): void {
247
+ this.childEvents.push([ts, safeName(name), what]);
248
+ }
249
+
250
+ pair(p: SessionWork["pairs"][number]): void {
251
+ this.pairs.push(p);
252
+ }
253
+
254
+ wrap(at: string, wrapped: boolean): void {
255
+ this.wraps.push({ at, wrapped });
256
+ }
257
+
258
+ private gap(start: string, end: string, kind: StallKind, on: string | undefined, via: Gap["via"]) {
259
+ if (Date.parse(end) - Date.parse(start) >= STALL_MS) this.gaps.push({ start, end, kind, on, via });
260
+ }
261
+
262
+ finish(session: string, nested: boolean): SessionWork | undefined {
263
+ const items = this.items(session, nested);
264
+ if (!items.length && !this.launches.length && !this.pairs.length) return undefined;
265
+ const end = Date.parse(this.last);
266
+ const spans = items.map((it) => it.active.map(([a, b]) => [Date.parse(a), b ? Date.parse(b) : end + 1] as const));
267
+ let unattributed = 0;
268
+ for (const [t, cost] of this.costs) {
269
+ const on = spans.flatMap((s, i) => (s.some(([a, b]) => t >= a && t < b) ? [i] : []));
270
+ if (!on.length) unattributed += cost;
271
+ for (const i of on) items[i].mainCost += cost / on.length;
272
+ }
273
+ this.gaps.forEach((g, gi) => {
274
+ const a = Date.parse(g.start);
275
+ const b = Date.parse(g.end);
276
+ spans.forEach((s, i) => {
277
+ const ms = s.reduce((sum, [x, y]) => sum + Math.max(0, Math.min(b, y) - Math.max(a, x)), 0);
278
+ if (ms > 0) items[i].stalls.push([gi, ms]);
279
+ });
280
+ });
281
+ for (const it of items) it.mainCost = Math.round(it.mainCost * 1e6) / 1e6;
282
+ return {
283
+ items,
284
+ gaps: this.gaps,
285
+ launches: this.launches,
286
+ childEvents: this.childEvents,
287
+ pairs: this.pairs,
288
+ wraps: this.wraps,
289
+ idleSince: this.idleFrom,
290
+ lastActivity: this.last,
291
+ unattributed: Math.round(unattributed * 1e6) / 1e6,
292
+ };
293
+ }
294
+
295
+ /** Items along each branch's chain of snapshots, the branch holding the file's last snapshot first. */
296
+ private items(session: string, nested: boolean): ItemRaw[] {
297
+ const n = this.snaps.length;
298
+ if (!n) return [];
299
+ const hasChild = new Array<boolean>(n).fill(false);
300
+ for (const s of this.snaps) if (s.pred >= 0) hasChild[s.pred] = true;
301
+ const leaves = [...Array(n).keys()].filter((i) => !hasChild[i]).sort((a, b) => b - a);
302
+ const main = new Set<number>();
303
+ for (let i = leaves[0]; i >= 0; i = this.snaps[i].pred) main.add(i);
304
+ const done = new Map<string, ItemRaw>();
305
+ const order: ItemRaw[] = [];
306
+ const reuse = new Map<number, number>();
307
+ for (const leaf of leaves) {
308
+ const chain: number[] = [];
309
+ for (let i = leaf; i >= 0; i = this.snaps[i].pred) chain.unshift(i);
310
+ const live = new Map<number, { identity: string; item?: ItemRaw }>();
311
+ const leafTs = this.snaps[leaf].ts;
312
+ let prevSize = -1;
313
+ for (const si of chain) {
314
+ const snap = this.snaps[si];
315
+ const seen = new Set<number>();
316
+ const fresh = prevSize <= 0;
317
+ prevSize = snap.tasks.length;
318
+ for (const task of snap.tasks) {
319
+ seen.add(task.id);
320
+ let cur = live.get(task.id);
321
+ if (!cur) {
322
+ const identity = `${si}:${task.id}`;
323
+ const known = done.get(identity);
324
+ cur = { identity, item: known ? undefined : this.newItem(session, nested, task, snap, si, main, reuse) };
325
+ if (cur.item && (task.status === "completed" || task.status === "deleted") && (fresh || task.origin)) cur.item.carried = true;
326
+ live.set(task.id, cur);
327
+ if (cur.item) {
328
+ done.set(identity, cur.item);
329
+ order.push(cur.item);
330
+ }
331
+ }
332
+ if (cur.item) this.step(cur.item, task, snap.ts);
333
+ }
334
+ for (const [id, cur] of live) {
335
+ if (seen.has(id)) continue;
336
+ // Removed from the list (a clear, or a handover that drops it) while not finished: it was dropped here.
337
+ if (cur.item && (cur.item.status === "pending" || cur.item.status === "in_progress")) this.step(cur.item, { ...lastLite(cur.item), status: "deleted" }, snap.ts);
338
+ live.delete(id);
339
+ }
340
+ }
341
+ const sideEnd = main.has(leaf) ? null : leafTs;
342
+ for (const cur of live.values()) if (cur.item && sideEnd) for (const span of cur.item.active) if (span[1] === null) span[1] = sideEnd;
343
+ }
344
+ return order;
345
+ }
346
+
347
+ private newItem(session: string, nested: boolean, task: TaskLite, snap: Snapshot, si: number, main: Set<number>, reuse: Map<number, number>): ItemRaw {
348
+ let key: string;
349
+ if (task.uid) key = task.uid;
350
+ else if (task.origin) key = `${task.origin}#${task.id}`;
351
+ else if (main.has(si)) {
352
+ const count = (reuse.get(task.id) ?? 0) + 1;
353
+ reuse.set(task.id, count);
354
+ key = count === 1 ? `${session}#${task.id}` : `${session}#${task.id}.${count}`;
355
+ } else key = `${session}#${task.id}@${safeName(snap.entry).slice(0, 8)}`;
356
+ return {
357
+ key,
358
+ id: task.id,
359
+ title: task.title,
360
+ owner: task.owner,
361
+ uid: task.uid,
362
+ origin: task.origin,
363
+ level: nested ? "nested" : "top",
364
+ status: "pending",
365
+ created: snap.ts,
366
+ active: [],
367
+ evidence: 0,
368
+ shas: [],
369
+ refs: [],
370
+ blockedBy: 0,
371
+ mainCost: 0,
372
+ stalls: [],
373
+ };
374
+ }
375
+
376
+ private step(item: ItemRaw, task: TaskLite, ts: string) {
377
+ const was = item.status;
378
+ if (task.uid && item.uid !== task.uid) item.key = item.uid = task.uid;
379
+ 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 });
380
+ if (task.status === was) return;
381
+ item.status = task.status;
382
+ if (task.status === "in_progress" && was !== "in_progress") {
383
+ item.start ??= ts;
384
+ item.close = undefined;
385
+ item.active.push([ts, null]);
386
+ } else if (task.status !== "in_progress" && was === "in_progress") {
387
+ const open = item.active.at(-1);
388
+ if (open && open[1] === null) open[1] = ts;
389
+ }
390
+ if (task.status === "completed" || task.status === "deleted") item.close = ts;
391
+ else if (task.status === "pending") item.close = undefined;
392
+ }
393
+ }
394
+
395
+ function lastLite(item: ItemRaw): TaskLite {
396
+ 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 };
397
+ }