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

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/lib/export.mjs ADDED
@@ -0,0 +1,1119 @@
1
+ // lib/export.mjs — Teamwork run report export (READ-ONLY)
2
+ //
3
+ // buildExportData(projectRoot, sessionId) reads one run directory and returns a
4
+ // plain data object. It never throws: an invalid or missing run yields an object
5
+ // whose `error` field is a string.
6
+ //
7
+ // renderExport(data, { format }) is a pure function of its input. format is
8
+ // "markdown" for GitHub-flavoured Markdown; anything else (including undefined)
9
+ // renders the single-file offline HTML document.
10
+ //
11
+ // Zero runtime dependencies. Node >= 18. No writes, no network, no scripts in
12
+ // the output, no clock reads.
13
+
14
+ import { closeSync, fstatSync, lstatSync, openSync, readSync, constants as fsConstants } from "node:fs"
15
+ import { isAbsolute, join, relative, resolve } from "node:path"
16
+
17
+ const SESSION_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
18
+ // A task id becomes a path segment (verify/report-<id>.json): one safe segment only.
19
+ const TASK_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
20
+ const CTRL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g
21
+ const SEVERITIES = ["critical", "high", "medium", "low"]
22
+ const PREFLIGHT_STATUSES = ["READY", "MISSING", "OUTAGE", "SKIPPED"]
23
+
24
+ const MAX_EVENTS_BYTES = 8 * 1024 * 1024
25
+ const MAX_JSON_BYTES = 16 * 1024 * 1024
26
+ const MAX_PITFALLS_BYTES = 1 * 1024 * 1024
27
+ const MAX_TASKS = 500
28
+ const MAX_FINDINGS = 200
29
+ const MAX_PITFALLS = 500
30
+ const MAX_FATAL = 50
31
+ const MAX_TEXT = 4000
32
+ const MAX_SHORT = 300
33
+ const MAX_PITFALL = 500
34
+
35
+ const HTML_ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }
36
+
37
+ // ------------------------------------------------------------ small helpers
38
+
39
+ function isRecord(value) {
40
+ return value !== null && typeof value === "object" && !Array.isArray(value)
41
+ }
42
+
43
+ // Own-property read: never reaches Object.prototype (e.g. a task id "constructor").
44
+ function own(obj, key) {
45
+ return isRecord(obj) && Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined
46
+ }
47
+
48
+ function numberOrNull(value) {
49
+ return typeof value === "number" && Number.isFinite(value) ? value : null
50
+ }
51
+
52
+ function nonNegInt(value) {
53
+ const n = numberOrNull(value)
54
+ return n !== null && n >= 0 ? Math.floor(n) : 0
55
+ }
56
+
57
+ // Printable text: control characters become spaces, trimmed, capped in length.
58
+ // Returns null for values that are not strings or finite numbers.
59
+ function txt(value, max = MAX_TEXT) {
60
+ let s
61
+ if (typeof value === "string") s = value
62
+ else if (typeof value === "number" && Number.isFinite(value)) s = String(value)
63
+ else if (typeof value === "boolean") s = String(value)
64
+ else return null
65
+ s = s.replace(CTRL, " ").trim()
66
+ if (s.length > max) s = s.slice(0, max) + "…"
67
+ return s
68
+ }
69
+
70
+ // Non-empty text or null.
71
+ function strOrNull(value, max = MAX_TEXT) {
72
+ if (typeof value !== "string") return null
73
+ const s = txt(value, max)
74
+ return s ? s : null
75
+ }
76
+
77
+ function isValidTaskId(taskId) {
78
+ return typeof taskId === "string" && TASK_ID.test(taskId) && !taskId.includes("..")
79
+ }
80
+
81
+ // Defang absolute URLs in text. The HTML output must contain no http(s) URL at
82
+ // all, even when a summary or a pitfall quotes one. "https://" becomes "https[://]".
83
+ function defang(s) {
84
+ return s.replace(/https?:\/\//gi, (m) => m.replace("://", "[://]"))
85
+ }
86
+
87
+ function escapeHtml(s) {
88
+ return String(s).replace(/[&<>"']/g, (c) => HTML_ESC[c])
89
+ }
90
+
91
+ // Escaped HTML text for any dynamic value. Never returns raw user text.
92
+ function h(value, fallback = "—", max = MAX_TEXT) {
93
+ const s = txt(value, max)
94
+ return escapeHtml(s ? defang(s) : fallback)
95
+ }
96
+
97
+ // Escaped GFM text for table cells and list items. Backslash-escapes the
98
+ // characters that would otherwise start Markdown markup or HTML.
99
+ function md(value, fallback = "—", max = MAX_TEXT) {
100
+ const s = txt(value, max)
101
+ if (!s) return fallback
102
+ return s.replace(/[\\`*_[\]<>|~!&]/g, "\\$&")
103
+ }
104
+
105
+ function int(value) {
106
+ if (typeof value !== "number" || !Number.isFinite(value)) return "n/a"
107
+ return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
108
+ }
109
+
110
+ function fmtUsd(value) {
111
+ return typeof value === "number" && Number.isFinite(value) ? `$${value.toFixed(4)}` : "n/a"
112
+ }
113
+
114
+ function fmtDuration(ms) {
115
+ if (typeof ms !== "number" || !Number.isFinite(ms)) return "unknown"
116
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`
117
+ const seconds = ms / 1000
118
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
119
+ const minutes = Math.floor(seconds / 60)
120
+ const rem = Math.round(seconds - minutes * 60)
121
+ return `${minutes}m ${String(rem).padStart(2, "0")}s`
122
+ }
123
+
124
+ function parseTs(value) {
125
+ if (typeof value !== "string") return NaN
126
+ return Date.parse(value)
127
+ }
128
+
129
+ function mib(bytes) {
130
+ const v = bytes / (1024 * 1024)
131
+ return Number.isInteger(v) ? String(v) : v.toFixed(1)
132
+ }
133
+
134
+ // ------------------------------------------------------------ bounded reads
135
+
136
+ // Read a file only if it is a regular file (never follow a symlink) and it is
137
+ // no larger than maxBytes. Returns { status: ok|absent|oversize|unreadable }.
138
+ function readBounded(file, maxBytes) {
139
+ let fd = null
140
+ try {
141
+ if (!lstatSync(file).isFile()) return { status: "unreadable" }
142
+ fd = openSync(file, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0))
143
+ const st = fstatSync(fd)
144
+ if (!st.isFile()) return { status: "unreadable" }
145
+ if (st.size > maxBytes) return { status: "oversize", size: st.size, cap: maxBytes }
146
+ // Read at most maxBytes+1 so a file that grows after fstat stays bounded.
147
+ const cap = Math.min(st.size, maxBytes) + 1
148
+ const buf = Buffer.alloc(cap)
149
+ let total = 0
150
+ while (total < cap) {
151
+ const n = readSync(fd, buf, total, cap - total, null)
152
+ if (n === 0) break
153
+ total += n
154
+ }
155
+ if (total > maxBytes) return { status: "oversize", size: total, cap: maxBytes }
156
+ return { status: "ok", text: buf.subarray(0, total).toString("utf8") }
157
+ } catch (err) {
158
+ return { status: err && err.code === "ENOENT" ? "absent" : "unreadable" }
159
+ } finally {
160
+ if (fd !== null) {
161
+ try {
162
+ closeSync(fd)
163
+ } catch {}
164
+ }
165
+ }
166
+ }
167
+
168
+ function isRealDir(p) {
169
+ try {
170
+ return lstatSync(p).isDirectory()
171
+ } catch {
172
+ return false
173
+ }
174
+ }
175
+
176
+ // True when .opencode or .opencode/teamwork is a symlink: nothing under it may be read.
177
+ function runRootIsLink(projectRoot) {
178
+ for (const p of [join(projectRoot, ".opencode"), join(projectRoot, ".opencode", "teamwork")]) {
179
+ try {
180
+ if (lstatSync(p).isSymbolicLink()) return true
181
+ } catch {}
182
+ }
183
+ return false
184
+ }
185
+
186
+ function oversizeDiag(label, r) {
187
+ return { file: label, message: `${label} exceeds the ${mib(r.cap)} MiB read cap (${mib(r.size)} MiB); it was not read` }
188
+ }
189
+
190
+ function unreadableDiag(label, why = "is not a regular file; it was not read") {
191
+ return { file: label, message: `${label} ${why}` }
192
+ }
193
+
194
+ // Read and parse one JSON object. Absent is silent. Oversize, unreadable or
195
+ // malformed files return null and record a warning.
196
+ function readJson(file, label, diags) {
197
+ const r = readBounded(file, MAX_JSON_BYTES)
198
+ if (r.status === "oversize") {
199
+ diags.push(oversizeDiag(label, r))
200
+ return null
201
+ }
202
+ if (r.status === "unreadable") {
203
+ diags.push(unreadableDiag(label))
204
+ return null
205
+ }
206
+ if (r.status !== "ok") return null
207
+ try {
208
+ const value = JSON.parse(r.text)
209
+ if (isRecord(value)) return value
210
+ } catch {}
211
+ diags.push({ file: label, message: `${label} is not a JSON object; it was ignored` })
212
+ return null
213
+ }
214
+
215
+ // A verify/report-<taskId>.json read. Refuses invalid ids, a symlinked or absent
216
+ // verify/ directory, and any path that would not stay inside the run directory.
217
+ function reportFor(runDir, taskId, verifyOk, diags) {
218
+ if (!verifyOk || !isValidTaskId(taskId)) return null
219
+ const file = join(runDir, "verify", `report-${taskId}.json`)
220
+ const rel = relative(resolve(runDir), resolve(file))
221
+ if (!rel || isAbsolute(rel) || rel.startsWith("..")) return null
222
+ return readJson(file, `verify/report-${taskId}.json`, diags)
223
+ }
224
+
225
+ function readPitfalls(runDir, diags) {
226
+ const r = readBounded(join(runDir, "pitfalls.md"), MAX_PITFALLS_BYTES)
227
+ if (r.status === "oversize") {
228
+ diags.push(oversizeDiag("pitfalls.md", r))
229
+ return []
230
+ }
231
+ if (r.status === "unreadable") {
232
+ diags.push(unreadableDiag("pitfalls.md"))
233
+ return []
234
+ }
235
+ if (r.status !== "ok") return []
236
+ const out = []
237
+ for (const line of r.text.split(/\r?\n/)) {
238
+ const trimmed = line.trimStart()
239
+ if (!trimmed.startsWith("- ")) continue
240
+ const entry = strOrNull(trimmed.slice(2), MAX_PITFALL)
241
+ if (entry) out.push(entry)
242
+ if (out.length >= MAX_PITFALLS) break
243
+ }
244
+ return out
245
+ }
246
+
247
+ // Parse events.jsonl; skip lines that are not usable event objects.
248
+ function readEvents(runDir, diags) {
249
+ const r = readBounded(join(runDir, "events.jsonl"), MAX_EVENTS_BYTES)
250
+ if (r.status === "oversize") {
251
+ diags.push(oversizeDiag("events.jsonl", r))
252
+ return []
253
+ }
254
+ if (r.status === "unreadable") {
255
+ diags.push(unreadableDiag("events.jsonl"))
256
+ return []
257
+ }
258
+ if (r.status !== "ok") return []
259
+ const events = []
260
+ for (const line of r.text.split("\n")) {
261
+ const trimmed = line.trim()
262
+ if (!trimmed) continue
263
+ let obj
264
+ try {
265
+ obj = JSON.parse(trimmed)
266
+ } catch {
267
+ continue // truncated or corrupt line
268
+ }
269
+ if (!isRecord(obj) || typeof obj.event !== "string" || Number.isNaN(parseTs(obj.ts))) continue
270
+ events.push({
271
+ ts: obj.ts,
272
+ tsMs: parseTs(obj.ts),
273
+ seq: Number.isInteger(obj.seq) && obj.seq > 0 ? obj.seq : null,
274
+ event: obj.event,
275
+ taskId: typeof obj.taskId === "string" ? obj.taskId : null,
276
+ to: typeof obj.to === "string" ? obj.to : null,
277
+ round: numberOrNull(obj.round),
278
+ agent: typeof obj.agent === "string" ? obj.agent : null,
279
+ agentSource: obj.agentSource === "explicit" || obj.agentSource === "session" || obj.agentSource === "plan" ? obj.agentSource : null,
280
+ branch: typeof obj.branch === "string" ? obj.branch : null,
281
+ worktree: typeof obj.worktree === "string" ? obj.worktree : null,
282
+ })
283
+ }
284
+ return events
285
+ }
286
+
287
+ // A finite, non-negative token bucket, or null. Only known fields are copied.
288
+ function sanitizeTokenBucket(bucket) {
289
+ if (!isRecord(bucket) || !isRecord(bucket.cache)) return null
290
+ const vals = [bucket.input, bucket.output, bucket.reasoning, bucket.cache.read, bucket.cache.write].map((v) =>
291
+ typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null,
292
+ )
293
+ if (vals.some((v) => v === null)) return null
294
+ const [input, output, reasoning, read, write] = vals
295
+ return { input, output, reasoning, cache: { read, write } }
296
+ }
297
+
298
+ function normStatus(value) {
299
+ if (typeof value !== "string") return null
300
+ const v = value.trim().toUpperCase()
301
+ return v === "PASS" || v === "FAIL" ? v : null
302
+ }
303
+
304
+ // ------------------------------------------------------------ data model
305
+
306
+ function errorData(sessionId, error, diags = []) {
307
+ return {
308
+ error,
309
+ sessionId,
310
+ topology: "unknown",
311
+ phase: "UNKNOWN",
312
+ status: "INCOMPLETE",
313
+ timing: "unknown",
314
+ startedAt: null,
315
+ endedAt: null,
316
+ durationMs: null,
317
+ budgetUsd: null,
318
+ budgetSource: null,
319
+ spentUsd: 0,
320
+ tokens: null,
321
+ tasks: [],
322
+ totals: { tasks: 0, passed: 0, failed: 0, blocked: 0, pending: 0, rounds: 0 },
323
+ unattributed: [],
324
+ security: null,
325
+ finalReport: null,
326
+ terms: { integrityMode: null, preflight: null, finalVerdict: null },
327
+ pitfalls: [],
328
+ warnings: diags.map((d) => d.message),
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Build the export data for one Teamwork run. Never throws.
334
+ * @param {string} projectRoot Project root containing .opencode/teamwork/
335
+ * @param {string} sessionId Run id (validated against the session allowlist)
336
+ */
337
+ export function buildExportData(projectRoot, sessionId) {
338
+ const id = typeof sessionId === "string" && SESSION_ID.test(sessionId) ? sessionId : null
339
+ try {
340
+ if (typeof projectRoot !== "string" || !projectRoot) return errorData(null, "projectRoot must be a non-empty string")
341
+ if (id === null) {
342
+ return errorData(null, "invalid session id: must match ^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$")
343
+ }
344
+ return buildRun(projectRoot, id)
345
+ } catch {
346
+ return errorData(id, "unexpected error while reading the run; nothing was exported")
347
+ }
348
+ }
349
+
350
+ function buildRun(projectRoot, id) {
351
+ const diags = []
352
+ if (runRootIsLink(projectRoot)) {
353
+ return errorData(id, ".opencode/teamwork is a symlink; nothing was read")
354
+ }
355
+ const runDir = join(projectRoot, ".opencode", "teamwork", id)
356
+ if (!isRealDir(runDir)) return errorData(id, `no Teamwork run "${id}" under .opencode/teamwork`)
357
+
358
+ const plan = readJson(join(runDir, "plan.dag.json"), "plan.dag.json", diags)
359
+ const state = readJson(join(runDir, "state.json"), "state.json", diags)
360
+ if (!plan || !state) {
361
+ return errorData(id, "plan.dag.json and state.json are required; one is missing or not a JSON object", diags)
362
+ }
363
+ const costs = readJson(join(runDir, "costs.json"), "costs.json", diags) || {}
364
+ const events = readEvents(runDir, diags)
365
+
366
+ const verifyDir = join(runDir, "verify")
367
+ const verifyOk = isRealDir(verifyDir)
368
+ if (!verifyOk) {
369
+ try {
370
+ if (lstatSync(verifyDir).isSymbolicLink()) diags.push(unreadableDiag("verify/", "is a symlink; verify reports were not read"))
371
+ } catch {}
372
+ }
373
+ const audit = verifyOk ? readJson(join(verifyDir, "security-audit.json"), "verify/security-audit.json", diags) : null
374
+ const final = verifyOk ? readJson(join(verifyDir, "final.json"), "verify/final.json", diags) : null
375
+ const pitfalls = readPitfalls(runDir, diags)
376
+
377
+ // ---- run-level timing: events when present, otherwise unknown
378
+ let startedAt = null
379
+ let endedAt = strOrNull(state.updatedAt, 80)
380
+ let durationMs = null
381
+ let timing = "unknown"
382
+ if (events.length) {
383
+ startedAt = events[0].ts
384
+ endedAt = events[events.length - 1].ts
385
+ durationMs = events[events.length - 1].tsMs - events[0].tsMs
386
+ timing = "events"
387
+ }
388
+
389
+ // ---- task ids: plan order, then state order, then event-only ids
390
+ const planTasks = Array.isArray(plan.tasks) ? plan.tasks.filter(isRecord) : []
391
+ const planById = new Map()
392
+ for (const t of planTasks) if (typeof t.id === "string" && !planById.has(t.id)) planById.set(t.id, t)
393
+ const stateTasks = isRecord(state.tasks) ? state.tasks : {}
394
+ const eventsByTask = new Map()
395
+ for (const ev of events) {
396
+ if (ev.event !== "task_transition" || ev.taskId === null) continue
397
+ if (!eventsByTask.has(ev.taskId)) eventsByTask.set(ev.taskId, [])
398
+ eventsByTask.get(ev.taskId).push(ev)
399
+ }
400
+ const idSet = new Set()
401
+ const taskIds = []
402
+ const addId = (x) => {
403
+ if (typeof x !== "string" || !x || idSet.has(x)) return
404
+ idSet.add(x)
405
+ taskIds.push(x)
406
+ }
407
+ for (const t of planTasks) addId(t.id)
408
+ for (const k of Object.keys(stateTasks)) addId(k)
409
+ for (const k of eventsByTask.keys()) addId(k)
410
+
411
+ const tasks = taskIds.slice(0, MAX_TASKS).map((taskId) =>
412
+ buildTask(taskId, {
413
+ runDir,
414
+ verifyOk,
415
+ diags,
416
+ costs,
417
+ stateTask: own(stateTasks, taskId),
418
+ planTask: planById.get(taskId) ?? null,
419
+ transitions: eventsByTask.get(taskId) || [],
420
+ }),
421
+ )
422
+ if (taskIds.length > MAX_TASKS) diags.push({ file: "state.json", message: `only the first ${MAX_TASKS} tasks were exported` })
423
+
424
+ // ---- cost buckets that are not tasks
425
+ const byTask = isRecord(costs.byTask) ? costs.byTask : {}
426
+ const unattributed = []
427
+ for (const key of Object.keys(byTask)) {
428
+ if (idSet.has(key) && isValidTaskId(key)) continue
429
+ unattributed.push({ bucket: strOrNull(key, 80) ?? "—", costUsd: numberOrNull(byTask[key]) ?? 0 })
430
+ }
431
+
432
+ const security = buildSecurity(audit)
433
+ const finalReport = buildFinal(final)
434
+ const terms = buildTerms(plan, state, final)
435
+ const status = overallStatus(tasks, security, finalReport)
436
+
437
+ const totals = {
438
+ tasks: tasks.length,
439
+ passed: tasks.filter((t) => t.status === "verified_pass").length,
440
+ failed: tasks.filter((t) => t.status === "verified_fail").length,
441
+ blocked: tasks.filter((t) => t.status === "blocked").length,
442
+ pending: 0,
443
+ rounds: tasks.reduce((sum, t) => sum + (t.rounds || 0), 0),
444
+ }
445
+ totals.pending = totals.tasks - totals.passed - totals.failed - totals.blocked
446
+
447
+ return {
448
+ error: null,
449
+ sessionId: id,
450
+ topology: strOrNull(plan.topology, MAX_SHORT) ?? "unknown",
451
+ phase: strOrNull(state.phase, MAX_SHORT) ?? "UNKNOWN",
452
+ status,
453
+ timing,
454
+ startedAt,
455
+ endedAt,
456
+ durationMs,
457
+ budgetUsd: numberOrNull(costs.budgetUsd),
458
+ budgetSource: strOrNull(costs.budgetSource, MAX_SHORT),
459
+ spentUsd: numberOrNull(costs.spentUsd) ?? 0,
460
+ tokens: sanitizeTokenBucket(costs.tokens),
461
+ tasks,
462
+ totals,
463
+ unattributed,
464
+ security,
465
+ finalReport,
466
+ terms,
467
+ pitfalls,
468
+ warnings: diags.map((d) => d.message),
469
+ }
470
+ }
471
+
472
+ function buildTask(taskId, ctx) {
473
+ const { runDir, verifyOk, diags, costs, stateTask, planTask, transitions } = ctx
474
+ const valid = isValidTaskId(taskId)
475
+ const report = reportFor(runDir, taskId, verifyOk, diags)
476
+
477
+ // Event-derived timing and identities.
478
+ let ev = null
479
+ if (transitions.length) {
480
+ const startIdx = 0
481
+ let endIdx = transitions.length - 1
482
+ for (let i = 0; i < transitions.length; i++) {
483
+ if (transitions[i].to === "verified_pass" || transitions[i].to === "blocked") endIdx = i
484
+ }
485
+ let rounds = 0
486
+ let workerAgent = null
487
+ let verifierAgent = null
488
+ let branch = null
489
+ let worktree = null
490
+ for (const t of transitions) {
491
+ if (t.round !== null && t.round > rounds) rounds = t.round
492
+ if (t.agent && (t.to === "worker_active" || t.to === "worker_done")) workerAgent = t.agent
493
+ if (t.agent && (t.to === "verifier_active" || t.to === "verified_pass" || t.to === "verified_fail")) verifierAgent = t.agent
494
+ if (t.branch) branch = t.branch
495
+ if (t.worktree) worktree = t.worktree
496
+ }
497
+ ev = {
498
+ startedAt: transitions[startIdx].ts,
499
+ endedAt: transitions[endIdx].ts,
500
+ durationMs: transitions[endIdx].tsMs - transitions[startIdx].tsMs,
501
+ rounds,
502
+ workerAgent,
503
+ verifierAgent,
504
+ branch,
505
+ worktree,
506
+ }
507
+ }
508
+
509
+ const status = strOrNull(stateTask?.status, MAX_SHORT) ?? strOrNull(planTask?.status, MAX_SHORT) ?? "pending"
510
+
511
+ const verification = isRecord(stateTask?.verification) ? stateTask.verification : null
512
+ let checksPassed = numberOrNull(verification?.passedChecks)
513
+ let checksTotal = numberOrNull(verification?.totalChecks)
514
+ if (checksTotal === null && report && Array.isArray(report.checks)) {
515
+ const checks = report.checks.filter(isRecord)
516
+ checksTotal = checks.length
517
+ checksPassed = checks.filter((c) => c.passed === true).length
518
+ }
519
+
520
+ const fatal = []
521
+ if (verification && Array.isArray(verification.fatalFindings)) {
522
+ for (const f of verification.fatalFindings) {
523
+ const s = strOrNull(f, MAX_TEXT)
524
+ if (s) fatal.push(s)
525
+ }
526
+ }
527
+ if (report && Array.isArray(report.fatalFindings)) {
528
+ for (const f of report.fatalFindings) {
529
+ if (!isRecord(f)) continue
530
+ const s = [strOrNull(f.where, MAX_SHORT), strOrNull(f.why, MAX_TEXT), strOrNull(f.fix, MAX_TEXT)].filter(Boolean).join(" — ")
531
+ if (s) fatal.push(s)
532
+ }
533
+ }
534
+
535
+ const tokenBuckets = isRecord(costs.byTaskTokens) ? costs.byTaskTokens : {}
536
+ const costBuckets = isRecord(costs.byTask) ? costs.byTask : {}
537
+
538
+ const note = [
539
+ ev ? null : "no events.jsonl entries for this task; start and duration unknown",
540
+ valid ? null : "task id failed validation; its verify report was not read",
541
+ ]
542
+ .filter(Boolean)
543
+ .join("; ")
544
+
545
+ return {
546
+ id: taskId,
547
+ valid,
548
+ status,
549
+ workerAgent: ev?.workerAgent ?? strOrNull(planTask?.agent, MAX_SHORT),
550
+ verifierAgent: strOrNull(report?.verifierAgent, MAX_SHORT) ?? ev?.verifierAgent ?? null,
551
+ verifierModel: strOrNull(report?.verifierModel, MAX_SHORT),
552
+ rounds: Math.max(numberOrNull(stateTask?.round) ?? 0, numberOrNull(planTask?.round) ?? 0, ev?.rounds ?? 0),
553
+ branch: strOrNull(stateTask?.branch, MAX_SHORT) ?? ev?.branch ?? null,
554
+ worktree: strOrNull(stateTask?.worktree, MAX_SHORT) ?? ev?.worktree ?? null,
555
+ summary: strOrNull(stateTask?.summary) ?? null,
556
+ feedback: strOrNull(stateTask?.feedback) ?? strOrNull(report?.feedbackForWorker) ?? null,
557
+ fatalFindings: fatal.slice(0, MAX_FATAL),
558
+ verificationStatus: normStatus(verification?.status) ?? normStatus(report?.status),
559
+ checksPassed,
560
+ checksTotal,
561
+ startedAt: ev?.startedAt ?? null,
562
+ endedAt: ev ? ev.endedAt : strOrNull(stateTask?.updatedAt, 80),
563
+ durationMs: ev ? ev.durationMs : null,
564
+ costUsd: Object.prototype.hasOwnProperty.call(costBuckets, taskId) ? numberOrNull(costBuckets[taskId]) : null,
565
+ tokens: Object.prototype.hasOwnProperty.call(tokenBuckets, taskId) ? sanitizeTokenBucket(tokenBuckets[taskId]) : null,
566
+ note: note || null,
567
+ }
568
+ }
569
+
570
+ function buildSecurity(raw) {
571
+ if (!raw) return null
572
+ const findings = Array.isArray(raw.findings)
573
+ ? raw.findings
574
+ .filter(isRecord)
575
+ .slice(0, MAX_FINDINGS)
576
+ .map((f) => ({
577
+ id: strOrNull(f.id, 80) ?? "—",
578
+ severity: strOrNull(f.severity, 32) ?? "—",
579
+ location: strOrNull(f.location, MAX_SHORT),
580
+ description: strOrNull(f.description, MAX_TEXT) ?? "—",
581
+ }))
582
+ : []
583
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 }
584
+ if (isRecord(raw.severityCounts) && SEVERITIES.some((k) => numberOrNull(raw.severityCounts[k]) !== null)) {
585
+ for (const k of SEVERITIES) counts[k] = nonNegInt(raw.severityCounts[k])
586
+ } else {
587
+ for (const f of findings) {
588
+ const k = f.severity.toLowerCase()
589
+ if (SEVERITIES.includes(k)) counts[k]++
590
+ }
591
+ }
592
+ return {
593
+ status: normStatus(raw.status),
594
+ timestamp: strOrNull(raw.timestamp, 80),
595
+ summary: strOrNull(raw.summary, MAX_TEXT),
596
+ counts,
597
+ findings,
598
+ }
599
+ }
600
+
601
+ function buildFinal(raw) {
602
+ if (!raw) return null
603
+ let checksPassed = numberOrNull(raw.passedChecks)
604
+ let checksTotal = numberOrNull(raw.totalChecks)
605
+ if (checksTotal === null && Array.isArray(raw.checks)) {
606
+ const checks = raw.checks.filter(isRecord)
607
+ checksTotal = checks.length
608
+ checksPassed = checks.filter((c) => c.passed === true).length
609
+ }
610
+ return {
611
+ status: normStatus(raw.status),
612
+ timestamp: strOrNull(raw.timestamp, 80),
613
+ summary: strOrNull(raw.summary, MAX_TEXT),
614
+ checksPassed,
615
+ checksTotal,
616
+ }
617
+ }
618
+
619
+ // plan.dag.json.preflight: a known status and an explicit bypass flag, or null.
620
+ function buildPreflightTerms(raw) {
621
+ if (!isRecord(raw)) return null
622
+ const status = typeof raw.status === "string" ? raw.status.trim().toUpperCase() : ""
623
+ if (!PREFLIGHT_STATUSES.includes(status)) return null
624
+ return { status, bypassed: raw.bypassed === true }
625
+ }
626
+
627
+ // verify/final.json provenance. `stamped` mirrors the engine's definition: a
628
+ // usable generatedBy.session, generatedAt and evidence object. A report without
629
+ // those is a legacy hand-written verdict and is shown as UNSTAMPED.
630
+ function buildFinalVerdict(raw) {
631
+ if (!isRecord(raw)) return null
632
+ const by = isRecord(raw.generatedBy) ? raw.generatedBy : null
633
+ const agent = strOrNull(by?.agent, MAX_SHORT)
634
+ const session = strOrNull(by?.session, MAX_SHORT)
635
+ const generatedAt = strOrNull(raw.generatedAt, 80)
636
+ const stamped =
637
+ typeof raw.stamped === "boolean" ? raw.stamped : !!session && !!generatedAt && isRecord(raw.evidence)
638
+ return {
639
+ status: strOrNull(raw.status, 32),
640
+ stamped,
641
+ generatedBy: by ? { agent, session } : null,
642
+ generatedAt,
643
+ integrityMode: strOrNull(raw.integrityMode, 32),
644
+ }
645
+ }
646
+
647
+ function buildTerms(plan, state, final) {
648
+ return {
649
+ integrityMode: strOrNull(plan.integrityMode, 32) ?? strOrNull(state.integrityMode, 32) ?? null,
650
+ preflight: buildPreflightTerms(plan.preflight),
651
+ finalVerdict: final ? buildFinalVerdict(final) : null,
652
+ }
653
+ }
654
+
655
+ // Guard terms supplied by a hand-built data object; already-derived terms keep
656
+ // their computed `stamped` flag instead of being re-derived without evidence.
657
+ function sanitizeTerms(raw) {
658
+ if (!isRecord(raw)) return { integrityMode: null, preflight: null, finalVerdict: null }
659
+ return {
660
+ integrityMode: strOrNull(raw.integrityMode, 32),
661
+ preflight: buildPreflightTerms(raw.preflight),
662
+ finalVerdict: buildFinalVerdict(raw.finalVerdict),
663
+ }
664
+ }
665
+
666
+ // PASS only when every task verified, the audit did not FAIL, and nothing is blocked
667
+ // or failed. FAIL on any hard failure. Anything else is INCOMPLETE.
668
+ function overallStatus(tasks, security, finalReport) {
669
+ const anyBad = tasks.some((t) => t.status === "blocked" || t.status === "verified_fail")
670
+ const secFail = !!security && (security.status === "FAIL" || security.counts.critical > 0 || security.counts.high > 0)
671
+ if (anyBad || secFail || finalReport?.status === "FAIL") return "FAIL"
672
+ if (finalReport?.status === "PASS") return "PASS"
673
+ if (tasks.length > 0 && tasks.every((t) => t.status === "verified_pass") && (!security || security.status === "PASS")) return "PASS"
674
+ return "INCOMPLETE"
675
+ }
676
+
677
+ // ------------------------------------------------------------ rendering
678
+
679
+ const BADGE = {
680
+ PASS: ["b-pass", "PASS"],
681
+ FAIL: ["b-fail", "FAIL"],
682
+ BLOCKED: ["b-blocked", "BLOCKED"],
683
+ INCOMPLETE: ["b-wait", "INCOMPLETE"],
684
+ }
685
+
686
+ function badgeLabel(status) {
687
+ if (status === "verified_pass") return "PASS"
688
+ if (status === "verified_fail") return "FAIL"
689
+ if (status === "blocked") return "BLOCKED"
690
+ return String(status ?? "pending").replace(/_/g, " ").toUpperCase()
691
+ }
692
+
693
+ function badgeClass(label) {
694
+ if (BADGE[label]) return BADGE[label][0]
695
+ if (label === "PENDING") return "b-wait"
696
+ return "b-other"
697
+ }
698
+
699
+ function badgeHtml(label) {
700
+ const text = h(label, "UNKNOWN", MAX_SHORT)
701
+ return `<span class="badge ${badgeClass(label)}">${text}</span>`
702
+ }
703
+
704
+ function taskStatusLabel(task) {
705
+ return badgeLabel(task.status)
706
+ }
707
+
708
+ const CSS = `:root{color-scheme:light dark;--bg:#f6f7f9;--fg:#1b1f24;--muted:#5b6470;--card:#fff;--line:#d8dde3;--code:#eef1f4;--pass:#15803d;--fail:#b91c1c;--block:#b45309;--wait:#475569;--info:#1d4ed8}
709
+ @media (prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#9aa4af;--card:#161b22;--line:#30363d;--code:#21262d;--pass:#3fb950;--fail:#f85149;--block:#d29922;--wait:#8b949e;--info:#58a6ff}}
710
+ *{box-sizing:border-box}
711
+ body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif}
712
+ .wrap{max-width:1100px;margin:0 auto;padding:24px 16px 48px}
713
+ h1{font-size:22px;margin:0 0 4px}
714
+ h2{font-size:17px;margin:28px 0 10px;border-bottom:1px solid var(--line);padding-bottom:6px}
715
+ h4{margin:10px 0 4px;font-size:13px;color:var(--muted)}
716
+ .sub{color:var(--muted);margin:0 0 16px}
717
+ code{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:var(--code);padding:1px 5px;border-radius:4px;word-break:break-all}
718
+ .card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:16px}
719
+ .warn{border-left:4px solid var(--block)}
720
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px 20px;margin:0}
721
+ .grid dt{color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}
722
+ .grid dd{margin:2px 0 0;font-weight:500;overflow-wrap:anywhere}
723
+ .badge{display:inline-block;padding:2px 9px;border-radius:999px;font-size:12px;font-weight:700;letter-spacing:.03em;color:#fff;white-space:nowrap}
724
+ .b-pass{background:var(--pass)}.b-fail{background:var(--fail)}.b-blocked{background:var(--block)}.b-wait{background:var(--wait)}.b-other{background:var(--info)}
725
+ .scroll{overflow-x:auto}
726
+ table{width:100%;border-collapse:collapse;background:var(--card);border:1px solid var(--line);border-radius:10px}
727
+ th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:break-word}
728
+ th{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;background:var(--code);white-space:nowrap}
729
+ tr:last-child td{border-bottom:0}
730
+ .tasks{min-width:760px}
731
+ .tasks th:first-child,.tasks td:first-child{width:100%;min-width:240px}
732
+ .tasks th:not(:first-child),.tasks td:not(:first-child){white-space:nowrap}
733
+ .num{text-align:right;white-space:nowrap}
734
+ .muted{color:var(--muted)}
735
+ details{margin-top:6px}
736
+ summary{cursor:pointer;color:var(--info)}
737
+ .txt{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--code);padding:8px;border-radius:6px;margin:4px 0}
738
+ .sev td{text-align:center;font-size:18px;font-weight:600}
739
+ ul{padding-left:20px;margin:6px 0}
740
+ li{margin:4px 0;overflow-wrap:anywhere}
741
+ footer{margin-top:32px;color:var(--muted);font-size:12px}
742
+ @media print{body{background:#fff;color:#000}.card,table{box-shadow:none;border-color:#999}.wrap{max-width:none}details{page-break-inside:avoid}details[open]{display:block}summary{color:#000}}`
743
+
744
+ function fmtTokensHtml(t) {
745
+ if (!t) return "n/a"
746
+ return `in ${int(t.input)} · out ${int(t.output)} · reasoning ${int(t.reasoning)} · cache read ${int(t.cache.read)} / write ${int(t.cache.write)}`
747
+ }
748
+
749
+ function fmtTokensMd(t) {
750
+ if (!t) return "n/a"
751
+ return `in ${int(t.input)} / out ${int(t.output)} / reasoning ${int(t.reasoning)} / cache read ${int(t.cache.read)} / write ${int(t.cache.write)}`
752
+ }
753
+
754
+ function preflightLabel(preflight) {
755
+ if (!preflight) return "not recorded"
756
+ return preflight.bypassed ? `${preflight.status} (bypassed)` : preflight.status
757
+ }
758
+
759
+ function verdictActors(v) {
760
+ return [v.generatedBy?.agent, v.generatedBy?.session].filter((x) => typeof x === "string" && x)
761
+ }
762
+
763
+ function finalVerdictHtml(v) {
764
+ if (!v) return `<span class="muted">not produced</span>`
765
+ if (!v.stamped) return `<span class="badge b-blocked">UNSTAMPED</span> <span class="muted">(legacy verdict)</span>`
766
+ const who = verdictActors(v)
767
+ const by = who.length ? h(who.join(" / "), "unknown", MAX_SHORT) : "unknown"
768
+ return `stamped by ${by}${v.generatedAt ? ` at ${h(v.generatedAt, "", 80)}` : ""}`
769
+ }
770
+
771
+ function finalVerdictMd(v) {
772
+ if (!v) return "not produced"
773
+ if (!v.stamped) return "UNSTAMPED (legacy)"
774
+ const who = verdictActors(v)
775
+ const by = who.length ? who.map((x) => md(x, "", MAX_SHORT)).join(" / ") : "unknown"
776
+ return `stamped by ${by}${v.generatedAt ? ` at ${md(v.generatedAt, "", 80)}` : ""}`
777
+ }
778
+
779
+ function renderHtml(d) {
780
+ const title = d.error ? "Teamwork run report (error)" : `Teamwork run ${h(d.sessionId, "unknown", MAX_SHORT)}`
781
+ const out = []
782
+ out.push(`<!DOCTYPE html>
783
+ <html lang="en">
784
+ <head>
785
+ <meta charset="utf-8">
786
+ <meta name="viewport" content="width=device-width, initial-scale=1">
787
+ <meta name="color-scheme" content="light dark">
788
+ <title>${title}</title>
789
+ <style>${CSS}</style>
790
+ </head>
791
+ <body>
792
+ <main class="wrap">
793
+ <header>
794
+ <h1>${title}</h1>
795
+ <p class="sub">Offline Teamwork run report, generated read-only from the run directory.</p>
796
+ </header>`)
797
+
798
+ if (d.error) {
799
+ out.push(`<section class="card warn"><h2>Export refused</h2><p>${h(d.error, "unknown error")}</p></section>`)
800
+ } else {
801
+ const timingLine =
802
+ d.timing === "events"
803
+ ? `${h(d.startedAt, "unknown", 80)} → ${h(d.endedAt, "unknown", 80)}`
804
+ : `timing unknown (no events.jsonl); last update ${h(d.endedAt, "unknown", 80)}`
805
+ out.push(`<section class="card" aria-label="Summary"><dl class="grid">
806
+ <div><dt>Session ID</dt><dd><code>${h(d.sessionId, "unknown", MAX_SHORT)}</code></dd></div>
807
+ <div><dt>Topology</dt><dd>${h(d.topology, "unknown", MAX_SHORT)}</dd></div>
808
+ <div><dt>Status</dt><dd>${badgeHtml(d.status)}</dd></div>
809
+ <div><dt>Phase</dt><dd>${h(d.phase, "UNKNOWN", MAX_SHORT)}</dd></div>
810
+ <div><dt>Duration</dt><dd>${fmtDuration(d.durationMs)}<br><span class="muted">${timingLine}</span></dd></div>
811
+ <div><dt>Budget vs spent</dt><dd>${fmtUsd(d.budgetUsd)} budget · ${fmtUsd(d.spentUsd)} spent${
812
+ d.budgetSource ? ` <span class="muted">(${h(d.budgetSource, "", MAX_SHORT)})</span>` : ""
813
+ }</dd></div>
814
+ <div><dt>Total tokens</dt><dd>${fmtTokensHtml(d.tokens)}</dd></div>
815
+ <div><dt>Tasks</dt><dd>${d.totals.tasks} total · ${d.totals.passed} passed · ${d.totals.failed} failed · ${d.totals.blocked} blocked · ${d.totals.pending} open</dd></div>
816
+ </dl></section>`)
817
+
818
+ out.push(`<h2>Run terms</h2><section class="card" aria-label="Run terms"><dl class="grid">
819
+ <div><dt>Integrity mode</dt><dd>${h(d.terms.integrityMode, "not recorded", 32)}</dd></div>
820
+ <div><dt>Preflight</dt><dd>${h(preflightLabel(d.terms.preflight), "not recorded", MAX_SHORT)}</dd></div>
821
+ <div><dt>Final verdict</dt><dd>${finalVerdictHtml(d.terms.finalVerdict)}</dd></div>
822
+ </dl></section>`)
823
+
824
+ out.push(`<h2>Tasks</h2>`)
825
+ out.push(`<div class="scroll"><table class="tasks"><thead><tr><th>Task</th><th>Status</th><th>Worker</th><th>Verifier</th><th class="num">Rounds</th><th>Duration</th><th class="num">Cost</th><th class="num">Checks</th></tr></thead><tbody>`)
826
+ if (!d.tasks.length) out.push(`<tr><td colspan="8" class="muted">No tasks recorded.</td></tr>`)
827
+ for (const t of d.tasks) {
828
+ const label = taskStatusLabel(t)
829
+ const checks = t.checksTotal !== null ? `${int(t.checksPassed ?? 0)}/${int(t.checksTotal)}` : "n/a"
830
+ const verifierModel = t.verifierModel ? `<br><span class="muted">${h(t.verifierModel, "", MAX_SHORT)}</span>` : ""
831
+ out.push(`<tr>
832
+ <td><strong>${h(t.id, "—", MAX_SHORT)}</strong>${t.note ? `<br><span class="muted">${h(t.note, "", MAX_TEXT)}</span>` : ""}
833
+ <details><summary>Feedback &amp; summary</summary>
834
+ <h4>Summary</h4><div class="txt">${h(t.summary, "none recorded")}</div>
835
+ <h4>Feedback</h4><div class="txt">${h(t.feedback, "none")}</div>
836
+ ${t.fatalFindings.length ? `<h4>Fatal findings</h4><ul>${t.fatalFindings.map((f) => `<li>${h(f, "", MAX_TEXT)}</li>`).join("")}</ul>` : ""}
837
+ <h4>Branch</h4><div class="txt">${h(t.branch, "n/a", MAX_SHORT)}</div>
838
+ <h4>Worktree</h4><div class="txt">${h(t.worktree, "n/a", MAX_SHORT)}</div>
839
+ </details></td>
840
+ <td>${badgeHtml(label)}</td>
841
+ <td>${h(t.workerAgent, "unknown", MAX_SHORT)}</td>
842
+ <td>${h(t.verifierAgent, "unknown", MAX_SHORT)}${verifierModel}</td>
843
+ <td class="num">${int(t.rounds)}</td>
844
+ <td>${fmtDuration(t.durationMs)}</td>
845
+ <td class="num">${fmtUsd(t.costUsd)}</td>
846
+ <td class="num">${checks}</td>
847
+ </tr>`)
848
+ }
849
+ out.push(`</tbody></table></div>`)
850
+
851
+ out.push(`<h2>Security audit</h2><section class="card">`)
852
+ if (!d.security) {
853
+ out.push(`<p>Pre-merge status: ${badgeHtml("NOT RUN")}</p><p class="muted">No verify/security-audit.json was found.</p>`)
854
+ } else {
855
+ const s = d.security
856
+ const sLabel = s.status ?? "UNKNOWN"
857
+ out.push(`<p>Pre-merge status: ${badgeHtml(sLabel)} <span class="muted">${h(s.timestamp, "", 80)}</span></p>`)
858
+ out.push(`<div class="scroll"><table class="sev"><thead><tr><th>Critical</th><th>High</th><th>Medium</th><th>Low</th></tr></thead><tbody><tr><td>${int(s.counts.critical)}</td><td>${int(s.counts.high)}</td><td>${int(s.counts.medium)}</td><td>${int(s.counts.low)}</td></tr></tbody></table></div>`)
859
+ if (s.summary) out.push(`<p>${h(s.summary)}</p>`)
860
+ if (s.findings.length) {
861
+ out.push(`<div class="scroll"><table><thead><tr><th>ID</th><th>Severity</th><th>Location</th><th>Description</th></tr></thead><tbody>`)
862
+ for (const f of s.findings) {
863
+ out.push(`<tr><td>${h(f.id)}</td><td>${h(f.severity)}</td><td>${h(f.location, "—", MAX_SHORT)}</td><td>${h(f.description)}</td></tr>`)
864
+ }
865
+ out.push(`</tbody></table></div>`)
866
+ } else {
867
+ out.push(`<p class="muted">No findings recorded.</p>`)
868
+ }
869
+ }
870
+ out.push(`</section>`)
871
+
872
+ if (d.finalReport) {
873
+ const f = d.finalReport
874
+ out.push(`<h2>Final verification</h2><section class="card"><p>Status: ${badgeHtml(f.status ?? "UNKNOWN")} · checks ${f.checksPassed === null ? "n/a" : int(f.checksPassed)}/${f.checksTotal === null ? "n/a" : int(f.checksTotal)}</p>${f.summary ? `<p>${h(f.summary)}</p>` : ""}</section>`)
875
+ }
876
+
877
+ out.push(`<h2>Pitfalls</h2><section class="card">`)
878
+ if (d.pitfalls.length) {
879
+ out.push(`<ul>${d.pitfalls.map((p) => `<li>${h(p, "", MAX_PITFALL)}</li>`).join("")}</ul>`)
880
+ } else {
881
+ out.push(`<p class="muted">No pitfalls recorded.</p>`)
882
+ }
883
+ out.push(`</section>`)
884
+
885
+ if (d.unattributed.length) {
886
+ out.push(`<h2>Other cost buckets</h2><div class="scroll"><table><thead><tr><th>Bucket</th><th class="num">Cost</th></tr></thead><tbody>`)
887
+ for (const u of d.unattributed) out.push(`<tr><td>${h(u.bucket, "—", 80)}</td><td class="num">${fmtUsd(u.costUsd)}</td></tr>`)
888
+ out.push(`</tbody></table></div>`)
889
+ }
890
+ }
891
+
892
+ if (d.warnings.length) {
893
+ out.push(`<h2>Warnings</h2><section class="card warn"><ul>${d.warnings.map((w) => `<li>${h(w, "", MAX_SHORT)}</li>`).join("")}</ul></section>`)
894
+ }
895
+
896
+ out.push(`<footer>Generated by opencode-teamwork export. Single file: no scripts, no external resources.</footer>
897
+ </main>
898
+ </body>
899
+ </html>
900
+ `)
901
+ return out.join("\n")
902
+ }
903
+
904
+ function renderMarkdown(d) {
905
+ const out = []
906
+ if (d.error) {
907
+ out.push("# Teamwork run report", "", `> **Error:** ${md(d.error, "unknown error")}`, "")
908
+ for (const w of d.warnings) out.push(`- ${md(w, "", MAX_SHORT)}`)
909
+ return out.join("\n") + "\n"
910
+ }
911
+
912
+ out.push(`# Teamwork run report: ${md(d.sessionId, "unknown", MAX_SHORT)}`, "")
913
+ out.push("## Summary", "")
914
+ out.push("| Field | Value |", "|---|---|")
915
+ out.push(`| Session ID | ${md(d.sessionId, "unknown", MAX_SHORT)} |`)
916
+ out.push(`| Topology | ${md(d.topology, "unknown", MAX_SHORT)} |`)
917
+ out.push(`| Status | **${md(d.status, "UNKNOWN", MAX_SHORT)}** |`)
918
+ out.push(`| Phase | ${md(d.phase, "UNKNOWN", MAX_SHORT)} |`)
919
+ out.push(`| Duration | ${fmtDuration(d.durationMs)}${d.timing === "events" ? ` (${md(d.startedAt, "unknown", 80)} → ${md(d.endedAt, "unknown", 80)})` : " (timing unknown: no events.jsonl)"} |`)
920
+ out.push(`| Budget | ${fmtUsd(d.budgetUsd)}${d.budgetSource ? ` (${md(d.budgetSource, "", MAX_SHORT)})` : ""} |`)
921
+ out.push(`| Spent | ${fmtUsd(d.spentUsd)} |`)
922
+ out.push(`| Total tokens | ${fmtTokensMd(d.tokens)} |`)
923
+ out.push(`| Tasks | ${d.totals.tasks} total, ${d.totals.passed} passed, ${d.totals.failed} failed, ${d.totals.blocked} blocked, ${d.totals.pending} open |`)
924
+ out.push("")
925
+
926
+ out.push("## Run terms", "")
927
+ out.push(`- **Integrity mode:** ${md(d.terms.integrityMode, "not recorded", 32)}`)
928
+ out.push(`- **Preflight:** ${md(preflightLabel(d.terms.preflight), "not recorded", MAX_SHORT)}`)
929
+ out.push(`- **Final verdict:** ${finalVerdictMd(d.terms.finalVerdict)}`)
930
+ out.push("")
931
+
932
+ out.push("## Tasks", "")
933
+ out.push("| Task | Status | Worker | Verifier | Rounds | Duration | Cost | Checks |", "|---|---|---|---|---:|---:|---:|---:|")
934
+ if (!d.tasks.length) out.push("| _none_ | | | | | | | |")
935
+ for (const t of d.tasks) {
936
+ const checks = t.checksTotal !== null ? `${int(t.checksPassed ?? 0)}/${int(t.checksTotal)}` : "n/a"
937
+ out.push(
938
+ `| ${md(t.id, "—", MAX_SHORT)} | ${md(taskStatusLabel(t), "UNKNOWN", MAX_SHORT)} | ${md(t.workerAgent, "unknown", MAX_SHORT)} | ${md(t.verifierAgent, "unknown", MAX_SHORT)} | ${int(t.rounds)} | ${fmtDuration(t.durationMs)} | ${fmtUsd(t.costUsd)} | ${checks} |`,
939
+ )
940
+ }
941
+ out.push("")
942
+
943
+ out.push("## Acceptance checklist", "")
944
+ if (!d.tasks.length) out.push("- [ ] No tasks recorded")
945
+ for (const t of d.tasks) {
946
+ const done = t.status === "verified_pass"
947
+ out.push(`- [${done ? "x" : " "}] ${md(t.id, "—", MAX_SHORT)}: ${md(taskStatusLabel(t), "UNKNOWN", MAX_SHORT)}${done ? ` (round ${int(t.rounds)})` : ""}`)
948
+ }
949
+ const secPass = !!d.security && d.security.status === "PASS"
950
+ out.push(`- [${secPass ? "x" : " "}] Security audit gate: ${md(d.security ? d.security.status : null, "NOT RUN", MAX_SHORT)}`)
951
+ out.push("")
952
+
953
+ out.push("## Task details", "")
954
+ if (!d.tasks.length) out.push("_No task details._", "")
955
+ for (const t of d.tasks) {
956
+ out.push(`### ${md(t.id, "—", MAX_SHORT)}`, "")
957
+ out.push(`- **Branch:** ${md(t.branch, "n/a", MAX_SHORT)}`)
958
+ out.push(`- **Summary:** ${md(t.summary, "none recorded")}`)
959
+ out.push(`- **Feedback:** ${md(t.feedback, "none")}`)
960
+ if (t.verifierModel) out.push(`- **Verifier model:** ${md(t.verifierModel, "", MAX_SHORT)}`)
961
+ if (t.tokens) out.push(`- **Tokens:** ${fmtTokensMd(t.tokens)}`)
962
+ if (t.note) out.push(`- **Note:** ${md(t.note, "", MAX_TEXT)}`)
963
+ for (const f of t.fatalFindings) out.push(`- **Fatal:** ${md(f, "", MAX_TEXT)}`)
964
+ out.push("")
965
+ }
966
+
967
+ out.push("## Security audit", "")
968
+ if (!d.security) {
969
+ out.push("Pre-merge status: **NOT RUN** (no verify/security-audit.json).", "")
970
+ } else {
971
+ const s = d.security
972
+ out.push(`Pre-merge status: **${md(s.status, "UNKNOWN", MAX_SHORT)}**${s.timestamp ? ` (${md(s.timestamp, "", 80)})` : ""}`, "")
973
+ out.push("| Critical | High | Medium | Low |", "|---:|---:|---:|---:|")
974
+ out.push(`| ${int(s.counts.critical)} | ${int(s.counts.high)} | ${int(s.counts.medium)} | ${int(s.counts.low)} |`, "")
975
+ if (s.summary) out.push(md(s.summary), "")
976
+ if (s.findings.length) {
977
+ for (const f of s.findings) {
978
+ out.push(`- **${md(f.id, "—", 80)}** (${md(f.severity, "—", 32)}) at ${md(f.location, "—", MAX_SHORT)}: ${md(f.description)}`)
979
+ }
980
+ } else {
981
+ out.push("_No findings recorded._")
982
+ }
983
+ out.push("")
984
+ }
985
+
986
+ if (d.finalReport) {
987
+ const f = d.finalReport
988
+ out.push("## Final verification", "")
989
+ out.push(`Status: **${md(f.status, "UNKNOWN", MAX_SHORT)}**, checks ${f.checksPassed === null ? "n/a" : int(f.checksPassed)}/${f.checksTotal === null ? "n/a" : int(f.checksTotal)}`, "")
990
+ if (f.summary) out.push(md(f.summary), "")
991
+ }
992
+
993
+ out.push("## Pitfalls", "")
994
+ if (d.pitfalls.length) {
995
+ for (const p of d.pitfalls) out.push(`- ${md(p, "", MAX_PITFALL)}`)
996
+ } else {
997
+ out.push("_No pitfalls recorded._")
998
+ }
999
+ out.push("")
1000
+
1001
+ if (d.warnings.length) {
1002
+ out.push("## Warnings", "")
1003
+ for (const w of d.warnings) out.push(`- ${md(w, "", MAX_SHORT)}`)
1004
+ out.push("")
1005
+ }
1006
+
1007
+ return out.join("\n")
1008
+ }
1009
+
1010
+ /**
1011
+ * Render export data as one document. Pure: no I/O, no clock.
1012
+ * format "markdown" gives GitHub-flavoured Markdown; anything else (including
1013
+ * undefined) gives the single-file HTML document.
1014
+ * @param {object} data From buildExportData (or an error object)
1015
+ * @param {{format?: string}} [options]
1016
+ * @returns {string}
1017
+ */
1018
+ export function renderExport(data, options = {}) {
1019
+ const format = options && options.format === "markdown" ? "markdown" : "html"
1020
+ const d = isRecord(data) ? normalize(data) : errorData(null, "no export data was provided")
1021
+ return format === "markdown" ? renderMarkdown(d) : renderHtml(d)
1022
+ }
1023
+
1024
+ // Guard the shape so a hand-built data object cannot break the renderers.
1025
+ function normalize(data) {
1026
+ if (data.error) {
1027
+ return { ...errorData(strOrNull(data.sessionId, MAX_SHORT), txt(data.error, MAX_SHORT) ?? "unknown error"), warnings: arr(data.warnings).map((w) => txt(w, MAX_SHORT)).filter(Boolean) }
1028
+ }
1029
+ const tasks = arr(data.tasks).filter(isRecord).map((t) => ({
1030
+ id: strOrNull(t.id, MAX_SHORT) ?? "—",
1031
+ valid: isValidTaskId(t.id),
1032
+ status: strOrNull(t.status, MAX_SHORT) ?? "pending",
1033
+ workerAgent: strOrNull(t.workerAgent, MAX_SHORT),
1034
+ verifierAgent: strOrNull(t.verifierAgent, MAX_SHORT),
1035
+ verifierModel: strOrNull(t.verifierModel, MAX_SHORT),
1036
+ rounds: nonNegInt(t.rounds),
1037
+ branch: strOrNull(t.branch, MAX_SHORT),
1038
+ worktree: strOrNull(t.worktree, MAX_SHORT),
1039
+ summary: strOrNull(t.summary),
1040
+ feedback: strOrNull(t.feedback),
1041
+ fatalFindings: arr(t.fatalFindings).map((f) => strOrNull(f)).filter(Boolean).slice(0, MAX_FATAL),
1042
+ checksPassed: numberOrNull(t.checksPassed),
1043
+ checksTotal: numberOrNull(t.checksTotal),
1044
+ startedAt: strOrNull(t.startedAt, 80),
1045
+ endedAt: strOrNull(t.endedAt, 80),
1046
+ durationMs: numberOrNull(t.durationMs),
1047
+ costUsd: numberOrNull(t.costUsd),
1048
+ tokens: sanitizeTokenBucket(t.tokens),
1049
+ note: strOrNull(t.note),
1050
+ }))
1051
+ const sec = isRecord(data.security) ? data.security : null
1052
+ const fin = isRecord(data.finalReport) ? data.finalReport : null
1053
+ const totals = isRecord(data.totals) ? data.totals : {}
1054
+ return {
1055
+ error: null,
1056
+ sessionId: strOrNull(data.sessionId, MAX_SHORT),
1057
+ topology: strOrNull(data.topology, MAX_SHORT) ?? "unknown",
1058
+ phase: strOrNull(data.phase, MAX_SHORT) ?? "UNKNOWN",
1059
+ status: strOrNull(data.status, MAX_SHORT) ?? "INCOMPLETE",
1060
+ timing: data.timing === "events" ? "events" : "unknown",
1061
+ startedAt: strOrNull(data.startedAt, 80),
1062
+ endedAt: strOrNull(data.endedAt, 80),
1063
+ durationMs: numberOrNull(data.durationMs),
1064
+ budgetUsd: numberOrNull(data.budgetUsd),
1065
+ budgetSource: strOrNull(data.budgetSource, MAX_SHORT),
1066
+ spentUsd: numberOrNull(data.spentUsd) ?? 0,
1067
+ tokens: sanitizeTokenBucket(data.tokens),
1068
+ tasks,
1069
+ totals: {
1070
+ tasks: tasks.length,
1071
+ passed: tasks.filter((t) => t.status === "verified_pass").length,
1072
+ failed: tasks.filter((t) => t.status === "verified_fail").length,
1073
+ blocked: tasks.filter((t) => t.status === "blocked").length,
1074
+ pending: 0,
1075
+ rounds: nonNegInt(totals.rounds),
1076
+ },
1077
+ unattributed: arr(data.unattributed)
1078
+ .filter(isRecord)
1079
+ .map((u) => ({ bucket: strOrNull(u.bucket, 80) ?? "—", costUsd: numberOrNull(u.costUsd) ?? 0 })),
1080
+ security: sec
1081
+ ? {
1082
+ status: normStatus(sec.status),
1083
+ timestamp: strOrNull(sec.timestamp, 80),
1084
+ summary: strOrNull(sec.summary),
1085
+ counts: {
1086
+ critical: nonNegInt(sec.counts?.critical),
1087
+ high: nonNegInt(sec.counts?.high),
1088
+ medium: nonNegInt(sec.counts?.medium),
1089
+ low: nonNegInt(sec.counts?.low),
1090
+ },
1091
+ findings: arr(sec.findings)
1092
+ .filter(isRecord)
1093
+ .slice(0, MAX_FINDINGS)
1094
+ .map((f) => ({
1095
+ id: strOrNull(f.id, 80) ?? "—",
1096
+ severity: strOrNull(f.severity, 32) ?? "—",
1097
+ location: strOrNull(f.location, MAX_SHORT),
1098
+ description: strOrNull(f.description) ?? "—",
1099
+ })),
1100
+ }
1101
+ : null,
1102
+ finalReport: fin
1103
+ ? {
1104
+ status: normStatus(fin.status),
1105
+ timestamp: strOrNull(fin.timestamp, 80),
1106
+ summary: strOrNull(fin.summary),
1107
+ checksPassed: numberOrNull(fin.checksPassed),
1108
+ checksTotal: numberOrNull(fin.checksTotal),
1109
+ }
1110
+ : null,
1111
+ terms: sanitizeTerms(data.terms),
1112
+ pitfalls: arr(data.pitfalls).map((p) => strOrNull(p, MAX_PITFALL)).filter(Boolean).slice(0, MAX_PITFALLS),
1113
+ warnings: arr(data.warnings).map((w) => txt(w, MAX_SHORT)).filter(Boolean),
1114
+ }
1115
+ }
1116
+
1117
+ function arr(value) {
1118
+ return Array.isArray(value) ? value : []
1119
+ }