@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,540 @@
1
+ // @heretek-ai/opencode-teamwork-v2 — run export test suite
2
+ //
3
+ // Hermetic, zero-dependency coverage for `lib/export.mjs` and the
4
+ // `opencode-teamwork export` CLI. Every fixture is a synthetic run directory
5
+ // inside its own mkdtemp dir. The CLI is spawned with cwd set to the fixture
6
+ // root and HOME pointed at an empty temp dir, so neither the developer's real
7
+ // ~/.config/opencode nor the live .opencode/teamwork/ tree is ever read.
8
+ //
9
+ // Run with plain Node (no test framework): failures are counted, printed, and
10
+ // make the process exit non-zero.
11
+
12
+ import { buildExportData, renderExport } from "../lib/export.mjs"
13
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync, existsSync, utimesSync } from "node:fs"
14
+ import { tmpdir } from "node:os"
15
+ import { join, dirname } from "node:path"
16
+ import { fileURLToPath } from "node:url"
17
+ import { spawnSync } from "node:child_process"
18
+ import assert from "node:assert"
19
+
20
+ const here = dirname(fileURLToPath(import.meta.url))
21
+ const cliPath = join(here, "..", "bin", "opencode-teamwork.mjs")
22
+
23
+ // Root temp dir for this run; every fixture lives under it and it is removed in the end.
24
+ const testDir = mkdtempSync(join(tmpdir(), "teamwork-export-test-"))
25
+
26
+ // An empty HOME: any accidental read of ~/.config/opencode finds nothing.
27
+ const emptyHome = mkdtempSync(join(testDir, "home-"))
28
+
29
+ // Keep the in-process environment hermetic too.
30
+ process.env.HOME = emptyHome
31
+ process.env.USERPROFILE = emptyHome
32
+ process.env.XDG_CONFIG_HOME = join(emptyHome, ".config")
33
+
34
+ const SESSION = "20261018-100000-ex01"
35
+ const MISSING = "20261018-999999-none"
36
+ const XSS = "<script>alert(1)</script>"
37
+
38
+ let passed = 0
39
+ let failed = 0
40
+
41
+ /** Run one named check; a thrown assertion is recorded and the suite continues. */
42
+ async function check(name, fn) {
43
+ try {
44
+ await fn()
45
+ passed++
46
+ console.log(`✓ ${name}`)
47
+ } catch (err) {
48
+ failed++
49
+ console.error(`✗ ${name}\n ${err && err.message ? err.message : err}`)
50
+ }
51
+ }
52
+
53
+ function makeRoot() {
54
+ return mkdtempSync(join(testDir, "root-"))
55
+ }
56
+
57
+ function runDirOf(root, id) {
58
+ return join(root, ".opencode", "teamwork", id)
59
+ }
60
+
61
+ function writeJson(file, value) {
62
+ mkdirSync(dirname(file), { recursive: true })
63
+ writeFileSync(file, JSON.stringify(value, null, 2) + "\n")
64
+ }
65
+
66
+ // ---------------------------------------------------------------- fixtures
67
+
68
+ // A healthy run, shaped after docs/ARTIFACTS.md:
69
+ // alpha: verified_pass in round 2, benign summary, a PASS report.
70
+ // beta: verified_fail in round 1; its summary and feedback carry the XSS payload.
71
+ // Nothing in here contains an http(s) URL, so the HTML must contain none either.
72
+ const EVENTS = [
73
+ { ts: "2026-10-18T10:00:00.000Z", event: "run_created", sessionId: SESSION, taskId: null, from: null, to: "pending", round: 0, agent: null, branch: null, worktree: null, phase: "DAG_BUILD" },
74
+ { ts: "2026-10-18T10:00:05.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "pending", to: "worker_active", round: 1, agent: "team/worker", branch: "teamwork/ex-alpha", worktree: "/wt/alpha", phase: "DISPATCH" },
75
+ { ts: "2026-10-18T10:00:10.000Z", event: "task_transition", sessionId: SESSION, taskId: "beta", from: "pending", to: "worker_active", round: 1, agent: "team/worker", branch: "teamwork/ex-beta", worktree: "/wt/beta", phase: "DISPATCH" },
76
+ { ts: "2026-10-18T10:01:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "beta", from: "worker_active", to: "verified_fail", round: 1, agent: "team/verifier", branch: "teamwork/ex-beta", worktree: "/wt/beta", phase: "VERIFY" },
77
+ { ts: "2026-10-18T10:02:00.000Z", event: "task_transition", sessionId: SESSION, taskId: "alpha", from: "worker_active", to: "verified_pass", round: 2, agent: "team/verifier", branch: "teamwork/ex-alpha", worktree: "/wt/alpha", phase: "VERIFY" },
78
+ ]
79
+
80
+ const STATE = {
81
+ version: 1,
82
+ sessionId: SESSION,
83
+ phase: "SECURITY_AUDIT",
84
+ tasks: {
85
+ alpha: {
86
+ status: "verified_pass",
87
+ round: 2,
88
+ branch: "teamwork/ex-alpha",
89
+ worktree: "/wt/alpha",
90
+ summary: "Implemented the alpha module",
91
+ feedback: null,
92
+ verification: { status: "PASS", passedChecks: 4, totalChecks: 4, fatalFindings: [] },
93
+ updatedAt: "2026-10-18T10:02:00.000Z",
94
+ },
95
+ beta: {
96
+ status: "verified_fail",
97
+ round: 1,
98
+ branch: "teamwork/ex-beta",
99
+ worktree: "/wt/beta",
100
+ summary: `Beta summary ${XSS}`,
101
+ feedback: `Verifier says: ${XSS}`,
102
+ verification: { status: "FAIL", passedChecks: 1, totalChecks: 3, fatalFindings: ["empty input crashes"] },
103
+ updatedAt: "2026-10-18T10:01:00.000Z",
104
+ },
105
+ },
106
+ updatedAt: "2026-10-18T10:02:00.000Z",
107
+ }
108
+
109
+ const PLAN = {
110
+ sessionId: SESSION,
111
+ topology: "iterative-coding",
112
+ tasks: [
113
+ { id: "alpha", dependsOn: [], requirements: ["R1"], agent: "team/worker", maxRounds: 4, status: "verified_pass", round: 2 },
114
+ { id: "beta", dependsOn: [], requirements: ["R2"], agent: "team/worker", maxRounds: 4, status: "verified_fail", round: 1 },
115
+ ],
116
+ }
117
+
118
+ const COSTS = {
119
+ sessionId: SESSION,
120
+ rootSessionIds: ["ses_root"],
121
+ budgetUsd: 5,
122
+ budgetSource: "manual",
123
+ spentUsd: 0.21,
124
+ byTask: { alpha: 0.12, beta: 0.05, _sentinel: 0.01, _unattributed: 0.02 },
125
+ byTaskTokens: { alpha: { input: 1234, output: 567, reasoning: 8, cache: { read: 90, write: 11 } } },
126
+ updatedAt: "2026-10-18T10:02:00.000Z",
127
+ tokens: { input: 1000, output: 200, reasoning: 0, cache: { read: 5, write: 6 } },
128
+ }
129
+
130
+ const SECURITY = {
131
+ status: "PASS",
132
+ timestamp: "2026-10-18T10:03:00.000Z",
133
+ summary: "No blocking findings.",
134
+ findings: [{ id: "SEC-1", severity: "low", location: "lib/example.mjs:12", description: "Minor hardening suggestion." }],
135
+ }
136
+
137
+ const REPORT_ALPHA = {
138
+ taskId: "alpha",
139
+ round: 2,
140
+ status: "PASS",
141
+ verifierAgent: "team/verifier",
142
+ verifierModel: "opencode/example-model",
143
+ checks: [{ passed: true }, { passed: true }, { passed: true }, { passed: true }],
144
+ fatalFindings: [],
145
+ }
146
+
147
+ const REPORT_BETA = {
148
+ taskId: "beta",
149
+ round: 1,
150
+ status: "FAIL",
151
+ verifierAgent: "team/verifier",
152
+ feedbackForWorker: `Fix the crash. ${XSS}`,
153
+ checks: [{ passed: true }, { passed: false }, { passed: false }],
154
+ fatalFindings: [{ where: "src/beta.mjs:3", why: "empty input crashes", fix: "guard the empty case" }],
155
+ }
156
+
157
+ // Run terms: demo mode, a recorded preflight bypass, and a stamped final verdict.
158
+ const TERMS_PLAN = { ...PLAN, integrityMode: "demo", preflight: { status: "MISSING", bypassed: true } }
159
+ const TERMS_STATE = { ...STATE, integrityMode: "demo" }
160
+ const FINAL_STAMPED = {
161
+ status: "PASS",
162
+ generatedBy: { agent: "team/final-verifier", session: "ses_final_verify" },
163
+ generatedAt: "2026-10-18T10:04:00.000Z",
164
+ integrityMode: "demo",
165
+ evidence: { tasks: 2, securityAudit: "PASS", allTasksVerifiedPass: false },
166
+ reasons: [],
167
+ }
168
+
169
+ // A single passing task, so a final PASS verdict yields an overall PASS.
170
+ const PASS_STATE = { ...STATE, tasks: { alpha: STATE.tasks.alpha } }
171
+ const PASS_PLAN = { ...TERMS_PLAN, tasks: [TERMS_PLAN.tasks[0]] }
172
+ const PASS_REPORTS = [REPORT_ALPHA]
173
+
174
+ /**
175
+ * Write a run directory under `root`. Pass `null` for any file to omit it.
176
+ */
177
+ function writeRun(root, { id = SESSION, events = EVENTS, state = STATE, plan = PLAN, costs = COSTS, security = SECURITY, finalReport = null, reports = [REPORT_ALPHA, REPORT_BETA] } = {}) {
178
+ const dir = runDirOf(root, id)
179
+ mkdirSync(dir, { recursive: true })
180
+ if (events !== null) writeFileSync(join(dir, "events.jsonl"), events.map((e) => JSON.stringify(e)).join("\n") + "\n")
181
+ if (state !== null) writeJson(join(dir, "state.json"), state)
182
+ if (plan !== null) writeJson(join(dir, "plan.dag.json"), plan)
183
+ if (costs !== null) writeJson(join(dir, "costs.json"), costs)
184
+ if (security !== null) writeJson(join(dir, "verify", "security-audit.json"), security)
185
+ if (finalReport !== null) writeJson(join(dir, "verify", "final.json"), finalReport)
186
+ for (const report of reports) writeJson(join(dir, "verify", `report-${report.taskId}.json`), report)
187
+ return dir
188
+ }
189
+
190
+ /** Write a run directory under a fresh root and return the root. */
191
+ function makeRun(opts) {
192
+ const root = makeRoot()
193
+ writeRun(root, opts)
194
+ return root
195
+ }
196
+
197
+ const healthyRoot = makeRun()
198
+ const healthyData = buildExportData(healthyRoot, SESSION)
199
+
200
+ // Isolated CLI runner. cwd MUST be the fixture root: the CLI resolves runs from process.cwd().
201
+ function runCli(args, cwd) {
202
+ return spawnSync(process.execPath, [cliPath, ...args], {
203
+ cwd,
204
+ encoding: "utf8",
205
+ env: { ...process.env, HOME: emptyHome, NO_COLOR: "" },
206
+ })
207
+ }
208
+
209
+ // ==========================================
210
+ // 1. HTML generation from a healthy fixture
211
+ // ==========================================
212
+
213
+ await check("HTML: healthy fixture builds without error", () => {
214
+ assert.strictEqual(healthyData.error, null, `buildExportData must succeed, got: ${healthyData.error}`)
215
+ assert.strictEqual(healthyData.tasks.length, 2)
216
+ })
217
+
218
+ await check("HTML: a mixed legacy (no seq) and new (seq + agentSource) log exports cleanly", () => {
219
+ // Export derives timing and actors but renders no event-level summary; lines
220
+ // with the new optional fields must be read without changing the result.
221
+ const mixed = EVENTS.map((e, i) => (i % 2 === 0 ? e : { ...e, seq: i + 1, agentSource: "session" }))
222
+ const data = buildExportData(makeRun({ events: mixed }), SESSION)
223
+ assert.strictEqual(data.error, null, `buildExportData must succeed, got: ${data.error}`)
224
+ assert.strictEqual(data.timing, "events")
225
+ const html = renderExport(data, { format: "html" })
226
+ const md = renderExport(data, { format: "markdown" })
227
+ assert(html.startsWith("<!DOCTYPE"), "mixed events must still render HTML")
228
+ assert(md.startsWith("# Teamwork run report"), "mixed events must still render Markdown")
229
+ assert.strictEqual(data.tasks.length, 2)
230
+ })
231
+
232
+ await check("HTML: output starts with a <!DOCTYPE> declaration", () => {
233
+ const html = renderExport(healthyData, { format: "html" })
234
+ assert(html.startsWith("<!DOCTYPE"), `must start with <!DOCTYPE, got: ${JSON.stringify(html.slice(0, 40))}`)
235
+ })
236
+
237
+ await check("HTML: CSS is embedded in a <style> block", () => {
238
+ const html = renderExport(healthyData, { format: "html" })
239
+ assert(/<style>/.test(html), "output must contain an embedded <style> block")
240
+ assert(!/<link[^>]+rel=["']?stylesheet/i.test(html), "output must not link an external stylesheet")
241
+ })
242
+
243
+ await check("HTML: task status badges are rendered", () => {
244
+ const html = renderExport(healthyData, { format: "html" })
245
+ assert(/class="badge b-pass"[^>]*>PASS</.test(html), "verified_pass must render a PASS badge")
246
+ assert(/class="badge b-fail"[^>]*>FAIL</.test(html), "verified_fail must render a FAIL badge")
247
+ })
248
+
249
+ await check("HTML: contains no external URLs (no http:// and no https://)", () => {
250
+ const html = renderExport(healthyData, { format: "html" })
251
+ assert(!html.includes("http://"), "output must not contain http://")
252
+ assert(!html.includes("https://"), "output must not contain https://")
253
+ })
254
+
255
+ // ==========================================
256
+ // 2. Markdown structure
257
+ // ==========================================
258
+
259
+ await check("Markdown: contains a GFM table row", () => {
260
+ const md = renderExport(healthyData, { format: "markdown" })
261
+ assert(/^\|.*\|$/m.test(md), "Markdown must contain at least one |-delimited table row")
262
+ })
263
+
264
+ await check("Markdown: contains a GFM table separator row (|---|---|)", () => {
265
+ const md = renderExport(healthyData, { format: "markdown" })
266
+ assert(/^\|(\s*:?-+:?\s*\|)+\s*$/m.test(md), "Markdown must contain a table separator row such as |---|---|")
267
+ })
268
+
269
+ await check("Markdown: contains a checklist line (- [ ] or - [x])", () => {
270
+ const md = renderExport(healthyData, { format: "markdown" })
271
+ assert(/^- \[[ x]\] /m.test(md), "Markdown must contain a checklist item")
272
+ assert(/^- \[x\] alpha: /m.test(md), "the passed task must be a checked item")
273
+ assert(/^- \[ \] beta: /m.test(md), "the failed task must be an unchecked item")
274
+ })
275
+
276
+ // ==========================================
277
+ // 2b. Run terms (integrity mode, preflight, final verdict provenance)
278
+ // ==========================================
279
+
280
+ const termsData = buildExportData(makeRun({ plan: TERMS_PLAN, state: TERMS_STATE, finalReport: FINAL_STAMPED }), SESSION)
281
+
282
+ await check("Run terms: buildExportData records integrity mode, preflight bypass and a stamped verdict", () => {
283
+ assert.strictEqual(termsData.error, null, `buildExportData must succeed, got: ${termsData.error}`)
284
+ assert.deepStrictEqual(termsData.terms, {
285
+ integrityMode: "demo",
286
+ preflight: { status: "MISSING", bypassed: true },
287
+ finalVerdict: {
288
+ status: "PASS",
289
+ stamped: true,
290
+ generatedBy: { agent: "team/final-verifier", session: "ses_final_verify" },
291
+ generatedAt: "2026-10-18T10:04:00.000Z",
292
+ integrityMode: "demo",
293
+ },
294
+ })
295
+ })
296
+
297
+ await check("Run terms: HTML shows integrity mode, preflight bypass and the stamping agent/session", () => {
298
+ const html = renderExport(termsData, { format: "html" })
299
+ assert(html.includes("demo"), "the integrity mode must appear")
300
+ assert(html.includes("MISSING (bypassed)"), "the bypassed preflight must be marked")
301
+ assert(html.includes("team/final-verifier"), "the stamping agent must appear")
302
+ assert(html.includes("ses_final_verify"), "the stamping session must appear")
303
+ assert(html.includes("2026-10-18T10:04:00.000Z"), "the generatedAt timestamp must appear")
304
+ assert(html.includes("stamped by "), "the verdict must be labelled as stamped")
305
+ })
306
+
307
+ await check("Run terms: Markdown shows integrity mode, preflight bypass and the stamping agent/session", () => {
308
+ const md = renderExport(termsData, { format: "markdown" })
309
+ assert(md.includes("demo"), "the integrity mode must appear")
310
+ assert(md.includes("MISSING (bypassed)"), "the bypassed preflight must be marked")
311
+ assert(md.includes("team/final-verifier"), "the stamping agent must appear")
312
+ assert(md.includes("ses\\_final\\_verify"), "the stamping session must appear (escaped)")
313
+ assert(md.includes("stamped by "), "the verdict must be labelled as stamped")
314
+ })
315
+
316
+ await check("Run terms: an unstamped verdict is marked UNSTAMPED and the run status is unchanged", () => {
317
+ const unstamped = { status: "PASS", integrityMode: "demo" }
318
+ const failData = buildExportData(makeRun({ plan: TERMS_PLAN, state: TERMS_STATE, finalReport: unstamped }), SESSION)
319
+ assert.strictEqual(failData.terms.finalVerdict.stamped, false, "a final report without generatedBy is unstamped")
320
+ assert.strictEqual(failData.status, "FAIL", "a failed task still fails the run despite an unstamped PASS")
321
+ const failHtml = renderExport(failData, { format: "html" })
322
+ const failMd = renderExport(failData, { format: "markdown" })
323
+ assert(failHtml.includes("UNSTAMPED"), "HTML must label the legacy verdict UNSTAMPED")
324
+ assert(failMd.includes("UNSTAMPED"), "Markdown must label the legacy verdict UNSTAMPED")
325
+ assert(/class="badge b-fail">FAIL</.test(failHtml), "HTML must still render the FAIL badge")
326
+ assert(failMd.includes("| Status | **FAIL** |"), "Markdown must still render the FAIL status")
327
+
328
+ const passData = buildExportData(
329
+ makeRun({ plan: PASS_PLAN, state: PASS_STATE, finalReport: unstamped, reports: PASS_REPORTS }),
330
+ SESSION,
331
+ )
332
+ assert.strictEqual(passData.status, "PASS", "an unstamped PASS with all tasks passing is still an overall PASS")
333
+ const passHtml = renderExport(passData, { format: "html" })
334
+ const passMd = renderExport(passData, { format: "markdown" })
335
+ assert(passHtml.includes("UNSTAMPED"), "HTML must label the legacy verdict UNSTAMPED")
336
+ assert(/class="badge b-pass">PASS</.test(passHtml), "HTML must still render the PASS badge")
337
+ assert(passMd.includes("| Status | **PASS** |"), "Markdown must still render the PASS status")
338
+ })
339
+
340
+ await check("Run terms: a legacy run degrades to not recorded / not produced without throwing", () => {
341
+ assert.deepStrictEqual(healthyData.terms, { integrityMode: null, preflight: null, finalVerdict: null })
342
+ const html = renderExport(healthyData, { format: "html" })
343
+ const md = renderExport(healthyData, { format: "markdown" })
344
+ assert(html.includes("not recorded"), "HTML must show 'not recorded' for absent mode/preflight")
345
+ assert(html.includes("not produced"), "HTML must show 'not produced' for an absent verdict")
346
+ assert(md.includes("not recorded"), "Markdown must show 'not recorded' for absent mode/preflight")
347
+ assert(md.includes("not produced"), "Markdown must show 'not produced' for an absent verdict")
348
+ })
349
+
350
+ await check("Run terms: a <script> agent name is escaped in both outputs", () => {
351
+ const data = buildExportData(
352
+ makeRun({ plan: TERMS_PLAN, state: TERMS_STATE, finalReport: { ...FINAL_STAMPED, generatedBy: { agent: XSS, session: "ses_final_verify" } } }),
353
+ SESSION,
354
+ )
355
+ const html = renderExport(data, { format: "html" })
356
+ const md = renderExport(data, { format: "markdown" })
357
+ assert(!html.includes("<script>"), "raw <script> must not appear in the HTML")
358
+ assert(/<dt>Final verdict<\/dt><dd>stamped by &lt;script&gt;alert\(1\)&lt;\/script&gt; \/ ses_final_verify at /.test(html), "the terms verdict must be HTML-escaped")
359
+ assert(!md.includes("<script>"), "raw <script> must not appear in the Markdown")
360
+ assert(md.includes("stamped by \\<script\\>alert(1)\\</script\\> / ses\\_final\\_verify"), "the terms verdict must be Markdown-escaped")
361
+ })
362
+
363
+ // ==========================================
364
+ // 3. HTML entity escaping (XSS)
365
+ // ==========================================
366
+
367
+ await check("XSS: <script> payload in feedback/summary is escaped to &lt;script&gt;", () => {
368
+ const html = renderExport(healthyData, { format: "html" })
369
+ assert(html.includes("&lt;script&gt;"), "escaped payload must appear as &lt;script&gt;")
370
+ })
371
+
372
+ await check("XSS: raw <script>alert(1) substring never appears in HTML output", () => {
373
+ const html = renderExport(healthyData, { format: "html" })
374
+ assert(!html.includes("<script>alert(1)"), "raw <script>alert(1) must not appear in the HTML")
375
+ assert(!/<script[\s>]/i.test(html), "no <script> element may appear in the HTML")
376
+ })
377
+
378
+ await check("XSS: a payload in the Markdown output is not a live HTML tag", () => {
379
+ const md = renderExport(healthyData, { format: "markdown" })
380
+ assert(!md.includes("<script>"), "raw <script> must not appear in the Markdown")
381
+ })
382
+
383
+ // ==========================================
384
+ // 4. Missing / invalid session id exits 1
385
+ // ==========================================
386
+
387
+ await check("CLI: a well-formed but nonexistent session id exits 1 with a stderr message", () => {
388
+ const res = runCli(["export", MISSING], healthyRoot)
389
+ assert.strictEqual(res.status, 1, `missing session must exit 1, got ${res.status}`)
390
+ assert(res.stderr.trim().length > 0, "missing session must explain itself on stderr")
391
+ assert.strictEqual(res.stdout, "", "no document may be produced for a missing session")
392
+ })
393
+
394
+ await check("CLI: an invalid session id (../../etc) exits 1 with a stderr message", () => {
395
+ const res = runCli(["export", "../../etc"], healthyRoot)
396
+ assert.strictEqual(res.status, 1, `invalid id must exit 1, got ${res.status}`)
397
+ assert(res.stderr.trim().length > 0, "invalid id must explain itself on stderr")
398
+ })
399
+
400
+ // ==========================================
401
+ // 5. --output and -o -
402
+ // ==========================================
403
+
404
+ await check("CLI: `-o <file>` writes a file whose content matches the rendered HTML", () => {
405
+ const res = runCli(["export", SESSION, "-o", "report-out.html"], healthyRoot)
406
+ assert.strictEqual(res.status, 0, `valid export must exit 0, got ${res.status}: ${res.stderr}`)
407
+ const file = join(healthyRoot, "report-out.html")
408
+ assert(existsSync(file), "-o must create the named file")
409
+ const written = readFileSync(file, "utf8")
410
+ assert.strictEqual(written, renderExport(healthyData, { format: "html" }), "file content must equal the rendered document")
411
+ assert(res.stdout.trim().endsWith("report-out.html"), `stdout must name the written path, got ${JSON.stringify(res.stdout)}`)
412
+ })
413
+
414
+ // `-o` and `--output` are separate case labels in the CLI, so each gets its own check:
415
+ // deleting either alias must fail the suite on its own.
416
+ await check("CLI: `--output <file>` writes a file whose content matches the rendered HTML", () => {
417
+ const res = runCli(["export", SESSION, "--output", "report-long.html"], healthyRoot)
418
+ assert.strictEqual(res.status, 0, `--output must exit 0, got ${res.status}: ${res.stderr}`)
419
+ const file = join(healthyRoot, "report-long.html")
420
+ assert(existsSync(file), "--output must create the named file")
421
+ assert.strictEqual(readFileSync(file, "utf8"), renderExport(healthyData, { format: "html" }), "file content must equal the rendered document")
422
+ assert(!res.stderr.includes("unknown argument"), "--output must not be treated as an unknown argument")
423
+ assert(res.stdout.trim().endsWith(file), `stdout must print the absolute path ${file}, got ${JSON.stringify(res.stdout)}`)
424
+ })
425
+
426
+ // Markdown: `-m` and `--markdown` are separate case labels too. Paired with `-o -` so the
427
+ // assertion is on stdout content (HTML by default, Markdown only if the alias is honoured).
428
+ await check("CLI: `-m` selects Markdown output", () => {
429
+ const res = runCli(["export", SESSION, "-m", "-o", "-"], healthyRoot)
430
+ assert.strictEqual(res.status, 0, `-m must exit 0, got ${res.status}: ${res.stderr}`)
431
+ assert.strictEqual(res.stdout, renderExport(healthyData, { format: "markdown" }), "-m must stream the Markdown document")
432
+ assert(!res.stderr.includes("unknown argument"), "-m must not be treated as an unknown argument")
433
+ })
434
+
435
+ await check("CLI: `--markdown` selects Markdown output", () => {
436
+ const res = runCli(["export", SESSION, "--markdown", "-o", "-"], healthyRoot)
437
+ assert.strictEqual(res.status, 0, `--markdown must exit 0, got ${res.status}: ${res.stderr}`)
438
+ assert.strictEqual(res.stdout, renderExport(healthyData, { format: "markdown" }), "--markdown must stream the Markdown document")
439
+ assert(!res.stderr.includes("unknown argument"), "--markdown must not be treated as an unknown argument")
440
+ })
441
+
442
+ // `--session <id>` vs the positional id: without the alias, the flag is "unknown" and the id
443
+ // only survives via the positional fallback, so the stderr assertion is what catches removal.
444
+ // The root holds a second run that is the most recently modified, so the positional fallback
445
+ // (runs[0]) would select OTHER. Only an honoured `--session SESSION` streams SESSION's document.
446
+ await check("CLI: `--session <id>` selects the named run (no unknown-argument warning)", () => {
447
+ const twoRoot = makeRun()
448
+ const OTHER = "20261018-200000-ex02"
449
+ const otherDir = writeRun(twoRoot, { id: OTHER })
450
+ const sessionDir = runDirOf(twoRoot, SESSION)
451
+ const now = Date.now() / 1000
452
+ utimesSync(sessionDir, now - 120, now - 120)
453
+ utimesSync(otherDir, now, now)
454
+ const expected = renderExport(buildExportData(twoRoot, SESSION), { format: "html" })
455
+ assert.notStrictEqual(expected, renderExport(buildExportData(twoRoot, OTHER), { format: "html" }), "fixture runs must render differently")
456
+ const res = runCli(["export", "--session", SESSION, "-o", "-"], twoRoot)
457
+ assert.strictEqual(res.status, 0, `--session must exit 0, got ${res.status}: ${res.stderr}`)
458
+ assert.strictEqual(res.stdout, expected, "--session must stream the named run, not the most recent one")
459
+ assert(!res.stderr.includes("unknown argument"), "--session must not be treated as an unknown argument")
460
+ })
461
+
462
+ // Uses its own pristine root: the alias checks above also invoke `-o -`, so a shared root
463
+ // would already contain anything a broken `-o -` path leaked before this snapshot is taken.
464
+ await check("CLI: `-o -` writes the document to stdout and creates no file", () => {
465
+ const cleanRoot = makeRun()
466
+ const before = readdirSync(cleanRoot).sort()
467
+ const res = runCli(["export", SESSION, "-o", "-"], cleanRoot)
468
+ assert.strictEqual(res.status, 0, `-o - must exit 0, got ${res.status}: ${res.stderr}`)
469
+ assert.strictEqual(res.stdout, renderExport(healthyData, { format: "html" }), "stdout must be exactly the rendered document")
470
+ assert.deepStrictEqual(readdirSync(cleanRoot).sort(), before, "-o - must not create any file in the project root")
471
+ assert(!existsSync(join(runDirOf(cleanRoot, SESSION), "report.html")), "-o - must not write the default report.html either")
472
+ })
473
+
474
+ await check("CLI: `-o ../escape.html` is refused with exit 1 and nothing is written", () => {
475
+ const res = runCli(["export", SESSION, "-o", "../escape.html"], healthyRoot)
476
+ assert.strictEqual(res.status, 1, `traversal output must exit 1, got ${res.status}`)
477
+ assert(res.stderr.trim().length > 0, "a refused output path must explain itself on stderr")
478
+ assert(!existsSync(join(testDir, "escape.html")), "nothing may be written outside the project root")
479
+ })
480
+
481
+ // ==========================================
482
+ // 6. package.json wiring (R2 `export` script, R4 aggregate `test`)
483
+ // ==========================================
484
+
485
+ // Read package.json with node:fs. Never shell out to npm: these checks must not depend on
486
+ // npm's behaviour, and they read only the repo's own manifest.
487
+ const packageJsonPath = join(here, "..", "package.json")
488
+
489
+ function readPackageScripts() {
490
+ const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8"))
491
+ assert(pkg && typeof pkg.scripts === "object" && pkg.scripts !== null, "package.json must have a scripts object")
492
+ return pkg.scripts
493
+ }
494
+
495
+ // Split an aggregate script such as "npm run a && npm run b" into its step names, in order.
496
+ function aggregateSteps(script) {
497
+ return script.split("&&").map((step) => {
498
+ const m = /^\s*npm run (\S+)\s*$/.exec(step)
499
+ return m ? m[1] : step.trim()
500
+ })
501
+ }
502
+
503
+ const PRE_EXISTING_SUITES = ["lint:prompts", "test:cost", "test:engine", "test:doctor", "test:timeline"]
504
+
505
+ await check("package.json: `export` script exists and is a non-empty command", () => {
506
+ const scripts = readPackageScripts()
507
+ assert.strictEqual(typeof scripts.export, "string", "scripts.export must be a command string (npm run export)")
508
+ assert(scripts.export.trim().length > 0, "scripts.export must not be empty")
509
+ })
510
+
511
+ await check("package.json: `export` script invokes bin/opencode-teamwork.mjs with the export subcommand", () => {
512
+ const command = readPackageScripts().export
513
+ const tokens = command.trim().split(/\s+/)
514
+ const i = tokens.findIndex((t) => t === "./bin/opencode-teamwork.mjs" || t === "bin/opencode-teamwork.mjs")
515
+ assert(i !== -1, `scripts.export must invoke bin/opencode-teamwork.mjs, got: ${JSON.stringify(command)}`)
516
+ assert.strictEqual(tokens[i + 1], "export", `the token after the CLI path must be "export", got: ${JSON.stringify(command)}`)
517
+ })
518
+
519
+ await check("package.json: aggregate `test` script includes test:export", () => {
520
+ const steps = aggregateSteps(readPackageScripts().test)
521
+ assert(steps.includes("test:export"), `scripts.test must run test:export, got steps: ${steps.join(", ")}`)
522
+ })
523
+
524
+ await check("package.json: aggregate `test` script still runs the five pre-existing suites in order, then test:export", () => {
525
+ const steps = aggregateSteps(readPackageScripts().test)
526
+ let at = -1
527
+ for (const suite of [...PRE_EXISTING_SUITES, "test:export"]) {
528
+ const idx = steps.indexOf(suite)
529
+ assert(idx !== -1, `scripts.test must still run ${suite} (steps: ${steps.join(", ")})`)
530
+ assert(idx > at, `${suite} must run after the previous suite (steps: ${steps.join(", ")})`)
531
+ at = idx
532
+ }
533
+ })
534
+
535
+ // ---------------------------------------------------------------- cleanup
536
+
537
+ rmSync(testDir, { recursive: true, force: true })
538
+
539
+ console.log(`\n${passed} passed, ${failed} failed`)
540
+ process.exitCode = failed ? 1 : 0