@heretek-ai/opencode-teamwork-v2 0.0.0-stage → 0.5.9

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.
@@ -0,0 +1,713 @@
1
+ // lib/timeline.mjs — Teamwork run lifecycle timeline (READ-ONLY)
2
+ //
3
+ // buildTimeline(projectRoot, sessionId?) reads a run directory and returns a
4
+ // structured timeline. When events.jsonl exists and yields at least one
5
+ // parseable event the timeline is exact ("events" mode). Otherwise it falls
6
+ // back to "derived" mode, which never invents a start time or a duration.
7
+ //
8
+ // renderTimeline(timeline, { color }) turns that object into printable lines.
9
+ //
10
+ // Zero runtime dependencies. Node >= 18. No writes, no mkdir, no rm, no
11
+ // process access, no clock reads: the output is a pure function of the files.
12
+
13
+ import { closeSync, existsSync, fstatSync, lstatSync, openSync, readdirSync, readSync, constants as fsConstants } from "node:fs"
14
+ import { isAbsolute, join, relative, resolve } from "node:path"
15
+
16
+ const SESSION_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
17
+ // A task id is used as a path segment (verify/report-<id>.json), so it must be
18
+ // a single safe segment: no separators, no "..", no leading dot.
19
+ const TASK_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
20
+ const TERMINAL_EVENT_STATES = new Set(["verified_pass", "blocked"])
21
+ const PASS_STATES = new Set(["pass", "verified_pass"])
22
+ const FAIL_STATES = new Set(["fail", "verified_fail"])
23
+
24
+ // Upper bounds on bytes read from one run file. events.jsonl is capped at 8 MiB
25
+ // (it is only ever scanned line by line, and a truncated tail would give a
26
+ // wrong end time, so an oversize events file is reported, not partly read).
27
+ // The JSON files are read whole up to 64 MiB, so a legitimately large
28
+ // state.json still renders correctly. Beyond either cap the file is reported.
29
+ const MAX_EVENTS_BYTES = 8 * 1024 * 1024
30
+ const MAX_JSON_BYTES = 64 * 1024 * 1024
31
+
32
+ // Per-timeline diagnostics (oversize / unreadable run files), kept outside the
33
+ // returned object so the frozen buildTimeline shape is unchanged. Keyed by the
34
+ // timeline object; renderTimeline and timelineWarnings read it.
35
+ const DIAGNOSTICS = new WeakMap()
36
+
37
+ function mib(bytes) {
38
+ const v = bytes / (1024 * 1024)
39
+ return Number.isInteger(v) ? String(v) : v.toFixed(1)
40
+ }
41
+
42
+ // Read a file only if it is a regular file (never follow a symlink) and it is
43
+ // no larger than maxBytes. Returns one of:
44
+ // { status: "ok", text } read in full
45
+ // { status: "absent" } does not exist
46
+ // { status: "oversize", size, cap } exists but is larger than maxBytes
47
+ // { status: "unreadable" } exists but is not a readable regular file
48
+ // Oversize is never reported as absent. Never writes.
49
+ function readBounded(file, maxBytes) {
50
+ let fd = null
51
+ try {
52
+ if (!lstatSync(file).isFile()) return { status: "unreadable" }
53
+ fd = openSync(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0))
54
+ const st = fstatSync(fd)
55
+ if (!st.isFile()) return { status: "unreadable" }
56
+ if (st.size > maxBytes) return { status: "oversize", size: st.size, cap: maxBytes }
57
+ // Read at most maxBytes+1 so a file that grows after fstat is still bounded.
58
+ const cap = Math.min(st.size, maxBytes) + 1
59
+ const buf = Buffer.alloc(cap)
60
+ let total = 0
61
+ while (total < cap) {
62
+ const n = readSync(fd, buf, total, cap - total, null)
63
+ if (n === 0) break
64
+ total += n
65
+ }
66
+ if (total > maxBytes) return { status: "oversize", size: total, cap: maxBytes }
67
+ return { status: "ok", text: buf.subarray(0, total).toString("utf8") }
68
+ } catch (err) {
69
+ return { status: err && err.code === "ENOENT" ? "absent" : "unreadable" }
70
+ } finally {
71
+ if (fd !== null) {
72
+ try {
73
+ closeSync(fd)
74
+ } catch {}
75
+ }
76
+ }
77
+ }
78
+
79
+ function oversizeDiag(label, r) {
80
+ return { file: label, kind: "oversize", message: `${label} exceeds the ${mib(r.cap)} MiB read cap (${mib(r.size)} MiB)` }
81
+ }
82
+
83
+ function unreadableDiag(label, why = "is not a regular file; it was not read") {
84
+ return { file: label, kind: "unreadable", message: `${label} ${why}` }
85
+ }
86
+
87
+ // True when .opencode or .opencode/teamwork is a symlink: nothing under it may
88
+ // be read (the engine refuses the same layout).
89
+ function runRootIsLink(projectRoot) {
90
+ for (const p of [join(projectRoot, ".opencode"), join(projectRoot, ".opencode", "teamwork")]) {
91
+ try {
92
+ if (lstatSync(p).isSymbolicLink()) return true
93
+ } catch {}
94
+ }
95
+ return false
96
+ }
97
+
98
+ // Validate a task id and assert that the report path it names stays inside
99
+ // the run directory. Returns the report path, or null if the id is refused.
100
+ function isValidTaskId(taskId) {
101
+ return typeof taskId === "string" && TASK_ID.test(taskId) && !taskId.includes("..")
102
+ }
103
+
104
+ function reportPathFor(runDir, taskId) {
105
+ if (!isValidTaskId(taskId)) return null
106
+ const file = join(runDir, "verify", `report-${taskId}.json`)
107
+ const rel = relative(resolve(runDir), resolve(file))
108
+ if (!rel || isAbsolute(rel) || rel.startsWith("..")) return null
109
+ return file
110
+ }
111
+
112
+ // Read verify/report-<taskId>.json as a JSON record, or null. Refuses invalid
113
+ // ids and any path that would not stay inside runDir (including a symlinked
114
+ // verify/ directory). Never throws.
115
+ function readReport(runDir, taskId, diags) {
116
+ const file = reportPathFor(runDir, taskId)
117
+ if (file === null) return null
118
+ try {
119
+ if (!lstatSync(join(runDir, "verify")).isDirectory()) return null
120
+ } catch {
121
+ return null
122
+ }
123
+ // taskId passed reportPathFor, so it is a safe token to show in the label.
124
+ return readJson(file, `verify/report-${taskId}.json`, diags)
125
+ }
126
+
127
+ // Read and parse one JSON run file. An absent file is silently null. An
128
+ // oversize or unreadable file is also null, but it records a diagnostic so the
129
+ // caller can show the reason instead of a confident "UNKNOWN"/"pending".
130
+ function readJson(file, label, diags) {
131
+ const r = readBounded(file, MAX_JSON_BYTES)
132
+ if (r.status === "oversize") {
133
+ diags.push(oversizeDiag(label, r))
134
+ return null
135
+ }
136
+ if (r.status === "unreadable") {
137
+ diags.push(unreadableDiag(label))
138
+ return null
139
+ }
140
+ if (r.status !== "ok") return null
141
+ const text = r.text
142
+ try {
143
+ const value = JSON.parse(text)
144
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
150
+ function isRecord(value) {
151
+ return value !== null && typeof value === "object" && !Array.isArray(value)
152
+ }
153
+
154
+ function numberOrNull(value) {
155
+ return typeof value === "number" && Number.isFinite(value) ? value : null
156
+ }
157
+
158
+ function stringOrNull(value) {
159
+ return typeof value === "string" ? value : null
160
+ }
161
+
162
+ function parseTs(value) {
163
+ if (typeof value !== "string") return NaN
164
+ return Date.parse(value)
165
+ }
166
+
167
+ function emptyTimeline(sessionId = null) {
168
+ return {
169
+ sessionId,
170
+ topology: "unknown",
171
+ phase: "UNKNOWN",
172
+ mode: "derived",
173
+ budgetUsd: null,
174
+ budgetSource: null,
175
+ spentUsd: 0,
176
+ startedAt: null,
177
+ endedAt: null,
178
+ durationMs: 0,
179
+ tasks: [],
180
+ unattributed: [],
181
+ totals: { tasks: 0, passed: 0, failed: 0, blocked: 0, totalRounds: 0, spentUsd: 0, tokens: null },
182
+ }
183
+ }
184
+
185
+ // Mirrors listTeamworkRuns() ordering: newest run directory first (mtime desc).
186
+ // Symlinked run directories are skipped so that nothing outside the
187
+ // .opencode/teamwork tree is ever read through this module.
188
+ function listRunIds(projectRoot) {
189
+ const base = join(projectRoot, ".opencode", "teamwork")
190
+ if (!existsSync(base) || runRootIsLink(projectRoot)) return []
191
+ let names
192
+ try {
193
+ names = readdirSync(base)
194
+ } catch {
195
+ return []
196
+ }
197
+ const runs = []
198
+ for (const name of names) {
199
+ if (!SESSION_ID.test(name)) continue
200
+ try {
201
+ const st = lstatSync(join(base, name))
202
+ if (!st.isDirectory()) continue
203
+ runs.push({ name, mtime: st.mtimeMs })
204
+ } catch {}
205
+ }
206
+ runs.sort((a, b) => b.mtime - a.mtime)
207
+ return runs.map((r) => r.name)
208
+ }
209
+
210
+ // Parse events.jsonl, skipping anything that is not a usable event object.
211
+ function readEvents(runDir, diags) {
212
+ const r = readBounded(join(runDir, "events.jsonl"), MAX_EVENTS_BYTES)
213
+ if (r.status === "oversize") {
214
+ diags.push(oversizeDiag("events.jsonl", r))
215
+ return []
216
+ }
217
+ if (r.status === "unreadable") {
218
+ diags.push(unreadableDiag("events.jsonl"))
219
+ return []
220
+ }
221
+ if (r.status !== "ok") return []
222
+ const text = r.text
223
+ const events = []
224
+ for (const line of text.split("\n")) {
225
+ const trimmed = line.trim()
226
+ if (!trimmed) continue
227
+ let obj
228
+ try {
229
+ obj = JSON.parse(trimmed)
230
+ } catch {
231
+ continue // truncated / corrupt line (e.g. partial write at kill)
232
+ }
233
+ if (!isRecord(obj) || typeof obj.event !== "string" || Number.isNaN(parseTs(obj.ts))) continue
234
+ events.push({
235
+ ts: obj.ts,
236
+ tsMs: parseTs(obj.ts),
237
+ // Monotonic per events.jsonl; null on legacy lines written before seq existed.
238
+ seq: Number.isInteger(obj.seq) && obj.seq > 0 ? obj.seq : null,
239
+ event: obj.event,
240
+ taskId: stringOrNull(obj.taskId),
241
+ to: stringOrNull(obj.to),
242
+ round: numberOrNull(obj.round),
243
+ agent: stringOrNull(obj.agent),
244
+ // Provenance of agent (explicit | session | plan); null on legacy / actorless lines.
245
+ agentSource: obj.agentSource === "explicit" || obj.agentSource === "session" || obj.agentSource === "plan" ? obj.agentSource : null,
246
+ branch: stringOrNull(obj.branch),
247
+ })
248
+ }
249
+ return events
250
+ }
251
+
252
+ // Per-phase time for one task: time spent in each state, summed over rounds.
253
+ // Only states that were left (have a following transition) are reported.
254
+ function phaseNote(transitions) {
255
+ const order = []
256
+ const sums = new Map()
257
+ for (let i = 0; i + 1 < transitions.length; i++) {
258
+ const state = transitions[i].to
259
+ if (typeof state !== "string") continue
260
+ const span = transitions[i + 1].tsMs - transitions[i].tsMs
261
+ if (!sums.has(state)) {
262
+ sums.set(state, 0)
263
+ order.push(state)
264
+ }
265
+ sums.set(state, sums.get(state) + span)
266
+ }
267
+ if (!order.length) return null
268
+ return "phases: " + order.map((s) => `${s} ${sums.get(s)}ms`).join(" · ")
269
+ }
270
+
271
+ function buildEventsMode(events, state, plan, costs) {
272
+ const first = events[0]
273
+ const last = events[events.length - 1]
274
+ const runStart = first.ts
275
+ const runEnd = last.ts
276
+ const runDuration = parseTs(runEnd) - parseTs(runStart)
277
+
278
+ // Group task transitions by task, in file (append) order.
279
+ const byTask = new Map()
280
+ for (const ev of events) {
281
+ if (ev.event !== "task_transition" || ev.taskId === null) continue
282
+ if (!byTask.has(ev.taskId)) byTask.set(ev.taskId, [])
283
+ byTask.get(ev.taskId).push(ev)
284
+ }
285
+
286
+ const taskIds = orderedTaskIds(plan, state, [...byTask.keys()])
287
+ const tasks = taskIds.map((taskId) => {
288
+ const stateTask = isRecord(state.tasks?.[taskId]) ? state.tasks[taskId] : null
289
+ const transitions = byTask.get(taskId) || []
290
+ const stateStatus = stringOrNull(stateTask?.status)
291
+ const branchFromState = stringOrNull(stateTask?.branch)
292
+
293
+ if (!transitions.length) {
294
+ // Known to state.json / plan but no events recorded: unknown timing.
295
+ return {
296
+ taskId,
297
+ status: stateStatus ?? "pending",
298
+ rounds: numberOrNull(stateTask?.round) ?? 0,
299
+ passedAtRound: null,
300
+ agent: null,
301
+ agentSource: null,
302
+ branch: branchFromState,
303
+ seq: null,
304
+ startedAt: null,
305
+ endedAt: stringOrNull(stateTask?.updatedAt),
306
+ durationMs: null,
307
+ approx: true,
308
+ costUsd: taskCost(costs, taskId),
309
+ tokens: taskTokens(costs, taskId),
310
+ note: joinNotes(
311
+ "no events.jsonl entries for this task; start and duration unknown",
312
+ isValidTaskId(taskId) ? null : invalidIdNote(taskId),
313
+ ),
314
+ }
315
+ }
316
+
317
+ const startedAt = transitions[0].ts
318
+ let endIdx = -1
319
+ let passIdx = -1
320
+ for (let i = 0; i < transitions.length; i++) {
321
+ const to = transitions[i].to
322
+ if (TERMINAL_EVENT_STATES.has(to)) endIdx = i
323
+ if (to === "verified_pass") passIdx = i
324
+ }
325
+ const endEvent = endIdx >= 0 ? transitions[endIdx] : transitions[transitions.length - 1]
326
+ const endedAt = endEvent.ts
327
+ const durationMs = parseTs(endedAt) - parseTs(startedAt)
328
+
329
+ let rounds = 0
330
+ let agent = null
331
+ let agentSource = null
332
+ let workerAgent = null
333
+ let workerAgentSource = null
334
+ let branch = null
335
+ for (const t of transitions) {
336
+ if (t.round !== null && t.round > rounds) rounds = t.round
337
+ if (t.agent !== null) {
338
+ agent = t.agent
339
+ agentSource = t.agentSource
340
+ }
341
+ if (t.to === "worker_active" && t.agent !== null) {
342
+ workerAgent = t.agent
343
+ workerAgentSource = t.agentSource
344
+ }
345
+ if (t.branch !== null) branch = t.branch
346
+ }
347
+ // Prefer the worker agent (the one that ran the task); fall back to the last seen.
348
+ if (workerAgent !== null) {
349
+ agent = workerAgent
350
+ agentSource = workerAgentSource
351
+ }
352
+
353
+ const lastTo = transitions[transitions.length - 1].to
354
+ return {
355
+ taskId,
356
+ status: stateStatus ?? lastTo ?? "pending",
357
+ rounds,
358
+ passedAtRound: passIdx >= 0 ? transitions[passIdx].round : null,
359
+ agent,
360
+ agentSource,
361
+ branch: branchFromState ?? branch,
362
+ // First sequenced event line for this task; null when the whole log
363
+ // predates seq (a task that continues after an upgrade still exposes it).
364
+ seq: transitions.find((t) => t.seq !== null)?.seq ?? null,
365
+ startedAt,
366
+ endedAt,
367
+ durationMs,
368
+ approx: false,
369
+ costUsd: taskCost(costs, taskId),
370
+ tokens: taskTokens(costs, taskId),
371
+ note: joinNotes(phaseNote(transitions), isValidTaskId(taskId) ? null : invalidIdNote(taskId)),
372
+ }
373
+ })
374
+
375
+ return {
376
+ mode: "events",
377
+ startedAt: runStart,
378
+ endedAt: runEnd,
379
+ durationMs: runDuration,
380
+ tasks,
381
+ }
382
+ }
383
+
384
+ // Human-readable note for a task id that failed validation. The id is shown
385
+ // (truncated) so the operator can see it, but it is never used in a path.
386
+ function invalidIdNote(taskId) {
387
+ const shown = String(taskId).slice(0, 80)
388
+ return `task id "${shown}" failed validation; its verify report was not read`
389
+ }
390
+
391
+ function joinNotes(...parts) {
392
+ const kept = parts.filter((p) => typeof p === "string" && p)
393
+ return kept.length ? kept.join("; ") : null
394
+ }
395
+
396
+ function buildDerivedMode(state, plan, runDir, costs, diags) {
397
+ const taskIds = orderedTaskIds(plan, state, [])
398
+ const tasks = taskIds.map((taskId) => {
399
+ const stateTask = isRecord(state.tasks?.[taskId]) ? state.tasks[taskId] : null
400
+ const valid = isValidTaskId(taskId)
401
+ const report = readReport(runDir, taskId, diags)
402
+ const status = stringOrNull(stateTask?.status) ?? "pending"
403
+ const reportPassed = report && typeof report.status === "string" && report.status.toUpperCase() === "PASS"
404
+ const passedAtRound = status === "verified_pass" && reportPassed ? numberOrNull(report.round) : null
405
+ const approxNote =
406
+ "approximate: state.json keeps only the last updatedAt per task, so start time and duration are unknown; real durations require events.jsonl"
407
+ return {
408
+ taskId,
409
+ status,
410
+ rounds: numberOrNull(stateTask?.round) ?? 0,
411
+ passedAtRound,
412
+ agent: null,
413
+ agentSource: null,
414
+ branch: stringOrNull(stateTask?.branch),
415
+ seq: null,
416
+ startedAt: null,
417
+ endedAt: stringOrNull(stateTask?.updatedAt),
418
+ durationMs: 0,
419
+ approx: true,
420
+ costUsd: taskCost(costs, taskId),
421
+ tokens: taskTokens(costs, taskId),
422
+ note: valid ? approxNote : `${approxNote}; ${invalidIdNote(taskId)}`,
423
+ }
424
+ })
425
+ return {
426
+ mode: "derived",
427
+ startedAt: null,
428
+ endedAt: stringOrNull(state.updatedAt),
429
+ durationMs: 0,
430
+ tasks,
431
+ }
432
+ }
433
+
434
+ // Task ids in plan order, then state order, then any extra ids seen in events.
435
+ function orderedTaskIds(plan, state, extra) {
436
+ const seen = new Set()
437
+ const ids = []
438
+ const add = (id) => {
439
+ if (typeof id !== "string" || !id || seen.has(id)) return
440
+ seen.add(id)
441
+ ids.push(id)
442
+ }
443
+ if (Array.isArray(plan.tasks)) for (const t of plan.tasks) add(isRecord(t) ? t.id : undefined)
444
+ if (isRecord(state.tasks)) for (const id of Object.keys(state.tasks)) add(id)
445
+ for (const id of extra) add(id)
446
+ return ids
447
+ }
448
+
449
+ function taskCost(costs, taskId) {
450
+ const buckets = isRecord(costs.byTask) ? costs.byTask : {}
451
+ if (!Object.prototype.hasOwnProperty.call(buckets, taskId)) return null
452
+ return numberOrNull(buckets[taskId])
453
+ }
454
+
455
+ // A finite, non-negative number, or null.
456
+ function nonNegativeOrNull(value) {
457
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null
458
+ }
459
+
460
+ // Sanitise one per-task token bucket into a fresh, well-formed object, or null.
461
+ // Every numeric field must be present and finite and >= 0; any other shape
462
+ // (string, number, null, array, missing or non-object cache, NaN, negative)
463
+ // yields null. Only the known fields are copied, so no stray keys leak through.
464
+ function sanitizeTokenBucket(bucket) {
465
+ if (!isRecord(bucket) || !isRecord(bucket.cache)) return null
466
+ const input = nonNegativeOrNull(bucket.input)
467
+ const output = nonNegativeOrNull(bucket.output)
468
+ const reasoning = nonNegativeOrNull(bucket.reasoning)
469
+ const read = nonNegativeOrNull(bucket.cache.read)
470
+ const write = nonNegativeOrNull(bucket.cache.write)
471
+ if (input === null || output === null || reasoning === null || read === null || write === null) return null
472
+ return { input, output, reasoning, cache: { read, write } }
473
+ }
474
+
475
+ // Per-task token bucket from costs.byTaskTokens, or null when absent or malformed.
476
+ // Legacy costs.json files (no byTaskTokens) yield null.
477
+ function taskTokens(costs, taskId) {
478
+ const buckets = isRecord(costs.byTaskTokens) ? costs.byTaskTokens : {}
479
+ if (!Object.prototype.hasOwnProperty.call(buckets, taskId)) return null
480
+ return sanitizeTokenBucket(buckets[taskId])
481
+ }
482
+
483
+ // Build the unattributed list. A bucket is a task only when it names a known
484
+ // task id and is not an internal/agent bucket. Everything else is listed here.
485
+ function buildUnattributed(costs, taskIdSet) {
486
+ const buckets = isRecord(costs.byTask) ? costs.byTask : {}
487
+ const out = []
488
+ for (const key of Object.keys(buckets)) {
489
+ const isInternal = key.startsWith("_") || key.includes("/")
490
+ if (!isInternal && taskIdSet.has(key)) continue
491
+ const usd = numberOrNull(buckets[key])
492
+ out.push({ bucket: key, costUsd: usd ?? 0 })
493
+ }
494
+ return out
495
+ }
496
+
497
+ /**
498
+ * Build a lifecycle timeline for one Teamwork run.
499
+ * @param {string} projectRoot Project root containing .opencode/teamwork/
500
+ * @param {string} [sessionId] Run id; defaults to the most recent run.
501
+ */
502
+ export function buildTimeline(projectRoot, sessionId) {
503
+ const diags = []
504
+ const timeline = buildRun(projectRoot, sessionId, diags)
505
+ DIAGNOSTICS.set(timeline, diags)
506
+ return timeline
507
+ }
508
+
509
+ /**
510
+ * Human-readable warnings for a timeline built by buildTimeline: run files that
511
+ * were too large or not regular files, and so were NOT read. Empty when every
512
+ * file was either read or genuinely absent.
513
+ * @returns {string[]}
514
+ */
515
+ export function timelineWarnings(timeline) {
516
+ const diags = timeline && typeof timeline === "object" ? DIAGNOSTICS.get(timeline) : undefined
517
+ return diags ? diags.map((d) => d.message) : []
518
+ }
519
+
520
+ function buildRun(projectRoot, sessionId, diags) {
521
+ if (typeof projectRoot !== "string") return emptyTimeline(typeof sessionId === "string" ? sessionId : null)
522
+
523
+ let id = sessionId
524
+ if (id === undefined || id === null) {
525
+ id = listRunIds(projectRoot)[0] ?? null
526
+ }
527
+ if (typeof id !== "string" || !SESSION_ID.test(id)) return emptyTimeline(typeof id === "string" ? id : null)
528
+
529
+ if (runRootIsLink(projectRoot)) {
530
+ diags.push(unreadableDiag(".opencode/teamwork", "is a symlink; the run root was not read"))
531
+ return emptyTimeline(id)
532
+ }
533
+
534
+ const runDir = join(projectRoot, ".opencode", "teamwork", id)
535
+ let isDir = false
536
+ try {
537
+ isDir = lstatSync(runDir).isDirectory()
538
+ } catch {}
539
+ if (!isDir) return emptyTimeline(id)
540
+
541
+ const state = readJson(join(runDir, "state.json"), "state.json", diags) || {}
542
+ const plan = readJson(join(runDir, "plan.dag.json"), "plan.dag.json", diags) || {}
543
+ const costs = readJson(join(runDir, "costs.json"), "costs.json", diags) || {}
544
+ const events = readEvents(runDir, diags)
545
+
546
+ const stateIds = isRecord(state.tasks) ? Object.keys(state.tasks) : []
547
+ const planIds = Array.isArray(plan.tasks) ? plan.tasks.map((t) => (isRecord(t) ? t.id : undefined)) : []
548
+ const knownIds = new Set([...stateIds, ...planIds.filter((x) => typeof x === "string")])
549
+
550
+ const mode = events.length ? "events" : "derived"
551
+ const body = events.length
552
+ ? buildEventsMode(events, state, plan, costs)
553
+ : buildDerivedMode(state, plan, runDir, costs, diags)
554
+ // events.jsonl exists but was not read: every task says why its timing is unknown.
555
+ const eventsDiag = diags.find((d) => d.file === "events.jsonl")
556
+ if (mode === "derived" && eventsDiag) {
557
+ for (const task of body.tasks) task.note = joinNotes(task.note, `${eventsDiag.message}; timing unavailable`)
558
+ }
559
+
560
+ // Event-only task ids are already in body.tasks; include them when deciding
561
+ // which cost buckets are tasks.
562
+ const taskIdSet = new Set([...knownIds, ...body.tasks.map((t) => t.taskId)])
563
+ const unattributed = buildUnattributed(costs, taskIdSet)
564
+
565
+ const tokens = isRecord(costs.tokens) ? costs.tokens : null
566
+ const spentUsd = numberOrNull(costs.spentUsd) ?? 0
567
+ const tasks = body.tasks
568
+ const totals = {
569
+ tasks: tasks.length,
570
+ passed: tasks.filter((t) => PASS_STATES.has(t.status)).length,
571
+ failed: tasks.filter((t) => FAIL_STATES.has(t.status)).length,
572
+ blocked: tasks.filter((t) => t.status === "blocked").length,
573
+ totalRounds: tasks.reduce((sum, t) => sum + (t.rounds || 0), 0),
574
+ spentUsd,
575
+ tokens,
576
+ }
577
+
578
+ return {
579
+ sessionId: stringOrNull(state.sessionId) ?? id,
580
+ topology: stringOrNull(plan.topology) ?? "unknown",
581
+ phase: stringOrNull(state.phase) ?? "UNKNOWN",
582
+ mode,
583
+ budgetUsd: numberOrNull(costs.budgetUsd),
584
+ budgetSource: stringOrNull(costs.budgetSource),
585
+ spentUsd,
586
+ startedAt: body.startedAt,
587
+ endedAt: body.endedAt,
588
+ durationMs: body.durationMs,
589
+ tasks,
590
+ unattributed,
591
+ totals,
592
+ }
593
+ }
594
+
595
+ // ---------------------------------------------------------------- rendering
596
+
597
+ function paint(enabled, code, text) {
598
+ return enabled ? `\x1b[${code}m${text}\x1b[0m` : text
599
+ }
600
+
601
+ function fmtDuration(ms) {
602
+ if (typeof ms !== "number" || !Number.isFinite(ms)) return "unknown"
603
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`
604
+ const seconds = ms / 1000
605
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
606
+ const minutes = Math.floor(seconds / 60)
607
+ const rem = Math.round(seconds - minutes * 60)
608
+ return `${minutes}m ${String(rem).padStart(2, "0")}s`
609
+ }
610
+
611
+ function fmtUsd(value) {
612
+ return typeof value === "number" && Number.isFinite(value) ? `$${value.toFixed(4)}` : "n/a"
613
+ }
614
+
615
+ function statusColor(status) {
616
+ if (PASS_STATES.has(status)) return "32" // green
617
+ if (FAIL_STATES.has(status) || status === "blocked") return "31" // red
618
+ if (status === "worker_active" || status === "worker_done") return "36" // cyan
619
+ if (status === "verifier_active") return "35" // magenta
620
+ return "33" // yellow for anything else (pending/unknown)
621
+ }
622
+
623
+ /**
624
+ * Render a timeline (from buildTimeline) as printable lines.
625
+ * Pure: no I/O, no clock. ANSI escapes only when color === true.
626
+ * @returns {string[]}
627
+ */
628
+ // C0 and C1 control characters (includes ESC, BEL, CR, LF, TAB, DEL). Data
629
+ // from state.json / events.jsonl can carry these; they must never reach the
630
+ // terminal, whether or not colour is enabled.
631
+ const CONTROL_CHARS = /[\x00-\x1f\x7f-\x9f]/g
632
+
633
+ // Return a copy of value with every string stripped of control characters.
634
+ // Keys, numbers, booleans and null are kept as they are, so the shape is the same.
635
+ function stripControls(value) {
636
+ if (typeof value === "string") return value.replace(CONTROL_CHARS, "")
637
+ if (Array.isArray(value)) return value.map(stripControls)
638
+ if (isRecord(value)) {
639
+ const out = {}
640
+ for (const key of Object.keys(value)) out[key.replace(CONTROL_CHARS, "")] = stripControls(value[key])
641
+ return out
642
+ }
643
+ return value
644
+ }
645
+
646
+ export function renderTimeline(timeline, options = {}) {
647
+ const color = options && options.color === true
648
+ const t = stripControls(timeline || emptyTimeline())
649
+ const diags = (timeline && typeof timeline === "object" && DIAGNOSTICS.get(timeline)) || []
650
+ const p = (code, text) => paint(color, code, text)
651
+ const lines = []
652
+ const approxTag = t.mode === "derived" ? p("33", " [APPROX]") : ""
653
+
654
+ lines.push(p("1", `Teamwork timeline — ${t.sessionId ?? "unknown"}`))
655
+ lines.push(` topology: ${t.topology ?? "unknown"} phase: ${t.phase ?? "UNKNOWN"} mode: ${t.mode}${approxTag}`)
656
+ const budget = typeof t.budgetUsd === "number" ? `$${t.budgetUsd}` : "n/a"
657
+ const source = t.budgetSource ? ` (${t.budgetSource})` : ""
658
+ lines.push(` budget: ${budget}${source} spent: ${fmtUsd(t.spentUsd)}`)
659
+ if (t.mode === "events") {
660
+ lines.push(` started: ${t.startedAt ?? "unknown"} ended: ${t.endedAt ?? "unknown"} wall-clock: ${fmtDuration(t.durationMs)}`)
661
+ } else {
662
+ // Say WHY there is no timing. An unread events.jsonl must never be reported as absent.
663
+ const eventsDiag = diags.find((d) => d.file === "events.jsonl")
664
+ const reason = eventsDiag
665
+ ? `${eventsDiag.message}; timing unavailable`
666
+ : diags.length
667
+ ? "some run files were not read, see warnings below"
668
+ : "no events.jsonl"
669
+ lines.push(p("33", ` wall-clock: unknown (derived mode: ${stripControls(reason)}; last update ${t.endedAt ?? "unknown"})`))
670
+ }
671
+ for (const d of diags) {
672
+ if (d.file === "events.jsonl") continue // already shown in the wall-clock line
673
+ lines.push(p("33", ` ! ${stripControls(d.message)}`))
674
+ }
675
+ lines.push("")
676
+
677
+ const tasks = Array.isArray(t.tasks) ? t.tasks : []
678
+ if (!tasks.length) lines.push(" (no tasks recorded)")
679
+
680
+ for (const task of tasks) {
681
+ const sc = statusColor(task.status)
682
+ const icon = PASS_STATES.has(task.status) ? "✓" : FAIL_STATES.has(task.status) || task.status === "blocked" ? "✗" : "•"
683
+ const passRound = task.passedAtRound != null ? `pass@round ${task.passedAtRound}` : "no pass"
684
+ const seqTag = task.seq != null ? ` seq: ${task.seq}` : ""
685
+ lines.push(`${p(sc, `${icon} ${task.taskId}`)} ${p(sc, task.status ?? "unknown")} rounds: ${task.rounds ?? 0} ${passRound}${seqTag}`)
686
+ const sourceTag = task.agentSource ? ` (${task.agentSource})` : ""
687
+ lines.push(` worker: ${task.agent ?? "unknown"}${sourceTag} branch: ${task.branch ?? "n/a"}`)
688
+ if (task.approx) {
689
+ lines.push(p("33", ` ~ approx start: ${task.startedAt ?? "unknown"} end: ${task.endedAt ?? "unknown"} duration: unknown`))
690
+ } else {
691
+ lines.push(` start: ${p("2", task.startedAt ?? "unknown")} end: ${p("2", task.endedAt ?? "unknown")} duration: ${fmtDuration(task.durationMs)}`)
692
+ }
693
+ const taskTokenText = task.tokens ? `in=${task.tokens.input} out=${task.tokens.output}` : "n/a"
694
+ lines.push(` cost: ${fmtUsd(task.costUsd)} tokens: ${taskTokenText}`)
695
+ if (task.note) lines.push(p(task.approx ? "33" : "2", ` note: ${task.note}`))
696
+ }
697
+
698
+ lines.push("")
699
+ const un = Array.isArray(t.unattributed) ? t.unattributed : []
700
+ if (un.length) {
701
+ lines.push(" unattributed cost:")
702
+ for (const u of un) lines.push(` ${u.bucket}: ${fmtUsd(u.costUsd)}`)
703
+ }
704
+
705
+ const totals = t.totals || {}
706
+ const tokenLine = totals.tokens
707
+ ? `tokens in=${totals.tokens.input ?? "?"} out=${totals.tokens.output ?? "?"}`
708
+ : "tokens n/a"
709
+ lines.push(
710
+ ` totals: ${totals.tasks ?? 0} tasks · ${p("32", `${totals.passed ?? 0} passed`)} · ${p("31", `${totals.failed ?? 0} failed`)} · ${p("31", `${totals.blocked ?? 0} blocked`)} · ${totals.totalRounds ?? 0} rounds · ${fmtUsd(totals.spentUsd)} · ${tokenLine}`,
711
+ )
712
+ return lines
713
+ }