@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,2041 @@
1
+ import { registerTeamworkTools } from "../plugins/opencode-teamwork/tools.ts"
2
+ import { listTeamworkRuns, inspectTeamworkRun, pruneTeamworkWorktrees } from "../lib/runs.mjs"
3
+ import { currentModels, readRawModelMap, writeModelMap, installAgents, DEFAULT_MODELS } from "../lib/team.mjs"
4
+ import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"
5
+ import { tmpdir } from "node:os"
6
+ import { dirname, join } from "node:path"
7
+ import { createServer } from "node:http"
8
+ import { execFileSync } from "node:child_process"
9
+ import { fileURLToPath } from "node:url"
10
+ import assert from "node:assert"
11
+
12
+ const testDir = mkdtempSync(join(tmpdir(), "teamwork-engine-test-"))
13
+
14
+ try {
15
+ let registeredTools = {}
16
+ const mockCtx = {
17
+ tool: {
18
+ transform: async (cb) => {
19
+ const editor = {
20
+ namespace: () => {},
21
+ add: (tool) => {
22
+ registeredTools[tool.name] = tool
23
+ },
24
+ }
25
+ await cb(editor)
26
+ },
27
+ },
28
+ session: { get: async () => undefined },
29
+ }
30
+
31
+ await registerTeamworkTools(mockCtx, testDir)
32
+
33
+ assert(registeredTools.next, "next tool must be registered")
34
+ assert(registeredTools.task_update, "task_update tool must be registered")
35
+ assert(registeredTools.security_audit, "security_audit tool must be registered")
36
+ assert(registeredTools.final_verify, "final_verify tool must be registered")
37
+ assert(registeredTools.worktree, "worktree tool must be registered")
38
+
39
+ // ==========================================
40
+ // Part 1: DAG Engine & Dynamic Pitfall Injection
41
+ // ==========================================
42
+ console.log("Testing DAG Engine & Dynamic Pitfall Injection...")
43
+
44
+ const planRes = await registeredTools.plan.execute({
45
+ sessionId: "20261018-000000-test",
46
+ topology: "distributed-coding",
47
+ skipInterview: true, // fixture: this part exercises the DAG engine, not the spec gate
48
+ tasks: [
49
+ { id: "T1", dependsOn: [], maxRounds: 2 },
50
+ { id: "T2", dependsOn: ["T1"], maxRounds: 2 },
51
+ ],
52
+ })
53
+ assert(planRes.content.includes("Planned 2 task(s)"), "Plan should create 2 tasks")
54
+
55
+ // Log a known pitfall for T1
56
+ await registeredTools.pitfall.execute({
57
+ sessionId: "20261018-000000-test",
58
+ taskId: "T1",
59
+ round: 1,
60
+ pitfall: "Do not assume non-empty array",
61
+ })
62
+
63
+ // Step 1: Initial state -> T1 readyForWorker with avoidPitfalls
64
+ let nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
65
+ assert.strictEqual(nextRes.readyForWorker.length, 1, "Only T1 should be ready for worker")
66
+ assert.strictEqual(nextRes.readyForWorker[0].id, "T1")
67
+ assert(nextRes.readyForWorker[0].avoidPitfalls.some((p) => p.includes("Do not assume non-empty array")), "Pitfall should be injected into readyForWorker")
68
+ assert.strictEqual(nextRes.readyForVerifier.length, 0)
69
+
70
+ // Step 2: Worker starts T1 -> worker_active
71
+ await registeredTools.task_update.execute({
72
+ sessionId: "20261018-000000-test",
73
+ taskId: "T1",
74
+ status: "worker_active",
75
+ })
76
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
77
+ assert.strictEqual(nextRes.readyForWorker.length, 0)
78
+ assert.strictEqual(nextRes.inProgress.length, 1)
79
+ assert.strictEqual(nextRes.inProgress[0].id, "T1")
80
+
81
+ // Step 3: Worker commits -> worker_done
82
+ await registeredTools.task_update.execute({
83
+ sessionId: "20261018-000000-test",
84
+ taskId: "T1",
85
+ status: "worker_done",
86
+ branch: "teamwork/20261018-000000-test-T1",
87
+ summary: "Implemented T1",
88
+ })
89
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
90
+ assert.strictEqual(nextRes.readyForVerifier.length, 1)
91
+ assert.strictEqual(nextRes.readyForVerifier[0].id, "T1")
92
+
93
+ // Step 4: Verifier fails T1 (round 1) -> readyForWorker again for round 2
94
+ await registeredTools.task_update.execute({
95
+ sessionId: "20261018-000000-test",
96
+ taskId: "T1",
97
+ status: "verifier_active",
98
+ })
99
+ await registeredTools.task_update.execute({
100
+ sessionId: "20261018-000000-test",
101
+ taskId: "T1",
102
+ status: "verified_fail",
103
+ feedback: "Fix edge case in validation",
104
+ })
105
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
106
+ assert.strictEqual(nextRes.readyForWorker.length, 1)
107
+ assert.strictEqual(nextRes.readyForWorker[0].id, "T1")
108
+ assert.strictEqual(nextRes.readyForWorker[0].round, 2, "Should advance to round 2")
109
+ assert.strictEqual(nextRes.readyForWorker[0].feedback, "R1: Fix edge case in validation", "Unresolved feedback must carry its round prefix")
110
+
111
+ // Step 5: T1 passes on round 2
112
+ await registeredTools.task_update.execute({
113
+ sessionId: "20261018-000000-test",
114
+ taskId: "T1",
115
+ status: "worker_active",
116
+ round: 2,
117
+ })
118
+ await registeredTools.task_update.execute({
119
+ sessionId: "20261018-000000-test",
120
+ taskId: "T1",
121
+ status: "worker_done",
122
+ })
123
+ await registeredTools.task_update.execute({
124
+ sessionId: "20261018-000000-test",
125
+ taskId: "T1",
126
+ status: "verifier_active",
127
+ })
128
+ await registeredTools.task_update.execute({
129
+ sessionId: "20261018-000000-test",
130
+ taskId: "T1",
131
+ status: "verified_pass",
132
+ verification: { status: "PASS", passedChecks: 5, totalChecks: 5 },
133
+ })
134
+
135
+ // Step 6: T1 passed -> T2 is unblocked and ready for worker!
136
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
137
+ assert.strictEqual(nextRes.readyForWorker.length, 1)
138
+ assert.strictEqual(nextRes.readyForWorker[0].id, "T2", "T2 should now be ready for worker")
139
+
140
+ // Step 7: T2 passes -> Pre-merge security gate triggers!
141
+ // The lifecycle is walked explicitly: a direct pending -> verified_pass jump is
142
+ // refused by the transition graph, and verified_pass requires PASS evidence.
143
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
144
+ await registeredTools.task_update.execute({
145
+ sessionId: "20261018-000000-test",
146
+ taskId: "T2",
147
+ status,
148
+ })
149
+ }
150
+ await registeredTools.task_update.execute({
151
+ sessionId: "20261018-000000-test",
152
+ taskId: "T2",
153
+ status: "verified_pass",
154
+ verification: { status: "PASS", passedChecks: 3, totalChecks: 3 },
155
+ })
156
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
157
+ assert.strictEqual(nextRes.status, "READY_FOR_SECURITY_AUDIT", "Should require security audit before all-passed")
158
+
159
+ // Step 8: Security Audit fails (Critical finding) -> BLOCKED_BY_SECURITY
160
+ const failAuditRes = await registeredTools.security_audit.execute({
161
+ sessionId: "20261018-000000-test",
162
+ status: "FAIL",
163
+ findings: [{ id: "SEC-1", severity: "Critical", description: "Hardcoded API key in config", location: "config.js:10" }],
164
+ summary: "Critical secret detected",
165
+ })
166
+ assert.strictEqual(failAuditRes.status, "FAIL")
167
+
168
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
169
+ assert.strictEqual(nextRes.status, "BLOCKED_BY_SECURITY", "Should block final merge when audit fails")
170
+
171
+ // Step 9: Remediate and run clean Security Audit -> final verification gate
172
+ const passAuditRes = await registeredTools.security_audit.execute({
173
+ sessionId: "20261018-000000-test",
174
+ status: "PASS",
175
+ findings: [{ id: "SEC-2", severity: "Low", description: "Missing cache header", location: "server.js:20" }],
176
+ summary: "All critical/high issues resolved",
177
+ })
178
+ assert.strictEqual(passAuditRes.status, "PASS")
179
+
180
+ // (a) Tasks + audit pass, but no verify/final.json -> NOT done.
181
+ const finalFile = join(testDir, ".opencode", "teamwork", "20261018-000000-test", "verify", "final.json")
182
+ const mainStateFile = join(testDir, ".opencode", "teamwork", "20261018-000000-test", "state.json")
183
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
184
+ assert.strictEqual(nextRes.status, "READY_FOR_FINAL_VERIFICATION", "Missing final.json must block ALL_PASSED")
185
+ assert.strictEqual(nextRes.finalReport, finalFile, "Response must name the final report path")
186
+ assert.strictEqual(nextRes.passedCount, 2)
187
+ assert.strictEqual(nextRes.integrityMode, "development", "a run with no request artifact defaults the gate to development")
188
+ let phase = JSON.parse(readFileSync(mainStateFile, "utf8")).phase
189
+ assert.strictEqual(phase, "FINAL_VERIFICATION", "Phase must advance to FINAL_VERIFICATION")
190
+
191
+ // (b) A FAIL final report blocks the run (never ALL_PASSED).
192
+ mkdirSync(dirname(finalFile), { recursive: true })
193
+ writeFileSync(finalFile, JSON.stringify({ status: "FAIL", summary: "acceptance criteria not met" }) + "\n")
194
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
195
+ assert.strictEqual(nextRes.status, "BLOCKED_BY_FINAL_VERIFICATION", "A FAIL final report must block the run")
196
+ assert.notStrictEqual(nextRes.status, "ALL_PASSED")
197
+ assert.strictEqual(nextRes.finalReport, finalFile)
198
+ assert.strictEqual(nextRes.integrityMode, "development", "BLOCKED_BY_FINAL_VERIFICATION must disclose the default mode")
199
+
200
+ // (c) A hand-written PASS report is UNSTAMPED: only the explicit legacy
201
+ // bypass lets it complete the run. (Before A2 any PASS was accepted.)
202
+ writeFileSync(finalFile, JSON.stringify({ status: "PASS", summary: "independent final check passed" }) + "\n")
203
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test" })
204
+ assert.strictEqual(nextRes.status, "FINAL_VERIFICATION_UNVERIFIED", "an unstamped PASS must not reach ALL_PASSED by default")
205
+ assert.strictEqual(nextRes.finalReport, finalFile, "FINAL_VERIFICATION_UNVERIFIED must include the final report path")
206
+ assert.strictEqual(nextRes.integrityMode, "development", "FINAL_VERIFICATION_UNVERIFIED must disclose the default mode")
207
+ phase = JSON.parse(readFileSync(mainStateFile, "utf8")).phase
208
+ assert.strictEqual(phase, "FINAL_VERIFICATION", "an unstamped PASS must leave the run in FINAL_VERIFICATION")
209
+
210
+ nextRes = await registeredTools.next.execute({ sessionId: "20261018-000000-test", allowUnstamped: true })
211
+ assert.strictEqual(nextRes.status, "ALL_PASSED", "allowUnstamped must accept a hand-written PASS")
212
+ assert.strictEqual(nextRes.stamped, false, "the bypassed verdict must not claim to be stamped")
213
+ assert.strictEqual(nextRes.unstampedBypass, true, "the result must flag the bypass")
214
+ assert.strictEqual(nextRes.finalReport, finalFile, "ALL_PASSED must include the final report path")
215
+ assert.strictEqual(nextRes.integrityMode, "development", "ALL_PASSED must disclose the default mode")
216
+ assert(/not produced by teamwork_final_verify/.test(nextRes.content), `the message must state the verdict was unverified: ${nextRes.content}`)
217
+ phase = JSON.parse(readFileSync(mainStateFile, "utf8")).phase
218
+ assert.strictEqual(phase, "MERGE", "Phase must advance to MERGE after the recorded bypass")
219
+
220
+ console.log("✓ DAG engine, dynamic pitfall injection & security gate verified")
221
+
222
+ // ==========================================
223
+ // Part 1b: Topology normalisation + verified_pass accounting
224
+ // ==========================================
225
+ console.log("Testing topology normalisation & completion accounting...")
226
+
227
+ const planFileOf = (id) => join(testDir, ".opencode", "teamwork", id, "plan.dag.json")
228
+ const stateFileOf = (id) => join(testDir, ".opencode", "teamwork", id, "state.json")
229
+ const runFile = (root, runId, name) => join(root, ".opencode", "teamwork", runId, name)
230
+ const readEvents = (root, runId) =>
231
+ readFileSync(runFile(root, runId, "events.jsonl"), "utf8")
232
+ .split("\n")
233
+ .filter((l) => l !== "")
234
+ .map((l) => JSON.parse(l))
235
+
236
+ // Every legacy alias is accepted and persisted as its canonical topology.
237
+ const aliases = {
238
+ "large-swarm": "distributed-coding",
239
+ "doc-review": "document-review",
240
+ "long-proof": "proof",
241
+ "massive-proof-swarm": "massive-proof",
242
+ }
243
+ for (const [alias, canonical] of Object.entries(aliases)) {
244
+ const id = `20261018-000000-alias-${alias}`
245
+ const r = await registeredTools.plan.execute({ sessionId: id, topology: alias, skipInterview: true, tasks: [{ id: "T1" }] })
246
+ assert(r.content.startsWith("Planned"), `alias ${alias} must be accepted: ${r.content}`)
247
+ const persisted = JSON.parse(readFileSync(planFileOf(id), "utf8"))
248
+ assert.strictEqual(persisted.topology, canonical, `${alias} must be persisted as ${canonical}`)
249
+ assert(!("routingReason" in persisted), "routingReason must be absent when not provided")
250
+ }
251
+
252
+ // routingReason is optional and persisted when provided.
253
+ const reasonRun = "20261018-000000-reason"
254
+ await registeredTools.plan.execute({
255
+ sessionId: reasonRun,
256
+ topology: "doc-review",
257
+ routingReason: "docs-only review",
258
+ skipInterview: true,
259
+ tasks: [{ id: "T1" }],
260
+ })
261
+ const reasonPlan = JSON.parse(readFileSync(planFileOf(reasonRun), "utf8"))
262
+ assert.strictEqual(reasonPlan.topology, "document-review", "alias must be normalised on write")
263
+ assert.strictEqual(reasonPlan.routingReason, "docs-only review", "routingReason must be persisted")
264
+
265
+ // An unknown topology is refused and writes nothing.
266
+ const badTopoRun = "20261018-000000-badtopo"
267
+ const badTopo = await registeredTools.plan.execute({
268
+ sessionId: badTopoRun,
269
+ topology: "not-a-topology",
270
+ tasks: [{ id: "T1" }],
271
+ })
272
+ assert(badTopo.content.startsWith("refused: invalid topology"), `unknown topology must be refused: ${badTopo.content}`)
273
+ assert(badTopo.content.includes("document-review"), "refusal must list the accepted values")
274
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", badTopoRun)), "a refused plan must write nothing")
275
+
276
+ // verified_pass is the canonical terminal state: status counts it, resume is complete.
277
+ // The legal lifecycle must be walked and PASS evidence supplied (the engine refuses
278
+ // both a status jump and an evidence-free verified_pass).
279
+ const passRun = "20261018-000000-verified"
280
+ await registeredTools.plan.execute({ sessionId: passRun, topology: "iterative-coding", skipInterview: true, tasks: [{ id: "P1" }, { id: "P2" }] })
281
+ for (const taskId of ["P1", "P2"]) {
282
+ for (const status of ["worker_active", "worker_done", "verifier_active", "verified_pass"]) {
283
+ await registeredTools.task_update.execute({
284
+ sessionId: passRun,
285
+ taskId,
286
+ status,
287
+ ...(status === "verified_pass" ? { verification: { status: "PASS" } } : {}),
288
+ })
289
+ }
290
+ }
291
+ const passStatus = await registeredTools.status.execute({ sessionId: passRun })
292
+ assert(passStatus.content.includes("2/2 pass"), `status must count verified_pass: ${passStatus.content}`)
293
+ const passResume = await registeredTools.resume.execute({ sessionId: passRun })
294
+ assert(passResume.content.includes("is complete"), `resume must treat verified_pass as closed: ${passResume.content}`)
295
+
296
+ // Legacy `pass` in an existing state.json is still counted as complete.
297
+ const legacyRun = "20261018-000000-legacy-pass"
298
+ await registeredTools.plan.execute({ sessionId: legacyRun, topology: "small-focused", skipInterview: true, tasks: [{ id: "L1" }] })
299
+ const legacyState = JSON.parse(readFileSync(stateFileOf(legacyRun), "utf8"))
300
+ legacyState.tasks.L1.status = "pass"
301
+ writeFileSync(stateFileOf(legacyRun), JSON.stringify(legacyState, null, 2) + "\n")
302
+ const legacyStatus = await registeredTools.status.execute({ sessionId: legacyRun })
303
+ assert(legacyStatus.content.includes("1/1 pass"), `status must still count legacy pass: ${legacyStatus.content}`)
304
+ const legacyResume = await registeredTools.resume.execute({ sessionId: legacyRun })
305
+ assert(legacyResume.content.includes("is complete"), `resume must treat legacy pass as closed: ${legacyResume.content}`)
306
+
307
+ console.log("✓ topology aliases normalised, unknown topologies refused, verified_pass counted as complete")
308
+
309
+ // ==========================================
310
+ // Part 1c: teamwork_plan spec gate (3.4)
311
+ // ==========================================
312
+ console.log("Testing the teamwork_plan spec gate...")
313
+
314
+ // (a) no spec + defaults -> refused, and the run dir is never created.
315
+ const noSpecRun = "20261018-000000-nospec"
316
+ const noSpecRes = await registeredTools.plan.execute({ sessionId: noSpecRun, topology: "iterative-coding", tasks: [{ id: "S1" }] })
317
+ assert(noSpecRes.content.startsWith("refused: no spec found"), `plan without a spec must be refused: ${noSpecRes.content}`)
318
+ assert(noSpecRes.content.includes(runFile(testDir, noSpecRun, "prompt_draft.md")), "refusal must name the expected spec path")
319
+ assert(noSpecRes.content.includes("skipInterview: true"), "refusal must name the explicit bypass")
320
+ assert(noSpecRes.content.includes("/teamwork-craft"), "refusal must name the action that produces a spec")
321
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", noSpecRun)), "a spec-gate refusal must create no run directory")
322
+
323
+ // A whitespace-only prompt_draft.md is not a spec: still refused, still no plan files.
324
+ const blankSpecRun = "20261018-000000-blankspec"
325
+ mkdirSync(join(testDir, ".opencode", "teamwork", blankSpecRun), { recursive: true })
326
+ writeFileSync(runFile(testDir, blankSpecRun, "prompt_draft.md"), " \n\t\n")
327
+ const blankRes = await registeredTools.plan.execute({ sessionId: blankSpecRun, topology: "iterative-coding", tasks: [{ id: "S1" }] })
328
+ assert(blankRes.content.startsWith("refused: no spec found"), `a whitespace-only spec must not satisfy the gate: ${blankRes.content}`)
329
+ assert(!existsSync(planFileOf(blankSpecRun)), "a refused plan with an existing run dir must write no plan files")
330
+
331
+ // (b) skipInterview: true -> succeeds, and run_created records the bypass.
332
+ const bypassRun = "20261018-000000-specbypass"
333
+ const bypassRes = await registeredTools.plan.execute({ sessionId: bypassRun, topology: "iterative-coding", skipInterview: true, tasks: [{ id: "S1" }] })
334
+ assert(bypassRes.content.startsWith("Planned"), `skipInterview must allow planning without a spec: ${bypassRes.content}`)
335
+ assert(bypassRes.content.includes("Spec gate bypassed"), "the bypass must be visible in the tool result")
336
+ const bypassCreated = readEvents(testDir, bypassRun).find((e) => e.event === "run_created")
337
+ assert.strictEqual(bypassCreated.specGate, "bypassed", "run_created must record specGate: bypassed")
338
+ assert(!Object.hasOwn(bypassCreated, "specPath"), "a bypass must not record a specPath")
339
+
340
+ // (c) non-empty prompt_draft.md -> succeeds, specPath recorded.
341
+ const specRun = "20261018-000000-specok"
342
+ mkdirSync(join(testDir, ".opencode", "teamwork", specRun), { recursive: true })
343
+ writeFileSync(runFile(testDir, specRun, "prompt_draft.md"), "# Spec\n\nBuild the thing.\n")
344
+ const specRes = await registeredTools.plan.execute({ sessionId: specRun, topology: "iterative-coding", tasks: [{ id: "S1" }] })
345
+ assert(specRes.content.startsWith("Planned"), `a present spec must satisfy the gate: ${specRes.content}`)
346
+ const specCreated = readEvents(testDir, specRun).find((e) => e.event === "run_created")
347
+ assert.strictEqual(specCreated.specGate, "satisfied", "run_created must record specGate: satisfied")
348
+ assert.strictEqual(specCreated.specPath, runFile(testDir, specRun, "prompt_draft.md"), "a satisfied gate must record the spec path")
349
+ assert.deepStrictEqual(
350
+ Object.keys(specCreated),
351
+ ["ts", "seq", "event", "sessionId", "taskId", "from", "to", "round", "agent", "branch", "worktree", "phase", "specGate", "specPath"],
352
+ "existing run_created fields must keep their order (seq after ts); the gate fields are appended",
353
+ )
354
+
355
+ // (d) requireSpec: false -> succeeds without a spec and is recorded as such.
356
+ const optOutRun = "20261018-000000-specoptout"
357
+ const optOutRes = await registeredTools.plan.execute({ sessionId: optOutRun, topology: "iterative-coding", requireSpec: false, tasks: [{ id: "S1" }] })
358
+ assert(optOutRes.content.startsWith("Planned"), `requireSpec: false must allow planning without a spec: ${optOutRes.content}`)
359
+ assert(!existsSync(runFile(testDir, optOutRun, "prompt_draft.md")), "requireSpec: false must not invent a spec file")
360
+ const optOutCreated = readEvents(testDir, optOutRun).find((e) => e.event === "run_created")
361
+ assert.strictEqual(optOutCreated.specGate, "not_required", "run_created must record specGate: not_required")
362
+ assert(!Object.hasOwn(optOutCreated, "specPath"), "not_required must not record a specPath")
363
+
364
+ console.log("✓ plan refuses without a spec (writing nothing), records satisfied/bypassed/not_required")
365
+
366
+ // ==========================================
367
+ // Part 1c-bis: request artifact and integrity modes
368
+ // ==========================================
369
+ console.log("Testing ORIGINAL_REQUEST.md and integrity modes...")
370
+
371
+ const requestFileOf = (id) => runFile(testDir, id, "ORIGINAL_REQUEST.md")
372
+
373
+ // (a) request + benchmark: verbatim artifact first, mode persisted everywhere.
374
+ const reqRun = "20261018-000000-request-bench"
375
+ const requestText = "Build the thing.\n\nKeep these spaces\tand this tab.\n\n indented line"
376
+ const reqRes = await registeredTools.plan.execute({
377
+ sessionId: reqRun,
378
+ topology: "iterative-coding",
379
+ skipInterview: true,
380
+ request: requestText,
381
+ integrityMode: "benchmark",
382
+ tasks: [{ id: "R1" }],
383
+ })
384
+ assert(reqRes.content.startsWith("Planned"), `request plan must succeed: ${reqRes.content}`)
385
+ assert(reqRes.content.includes("benchmark"), "the plan result must name the integrity mode")
386
+ const reqMd = readFileSync(requestFileOf(reqRun), "utf8")
387
+ assert(reqMd.startsWith("# Original Request\n\n- Integrity mode: benchmark\n- Recorded: "), `artifact header must be exact: ${reqMd.slice(0, 80)}`)
388
+ assert(/- Recorded: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/.test(reqMd), "Recorded must be ISO8601 UTC")
389
+ assert(reqMd.includes(`- Session: ${reqRun}`), "artifact must name the run session")
390
+ assert(reqMd.includes(`## Request\n\n${requestText}`), "request text must be preserved verbatim (interior whitespace intact)")
391
+ assert.strictEqual(JSON.parse(readFileSync(planFileOf(reqRun), "utf8")).integrityMode, "benchmark", "plan.dag.json must carry integrityMode")
392
+ assert.strictEqual(JSON.parse(readFileSync(stateFileOf(reqRun), "utf8")).integrityMode, "benchmark", "state.json must carry integrityMode")
393
+
394
+ // (b) a second plan into the same run is refused and writes nothing else.
395
+ const planBefore = readFileSync(planFileOf(reqRun), "utf8")
396
+ const stateBefore = readFileSync(stateFileOf(reqRun), "utf8")
397
+ const secondReq = await registeredTools.plan.execute({
398
+ sessionId: reqRun,
399
+ topology: "iterative-coding",
400
+ skipInterview: true,
401
+ request: "a different request",
402
+ integrityMode: "benchmark",
403
+ tasks: [{ id: "R2" }],
404
+ })
405
+ assert(secondReq.content.startsWith("refused:"), `a second request must be refused: ${secondReq.content}`)
406
+ assert(/write-once/i.test(secondReq.content), "refusal must explain the write-once rule")
407
+ assert(/new session/i.test(secondReq.content), "refusal must point at a new session")
408
+ assert.strictEqual(readFileSync(requestFileOf(reqRun), "utf8"), reqMd, "the recorded request must be unchanged")
409
+ assert.strictEqual(readFileSync(planFileOf(reqRun), "utf8"), planBefore, "a refused request must not rewrite plan.dag.json")
410
+ assert.strictEqual(readFileSync(stateFileOf(reqRun), "utf8"), stateBefore, "a refused request must not rewrite state.json")
411
+
412
+ // (c) an invalid mode is refused before anything is written.
413
+ const badModeRun = "20261018-000000-badmode"
414
+ const badMode = await registeredTools.plan.execute({
415
+ sessionId: badModeRun,
416
+ topology: "iterative-coding",
417
+ skipInterview: true,
418
+ request: "do it",
419
+ integrityMode: "production",
420
+ tasks: [{ id: "M1" }],
421
+ })
422
+ assert(badMode.content.startsWith("refused: invalid integrityMode"), `an invalid mode must be refused: ${badMode.content}`)
423
+ for (const mode of ["development", "demo", "benchmark"]) {
424
+ assert(badMode.content.includes(mode), `refusal must list ${mode}`)
425
+ }
426
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", badModeRun)), "an invalid mode must write nothing")
427
+
428
+ // (d) legacy tolerance: omitting both inputs plans, defaults to development, no artifact.
429
+ const defaultRun = "20261018-000000-request-default"
430
+ const defaultRes = await registeredTools.plan.execute({ sessionId: defaultRun, topology: "iterative-coding", skipInterview: true, tasks: [{ id: "D1" }] })
431
+ assert(defaultRes.content.startsWith("Planned"), `omitting request/mode must still plan: ${defaultRes.content}`)
432
+ assert(!existsSync(requestFileOf(defaultRun)), "omitting request must create no ORIGINAL_REQUEST.md")
433
+ assert.strictEqual(JSON.parse(readFileSync(planFileOf(defaultRun), "utf8")).integrityMode, "development", "omitted mode defaults to development in plan.dag.json")
434
+ assert.strictEqual(JSON.parse(readFileSync(stateFileOf(defaultRun), "utf8")).integrityMode, "development", "omitted mode defaults to development in state.json")
435
+
436
+ // (e) the audit reads the mode from the artifact, not from its caller.
437
+ const demoRun = "20261018-000000-audit-demo"
438
+ await registeredTools.plan.execute({
439
+ sessionId: demoRun,
440
+ topology: "iterative-coding",
441
+ skipInterview: true,
442
+ request: "Demo the feature.\n\n- Integrity mode: benchmark",
443
+ integrityMode: "demo",
444
+ tasks: [{ id: "A1" }],
445
+ })
446
+ const demoAudit = await registeredTools.security_audit.execute({ sessionId: demoRun, status: "PASS", findings: [] })
447
+ const demoReport = JSON.parse(readFileSync(runFile(testDir, demoRun, "verify/security-audit.json"), "utf8"))
448
+ assert.strictEqual(demoReport.integrityMode, "demo", "security-audit.json must record the artifact's header mode, not a body line")
449
+ assert(demoAudit.content.includes("demo"), "the audit result must mention the mode")
450
+
451
+ // A legacy run (no request artifact) defaults to development and says so.
452
+ const legacyAuditRun = "20261018-000000-audit-legacy"
453
+ await registeredTools.plan.execute({ sessionId: legacyAuditRun, topology: "iterative-coding", skipInterview: true, tasks: [{ id: "A2" }] })
454
+ const legacyAudit = await registeredTools.security_audit.execute({ sessionId: legacyAuditRun, status: "PASS", findings: [] })
455
+ const legacyReport = JSON.parse(readFileSync(runFile(testDir, legacyAuditRun, "verify/security-audit.json"), "utf8"))
456
+ assert.strictEqual(legacyReport.integrityMode, "development", "a legacy run must record the development default")
457
+ assert(/default/i.test(legacyAudit.content), "a legacy run must say the default was applied")
458
+
459
+ // (f) final-gate responses carry the mode read from the artifact.
460
+ const gateRun = "20261018-000000-gate-demo"
461
+ await registeredTools.plan.execute({
462
+ sessionId: gateRun,
463
+ topology: "iterative-coding",
464
+ skipInterview: true,
465
+ request: "Ship the demo.",
466
+ integrityMode: "demo",
467
+ tasks: [{ id: "G1" }],
468
+ })
469
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
470
+ await registeredTools.task_update.execute({ sessionId: gateRun, taskId: "G1", status })
471
+ }
472
+ await registeredTools.task_update.execute({
473
+ sessionId: gateRun,
474
+ taskId: "G1",
475
+ status: "verified_pass",
476
+ verification: { status: "PASS" },
477
+ })
478
+ await registeredTools.security_audit.execute({ sessionId: gateRun, status: "PASS", findings: [] })
479
+
480
+ const gateFinal = runFile(testDir, gateRun, "verify/final.json")
481
+ let gateRes = await registeredTools.next.execute({ sessionId: gateRun })
482
+ assert.strictEqual(gateRes.status, "READY_FOR_FINAL_VERIFICATION")
483
+ assert.strictEqual(gateRes.integrityMode, "demo", "READY_FOR_FINAL_VERIFICATION must carry integrityMode")
484
+ assert(gateRes.content.includes("Integrity mode: demo"), `READY message must mention the mode: ${gateRes.content}`)
485
+
486
+ mkdirSync(dirname(gateFinal), { recursive: true })
487
+ writeFileSync(gateFinal, JSON.stringify({ status: "FAIL", summary: "not yet" }) + "\n")
488
+ gateRes = await registeredTools.next.execute({ sessionId: gateRun })
489
+ assert.strictEqual(gateRes.status, "BLOCKED_BY_FINAL_VERIFICATION")
490
+ assert.strictEqual(gateRes.integrityMode, "demo", "BLOCKED_BY_FINAL_VERIFICATION must carry integrityMode")
491
+ assert(gateRes.content.includes("Integrity mode: demo"), `BLOCKED message must mention the mode: ${gateRes.content}`)
492
+
493
+ // The gate demo's report is hand-written, so reaching ALL_PASSED here takes
494
+ // the explicit bypass (the default refusal is covered in Part 1c(c) above).
495
+ writeFileSync(gateFinal, JSON.stringify({ status: "PASS", summary: "ok" }) + "\n")
496
+ gateRes = await registeredTools.next.execute({ sessionId: gateRun })
497
+ assert.strictEqual(gateRes.status, "FINAL_VERIFICATION_UNVERIFIED", "a hand-written PASS must be refused by default")
498
+ gateRes = await registeredTools.next.execute({ sessionId: gateRun, allowUnstamped: true })
499
+ assert.strictEqual(gateRes.status, "ALL_PASSED")
500
+ assert.strictEqual(gateRes.stamped, false, "the bypassed verdict must not claim to be stamped")
501
+ assert.strictEqual(gateRes.integrityMode, "demo", "ALL_PASSED must carry integrityMode")
502
+ assert(gateRes.content.includes("Integrity mode: demo"), `ALL_PASSED message must mention the mode: ${gateRes.content}`)
503
+
504
+ console.log("✓ request recorded verbatim once, modes validated/persisted, audit & final gate read the artifact")
505
+
506
+ // ==========================================
507
+ // Part 1c-quinquies: input preflight gate
508
+ // ==========================================
509
+ console.log("Testing the input preflight gate...")
510
+
511
+ const existingInput = join(testDir, "preflight-existing.txt")
512
+ writeFileSync(existingInput, "present\n")
513
+ const missingAbs = join(testDir, "preflight-does-not-exist.txt")
514
+ assert(!existsSync(missingAbs), "fixture: the missing path must not exist")
515
+
516
+ // (a) an existing absolute path named by the request -> READY, plan proceeds.
517
+ const pfReadyRun = "20261018-000000-preflight-ready"
518
+ const pfReady = await registeredTools.plan.execute({
519
+ sessionId: pfReadyRun,
520
+ topology: "iterative-coding",
521
+ skipInterview: true,
522
+ request: `Read ${existingInput} before planning`,
523
+ tasks: [{ id: "PF1" }],
524
+ })
525
+ assert(pfReady.content.startsWith("Planned"), `an existing input must not block: ${pfReady.content}`)
526
+ assert(/Preflight: READY/.test(pfReady.content), `the plan result must report the preflight: ${pfReady.content}`)
527
+ const pfReadyPlan = JSON.parse(readFileSync(planFileOf(pfReadyRun), "utf8"))
528
+ assert.deepStrictEqual(pfReadyPlan.preflight, { status: "READY", bypassed: false }, "a READY preflight must be recorded in plan.dag.json")
529
+
530
+ // (b) an absolute path named by the request that does not exist -> refused, no run dir.
531
+ const pfMissingRun = "20261018-000000-preflight-missing"
532
+ const pfMissing = await registeredTools.plan.execute({
533
+ sessionId: pfMissingRun,
534
+ topology: "iterative-coding",
535
+ skipInterview: true,
536
+ request: `Read ${missingAbs} before planning`,
537
+ tasks: [{ id: "PF1" }],
538
+ })
539
+ assert(pfMissing.content.startsWith("refused:"), `a missing absolute input must be refused: ${pfMissing.content}`)
540
+ assert(/MISSING/.test(pfMissing.content), "the refusal must name the item status")
541
+ assert(pfMissing.content.includes(missingAbs), "the refusal must name the missing path")
542
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", pfMissingRun)), "a preflight refusal must create no run directory")
543
+
544
+ // (c) a missing entry in the explicit `inputs` array -> refused.
545
+ const pfExplicitRun = "20261018-000000-preflight-explicit"
546
+ const pfExplicit = await registeredTools.plan.execute({
547
+ sessionId: pfExplicitRun,
548
+ topology: "iterative-coding",
549
+ skipInterview: true,
550
+ inputs: [missingAbs],
551
+ tasks: [{ id: "PF1" }],
552
+ })
553
+ assert(pfExplicit.content.startsWith("refused:"), `a missing explicit input must be refused: ${pfExplicit.content}`)
554
+ assert(pfExplicit.content.includes(missingAbs), "the refusal must name the explicit input")
555
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", pfExplicitRun)), "an explicit-input refusal must create no run directory")
556
+
557
+ // (d) the same missing input with allowMissingInputs: true -> planned + recorded bypass.
558
+ const pfBypassRun = "20261018-000000-preflight-bypass"
559
+ const pfBypass = await registeredTools.plan.execute({
560
+ sessionId: pfBypassRun,
561
+ topology: "iterative-coding",
562
+ skipInterview: true,
563
+ request: `Read ${missingAbs} before planning`,
564
+ allowMissingInputs: true,
565
+ tasks: [{ id: "PF1" }],
566
+ })
567
+ assert(pfBypass.content.startsWith("Planned"), `allowMissingInputs must permit the plan: ${pfBypass.content}`)
568
+ assert(/Preflight: MISSING \(bypassed: allowMissingInputs\)/.test(pfBypass.content), `the bypass must be visible: ${pfBypass.content}`)
569
+ const pfBypassPlan = JSON.parse(readFileSync(planFileOf(pfBypassRun), "utf8"))
570
+ assert.deepStrictEqual(pfBypassPlan.preflight, { status: "MISSING", bypassed: true }, "the bypass must be persisted in plan.dag.json")
571
+ const pfBypassCreated = readEvents(testDir, pfBypassRun).find((e) => e.event === "run_created")
572
+ assert(/preflight bypassed: MISSING \(1 item\)/.test(pfBypassCreated.note), `run_created must note the bypass: ${pfBypassCreated.note}`)
573
+
574
+ // (e) a relative path-like token that does not exist is advisory only.
575
+ const pfAdvisoryRun = "20261018-000000-preflight-advisory"
576
+ const pfAdvisory = await registeredTools.plan.execute({
577
+ sessionId: pfAdvisoryRun,
578
+ topology: "iterative-coding",
579
+ skipInterview: true,
580
+ request: "Review nonexistent/advisory-only.md before planning",
581
+ tasks: [{ id: "PF1" }],
582
+ })
583
+ assert(pfAdvisory.content.startsWith("Planned"), `an advisory path must never block: ${pfAdvisory.content}`)
584
+ assert(
585
+ /advisory path missing \(non-blocking\): nonexistent\/advisory-only\.md/.test(pfAdvisory.content),
586
+ `the advisory miss must be reported: ${pfAdvisory.content}`,
587
+ )
588
+ const pfAdvisoryPlan = JSON.parse(readFileSync(planFileOf(pfAdvisoryRun), "utf8"))
589
+ assert.deepStrictEqual(pfAdvisoryPlan.preflight, { status: "READY", bypassed: false }, "an advisory miss must leave the status READY")
590
+
591
+ // (f) a URL is UNCHECKED by default, and the plan proceeds.
592
+ const pfUncheckedRun = "20261018-000000-preflight-unchecked"
593
+ const uncheckedUrl = "http://127.0.0.1:1/unchecked"
594
+ const pfUnchecked = await registeredTools.plan.execute({
595
+ sessionId: pfUncheckedRun,
596
+ topology: "iterative-coding",
597
+ skipInterview: true,
598
+ request: `Watch ${uncheckedUrl} before planning`,
599
+ tasks: [{ id: "PF1" }],
600
+ })
601
+ assert(pfUnchecked.content.startsWith("Planned"), `an unchecked URL must not block: ${pfUnchecked.content}`)
602
+ assert(/1 unchecked/.test(pfUnchecked.content), `the plan result must report the unchecked URL: ${pfUnchecked.content}`)
603
+ assert.deepStrictEqual(JSON.parse(readFileSync(planFileOf(pfUncheckedRun), "utf8")).preflight, { status: "READY", bypassed: false })
604
+
605
+ // (g) URL checking against a local server (no internet): 200 is READY,
606
+ // 500 and connection refused are OUTAGE and refuse the plan.
607
+ let preflightServer
608
+ const stopServer = (server) =>
609
+ new Promise((resolve) => {
610
+ server.close(resolve)
611
+ if (typeof server.closeAllConnections === "function") server.closeAllConnections()
612
+ })
613
+ try {
614
+ preflightServer = createServer((req, res) => {
615
+ res.writeHead(req.url === "/ok" ? 200 : 500)
616
+ res.end()
617
+ })
618
+ await new Promise((resolve) => preflightServer.listen(0, "127.0.0.1", resolve))
619
+ const port = preflightServer.address().port
620
+ const base = `http://127.0.0.1:${port}`
621
+
622
+ const pfUrlOkRun = "20261018-000000-preflight-url-ok"
623
+ const pfUrlOk = await registeredTools.plan.execute({
624
+ sessionId: pfUrlOkRun,
625
+ topology: "iterative-coding",
626
+ skipInterview: true,
627
+ request: `Fetch ${base}/ok before planning`,
628
+ checkUrls: true,
629
+ tasks: [{ id: "PF1" }],
630
+ })
631
+ assert(pfUrlOk.content.startsWith("Planned"), `a 200 URL must be READY: ${pfUrlOk.content}`)
632
+ assert.deepStrictEqual(JSON.parse(readFileSync(planFileOf(pfUrlOkRun), "utf8")).preflight, { status: "READY", bypassed: false })
633
+
634
+ const pfUrlFailRun = "20261018-000000-preflight-url-500"
635
+ const pfUrlFail = await registeredTools.plan.execute({
636
+ sessionId: pfUrlFailRun,
637
+ topology: "iterative-coding",
638
+ skipInterview: true,
639
+ request: `Fetch ${base}/fail before planning`,
640
+ checkUrls: true,
641
+ tasks: [{ id: "PF1" }],
642
+ })
643
+ assert(pfUrlFail.content.startsWith("refused:"), `a 500 URL must be OUTAGE and refuse the plan: ${pfUrlFail.content}`)
644
+ assert(/OUTAGE/.test(pfUrlFail.content) && pfUrlFail.content.includes(`${base}/fail`), "the refusal must name the outage")
645
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", pfUrlFailRun)), "a URL refusal must create no run directory")
646
+
647
+ // Closing the listener makes the same port refuse connections.
648
+ await stopServer(preflightServer)
649
+ preflightServer = undefined
650
+ const pfUrlDownRun = "20261018-000000-preflight-url-down"
651
+ const pfUrlDown = await registeredTools.plan.execute({
652
+ sessionId: pfUrlDownRun,
653
+ topology: "iterative-coding",
654
+ skipInterview: true,
655
+ request: `Fetch ${base}/down before planning`,
656
+ checkUrls: true,
657
+ tasks: [{ id: "PF1" }],
658
+ })
659
+ assert(pfUrlDown.content.startsWith("refused:"), `a refused connection must be OUTAGE and refuse the plan: ${pfUrlDown.content}`)
660
+ assert(/OUTAGE/.test(pfUrlDown.content), "the refusal must name the outage")
661
+ assert(!existsSync(join(testDir, ".opencode", "teamwork", pfUrlDownRun)), "a connection refusal must create no run directory")
662
+ } finally {
663
+ if (preflightServer) await stopServer(preflightServer)
664
+ }
665
+
666
+ // Standalone teamwork_preflight: re-reads ORIGINAL_REQUEST.md, writes
667
+ // preflight.json, and appends a preflight event (with a note when missing).
668
+ const standaloneMissing = join(testDir, "preflight-standalone-missing.txt")
669
+ const standalone = await registeredTools.preflight.execute({
670
+ sessionId: pfReadyRun,
671
+ inputs: [standaloneMissing],
672
+ })
673
+ assert.strictEqual(standalone.status, "MISSING", `the standalone report must sum to MISSING: ${standalone.content}`)
674
+ const standaloneReport = JSON.parse(readFileSync(runFile(testDir, pfReadyRun, "preflight.json"), "utf8"))
675
+ assert(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(standaloneReport.checkedAt), "checkedAt must be ISO8601 UTC")
676
+ assert.strictEqual(standaloneReport.integrityMode, "development", "preflight.json must record the run's integrity mode")
677
+ assert.strictEqual(standaloneReport.summary.status, "MISSING")
678
+ assert(
679
+ standaloneReport.items.some((i) => i.value === existingInput && i.status === "READY" && i.detail === "file"),
680
+ "the recorded request's input must be re-read from ORIGINAL_REQUEST.md",
681
+ )
682
+ assert(
683
+ standaloneReport.items.some((i) => i.value === standaloneMissing && i.status === "MISSING" && i.blocking === true),
684
+ "the explicit missing input must be reported as blocking",
685
+ )
686
+ const standaloneEvent = readEvents(testDir, pfReadyRun).find((e) => e.event === "preflight")
687
+ assert(standaloneEvent, "teamwork_preflight must append a preflight event")
688
+ assert.strictEqual(standaloneEvent.to, "MISSING", "the preflight event must record the status")
689
+ assert(/missing|unreachable/i.test(standaloneEvent.note), `the preflight event must note the miss: ${standaloneEvent.note}`)
690
+
691
+ console.log("✓ preflight blocks missing/outage inputs, ignores advisory paths, checks localhost URLs, records bypass; standalone tool writes preflight.json")
692
+
693
+ // ==========================================
694
+ // Part 1c-ter: final_verify tool
695
+ // ==========================================
696
+ console.log("Testing the final_verify tool...")
697
+
698
+ const reportFileOf = (runId, taskId) => runFile(testDir, runId, `verify/report-${taskId}.json`)
699
+ const writeTaskReport = (runId, taskId, status = "PASS") => {
700
+ const file = reportFileOf(runId, taskId)
701
+ mkdirSync(dirname(file), { recursive: true })
702
+ writeFileSync(file, JSON.stringify({ taskId, status, timestamp: new Date().toISOString() }) + "\n")
703
+ }
704
+ const seedVerifiedRun = async (runId, taskIds, { request, integrityMode, auditStatus = "PASS" } = {}) => {
705
+ await registeredTools.plan.execute({
706
+ sessionId: runId,
707
+ topology: "iterative-coding",
708
+ skipInterview: true,
709
+ ...(request !== undefined ? { request, integrityMode } : {}),
710
+ tasks: taskIds.map((id) => ({ id })),
711
+ })
712
+ for (const taskId of taskIds) {
713
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
714
+ await registeredTools.task_update.execute({ sessionId: runId, taskId, status })
715
+ }
716
+ await registeredTools.task_update.execute({
717
+ sessionId: runId,
718
+ taskId,
719
+ status: "verified_pass",
720
+ verification: { status: "PASS" },
721
+ })
722
+ writeTaskReport(runId, taskId, "PASS")
723
+ }
724
+ await registeredTools.security_audit.execute({
725
+ sessionId: runId,
726
+ status: auditStatus,
727
+ findings: auditStatus === "FAIL" ? [{ severity: "Critical", description: "hardcoded secret" }] : [],
728
+ })
729
+ }
730
+ const finalFileOf = (runId) => runFile(testDir, runId, "verify/final.json")
731
+
732
+ // (a) All tasks verified_pass + every report PASS + audit PASS -> PASS, stamped, event appended.
733
+ const fvPassRun = "20261018-000000-fv-pass"
734
+ await seedVerifiedRun(fvPassRun, ["F1", "F2"])
735
+ assert(!existsSync(runFile(testDir, fvPassRun, "ORIGINAL_REQUEST.md")), "fixture run must have no request artifact")
736
+ const fvPassEventsBefore = readEvents(testDir, fvPassRun).length
737
+ const fvPass = await registeredTools.final_verify.execute(
738
+ { sessionId: fvPassRun, summary: " All acceptance criteria met. " },
739
+ { sessionID: "ses_final_verify" },
740
+ )
741
+ assert.strictEqual(fvPass.status, "PASS", `complete evidence must PASS: ${fvPass.content}`)
742
+ assert.strictEqual(fvPass.finalReport, finalFileOf(fvPassRun), "the result must name verify/final.json")
743
+ assert(fvPass.content.includes("FINAL VERIFICATION PASSED"), `result must state the verdict: ${fvPass.content}`)
744
+ assert(fvPass.content.includes("development"), "result must state the integrity mode")
745
+ const fvPassReport = JSON.parse(readFileSync(finalFileOf(fvPassRun), "utf8"))
746
+ assert.strictEqual(fvPassReport.status, "PASS", "verify/final.json must record PASS")
747
+ assert.strictEqual(fvPassReport.generatedBy.session, "ses_final_verify", "generatedBy.session must record the calling session")
748
+ assert.strictEqual(fvPassReport.generatedBy.agent, null, "no session agent is available in this test")
749
+ assert(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(fvPassReport.generatedAt), "generatedAt must be ISO8601 UTC")
750
+ assert.strictEqual(fvPassReport.integrityMode, "development", "a run with no request artifact defaults to development")
751
+ assert.strictEqual(fvPassReport.summary, "All acceptance criteria met.", "summary must be cleaned and recorded")
752
+ assert.deepStrictEqual(
753
+ fvPassReport.evidence.tasks,
754
+ [
755
+ { id: "F1", status: "verified_pass", report: "verify/report-F1.json", reportStatus: "PASS" },
756
+ { id: "F2", status: "verified_pass", report: "verify/report-F2.json", reportStatus: "PASS" },
757
+ ],
758
+ "evidence.tasks must list each task id with its report path and status",
759
+ )
760
+ assert.deepStrictEqual(
761
+ fvPassReport.evidence.securityAudit,
762
+ { path: "verify/security-audit.json", status: "PASS" },
763
+ "evidence must record the security audit",
764
+ )
765
+ assert.strictEqual(fvPassReport.evidence.allTasksVerifiedPass, true)
766
+ assert.deepStrictEqual(fvPassReport.reasons, [], "a PASS verdict carries no reasons")
767
+ const fvPassEvents = readEvents(testDir, fvPassRun)
768
+ assert.strictEqual(fvPassEvents.length, fvPassEventsBefore + 1, "final_verify must append exactly one event")
769
+ const fvEvent = fvPassEvents[fvPassEvents.length - 1]
770
+ assert.strictEqual(fvEvent.event, "final_verification", "the event must be final_verification")
771
+ assert.strictEqual(fvEvent.to, "PASS")
772
+ assert.strictEqual(fvEvent.taskId, null)
773
+ assert.strictEqual(fvEvent.round, 0)
774
+ assert.strictEqual(typeof fvEvent.seq, "number", "the event must carry an engine-assigned seq")
775
+ assert(fvEvent.seq > 0, "seq must be positive")
776
+
777
+ // (h) The stamped PASS completes the run: ALL_PASSED with stamped: true.
778
+ const fvStampedGate = await registeredTools.next.execute({ sessionId: fvPassRun })
779
+ assert.strictEqual(fvStampedGate.status, "ALL_PASSED", `a stamped PASS must complete the run: ${fvStampedGate.content}`)
780
+ assert.strictEqual(fvStampedGate.stamped, true, "a stamped verdict must report stamped: true")
781
+ assert.notStrictEqual(fvStampedGate.unstampedBypass, true, "a stamped verdict is not a bypass")
782
+ assert.strictEqual(fvStampedGate.finalReport, finalFileOf(fvPassRun))
783
+ assert.strictEqual(fvStampedGate.integrityMode, "development")
784
+ assert.strictEqual(JSON.parse(readFileSync(runFile(testDir, fvPassRun, "state.json"), "utf8")).phase, "MERGE")
785
+
786
+ // (i) A hand-written PASS (no stamp) cannot complete the run by default.
787
+ const fvHandRun = "20261018-000000-fv-handwritten"
788
+ await seedVerifiedRun(fvHandRun, ["F1"])
789
+ const fvHandFile = finalFileOf(fvHandRun)
790
+ mkdirSync(dirname(fvHandFile), { recursive: true })
791
+ writeFileSync(fvHandFile, JSON.stringify({ status: "PASS", summary: "looks fine to me" }) + "\n")
792
+ const fvHandDefault = await registeredTools.next.execute({ sessionId: fvHandRun })
793
+ assert.strictEqual(
794
+ fvHandDefault.status,
795
+ "FINAL_VERIFICATION_UNVERIFIED",
796
+ `an unstamped PASS must be refused by default: ${fvHandDefault.content}`,
797
+ )
798
+ assert.strictEqual(fvHandDefault.finalReport, fvHandFile)
799
+ assert.strictEqual(fvHandDefault.integrityMode, "development")
800
+ assert(/teamwork_final_verify/.test(fvHandDefault.content), "the message must point at teamwork_final_verify")
801
+ assert(/allowUnstamped/.test(fvHandDefault.content), "the message must name the legacy bypass")
802
+ assert.strictEqual(
803
+ JSON.parse(readFileSync(runFile(testDir, fvHandRun, "state.json"), "utf8")).phase,
804
+ "FINAL_VERIFICATION",
805
+ "an unstamped PASS must leave the run in FINAL_VERIFICATION",
806
+ )
807
+
808
+ // (j) The same report with allowUnstamped: true completes, flagged and recorded.
809
+ const fvHandBypass = await registeredTools.next.execute({ sessionId: fvHandRun, allowUnstamped: true })
810
+ assert.strictEqual(fvHandBypass.status, "ALL_PASSED", `allowUnstamped must complete the run: ${fvHandBypass.content}`)
811
+ assert.strictEqual(fvHandBypass.stamped, false, "a bypassed verdict must report stamped: false")
812
+ assert.strictEqual(fvHandBypass.unstampedBypass, true, "a bypassed verdict must report unstampedBypass: true")
813
+ assert(/not produced by teamwork_final_verify/.test(fvHandBypass.content), "the message must state the verdict was not tool-produced")
814
+ assert.strictEqual(
815
+ JSON.parse(readFileSync(runFile(testDir, fvHandRun, "state.json"), "utf8")).phase,
816
+ "MERGE",
817
+ "the recorded bypass advances the run to MERGE",
818
+ )
819
+ const bypassEvent = readEvents(testDir, fvHandRun).filter((e) => e.event === "final_verification_bypass").pop()
820
+ assert(bypassEvent, "the bypass must be recorded as a final_verification_bypass event")
821
+ assert.strictEqual(bypassEvent.to, "ALL_PASSED")
822
+ assert.strictEqual(bypassEvent.taskId, null)
823
+ assert.strictEqual(bypassEvent.phase, "MERGE")
824
+ assert.strictEqual(typeof bypassEvent.note, "string", "the bypass event must carry a note")
825
+ assert(bypassEvent.note.includes("allowUnstamped"), `the note must explain the bypass: ${bypassEvent.note}`)
826
+ assert.strictEqual(typeof bypassEvent.seq, "number", "the bypass event must carry an engine-assigned seq")
827
+ assert(bypassEvent.seq > 0, "the bypass event seq must be positive")
828
+ assert.strictEqual(bypassEvent.agent, null, "no session agent is available in this test")
829
+
830
+ // (k) A report with provenance but no evidence is still unstamped.
831
+ const fvNoEvidenceRun = "20261018-000000-fv-noevidence"
832
+ await seedVerifiedRun(fvNoEvidenceRun, ["F1"])
833
+ writeFileSync(
834
+ finalFileOf(fvNoEvidenceRun),
835
+ JSON.stringify({
836
+ status: "PASS",
837
+ generatedBy: { agent: "team/verifier", session: "ses_handwritten" },
838
+ generatedAt: new Date().toISOString(),
839
+ integrityMode: "development",
840
+ reasons: [],
841
+ }) + "\n",
842
+ )
843
+ const fvNoEvidence = await registeredTools.next.execute({ sessionId: fvNoEvidenceRun })
844
+ assert.strictEqual(
845
+ fvNoEvidence.status,
846
+ "FINAL_VERIFICATION_UNVERIFIED",
847
+ `a report without evidence must be refused by default: ${fvNoEvidence.content}`,
848
+ )
849
+
850
+ // (l) A stamped FAIL still blocks the run (unchanged behaviour).
851
+ const fvStampedFailRun = "20261018-000000-fv-stampedfail"
852
+ await seedVerifiedRun(fvStampedFailRun, ["F1"])
853
+ const fvStampedFail = await registeredTools.final_verify.execute({
854
+ sessionId: fvStampedFailRun,
855
+ failReason: "acceptance criterion 1 is unmet",
856
+ })
857
+ assert.strictEqual(fvStampedFail.status, "FAIL")
858
+ const fvStampedFailGate = await registeredTools.next.execute({ sessionId: fvStampedFailRun })
859
+ assert.strictEqual(
860
+ fvStampedFailGate.status,
861
+ "BLOCKED_BY_FINAL_VERIFICATION",
862
+ "a stamped FAIL must still block the run",
863
+ )
864
+ assert.notStrictEqual(fvStampedFailGate.status, "ALL_PASSED")
865
+
866
+ // (b) A missing task report -> FAIL naming the task; the written file is FAIL too.
867
+ const fvMissingRun = "20261018-000000-fv-missing"
868
+ await seedVerifiedRun(fvMissingRun, ["F1", "F2"])
869
+ rmSync(reportFileOf(fvMissingRun, "F2"))
870
+ const fvMissing = await registeredTools.final_verify.execute({ sessionId: fvMissingRun })
871
+ assert.strictEqual(fvMissing.status, "FAIL", `a missing report must FAIL: ${fvMissing.content}`)
872
+ assert(
873
+ fvMissing.reasons.some((r) => r.includes("F2") && r.includes("MISSING")),
874
+ `the reason must name the task and the missing report: ${JSON.stringify(fvMissing.reasons)}`,
875
+ )
876
+ assert(fvMissing.content.includes("F2") && fvMissing.content.includes("MISSING"), "the message must state the reason")
877
+ assert.strictEqual(JSON.parse(readFileSync(finalFileOf(fvMissingRun), "utf8")).status, "FAIL", "the file must be written as FAIL")
878
+
879
+ // (f) Re-running cannot upgrade a FAIL file while the evidence still fails.
880
+ const fvSecond = await registeredTools.final_verify.execute({ sessionId: fvMissingRun })
881
+ assert.strictEqual(fvSecond.status, "FAIL", "a second call must recompute FAIL, not trust the previous call")
882
+ assert.strictEqual(
883
+ JSON.parse(readFileSync(finalFileOf(fvMissingRun), "utf8")).status,
884
+ "FAIL",
885
+ "a second call must not upgrade the artifact to PASS",
886
+ )
887
+
888
+ // (c) Security audit FAIL -> FAIL.
889
+ const fvAuditRun = "20261018-000000-fv-auditfail"
890
+ await seedVerifiedRun(fvAuditRun, ["F1"], { auditStatus: "FAIL" })
891
+ const fvAudit = await registeredTools.final_verify.execute({ sessionId: fvAuditRun })
892
+ assert.strictEqual(fvAudit.status, "FAIL", `a FAIL audit must FAIL the verdict: ${fvAudit.content}`)
893
+ assert(
894
+ fvAudit.reasons.some((r) => r.startsWith("security audit:") && r.includes("FAIL")),
895
+ `the reason must name the security audit: ${JSON.stringify(fvAudit.reasons)}`,
896
+ )
897
+ assert.strictEqual(JSON.parse(readFileSync(finalFileOf(fvAuditRun), "utf8")).status, "FAIL")
898
+
899
+ // (d) A task that is not verified_pass -> FAIL.
900
+ const fvPendingRun = "20261018-000000-fv-notpassed"
901
+ await registeredTools.plan.execute({ sessionId: fvPendingRun, topology: "iterative-coding", skipInterview: true, tasks: [{ id: "F1" }] })
902
+ writeTaskReport(fvPendingRun, "F1", "PASS")
903
+ await registeredTools.security_audit.execute({ sessionId: fvPendingRun, status: "PASS", findings: [] })
904
+ const fvPending = await registeredTools.final_verify.execute({ sessionId: fvPendingRun })
905
+ assert.strictEqual(fvPending.status, "FAIL", `an unverified task must FAIL: ${fvPending.content}`)
906
+ assert(
907
+ fvPending.reasons.some((r) => r.includes("F1") && r.includes("pending")),
908
+ `the reason must name the task and its status: ${JSON.stringify(fvPending.reasons)}`,
909
+ )
910
+ assert.strictEqual(JSON.parse(readFileSync(finalFileOf(fvPendingRun), "utf8")).status, "FAIL")
911
+
912
+ // (e) failReason forces FAIL even when the evidence is all PASS.
913
+ const fvForced = await registeredTools.final_verify.execute({
914
+ sessionId: fvPassRun,
915
+ failReason: "acceptance criterion 2 is unmet",
916
+ })
917
+ assert.strictEqual(fvForced.status, "FAIL", "failReason must force FAIL despite PASS evidence")
918
+ assert(fvForced.reasons.includes("acceptance criterion 2 is unmet"), "failReason must be appended to reasons")
919
+ assert.strictEqual(JSON.parse(readFileSync(finalFileOf(fvPassRun), "utf8")).status, "FAIL", "the forced FAIL must be written")
920
+
921
+ // (g) integrityMode comes from ORIGINAL_REQUEST.md when present, else development.
922
+ const fvBenchRun = "20261018-000000-fv-benchmark"
923
+ await seedVerifiedRun(fvBenchRun, ["F1"], { request: "Ship it.", integrityMode: "benchmark" })
924
+ const fvBench = await registeredTools.final_verify.execute({ sessionId: fvBenchRun })
925
+ assert.strictEqual(fvBench.status, "PASS", `complete benchmark evidence must PASS: ${fvBench.content}`)
926
+ assert.strictEqual(fvBench.integrityMode, "benchmark", "the result must carry the artifact's mode")
927
+ assert(fvBench.content.includes("benchmark"), "the message must state the artifact's mode")
928
+ assert.strictEqual(
929
+ JSON.parse(readFileSync(finalFileOf(fvBenchRun), "utf8")).integrityMode,
930
+ "benchmark",
931
+ "verify/final.json must record the artifact's mode",
932
+ )
933
+
934
+ console.log("✓ final_verify computes PASS only from evidence, stamps provenance + seq, and cannot be overridden")
935
+
936
+ // ==========================================
937
+ // Part 1c-quater: integrity mode enforcement
938
+ // ==========================================
939
+ console.log("Testing integrity mode enforcement...")
940
+
941
+ const INTEGRITY_RULES = {
942
+ fabricated_output: "development",
943
+ core_logic_copied: "demo",
944
+ delegated_core_work: "demo",
945
+ test_source_read: "demo",
946
+ external_dependency_used: "benchmark",
947
+ }
948
+ const MODE_ORDER = ["development", "demo", "benchmark"]
949
+ const forbiddenAt = (rule, mode) => MODE_ORDER.indexOf(mode) >= MODE_ORDER.indexOf(INTEGRITY_RULES[rule])
950
+ const auditFileOf = (runId) => runFile(testDir, runId, "verify/security-audit.json")
951
+
952
+ // One run per mode, each with its mode recorded in ORIGINAL_REQUEST.md.
953
+ const modeRuns = {}
954
+ for (const mode of MODE_ORDER) {
955
+ const runId = `20261018-000000-integrity-${mode}`
956
+ const planned = await registeredTools.plan.execute({
957
+ sessionId: runId,
958
+ topology: "iterative-coding",
959
+ skipInterview: true,
960
+ request: `Run at ${mode}.`,
961
+ integrityMode: mode,
962
+ tasks: [{ id: "I1" }],
963
+ })
964
+ assert(planned.content.startsWith("Planned"), `integrity fixture ${mode} must plan: ${planned.content}`)
965
+ modeRuns[mode] = runId
966
+ }
967
+
968
+ // Full 5 rules x 3 modes matrix, driven by the table (15 cases).
969
+ let matrixCases = 0
970
+ for (const mode of MODE_ORDER) {
971
+ for (const rule of Object.keys(INTEGRITY_RULES)) {
972
+ const res = await registeredTools.security_audit.execute({
973
+ sessionId: modeRuns[mode],
974
+ status: "PASS",
975
+ findings: [],
976
+ integrityFindings: [{ rule, where: "src/core.ts:1", why: "reported by the auditor" }],
977
+ })
978
+ const expected = forbiddenAt(rule, mode) ? "FAIL" : "PASS"
979
+ assert.strictEqual(res.status, expected, `${rule} at ${mode} must be ${expected}: ${res.content}`)
980
+ const report = JSON.parse(readFileSync(auditFileOf(modeRuns[mode]), "utf8"))
981
+ assert.strictEqual(report.status, expected, `${rule} at ${mode}: artifact status must be ${expected}`)
982
+ assert.strictEqual(report.integrityMode, mode, `${rule} at ${mode}: artifact must record the run's mode`)
983
+ assert.strictEqual(report.integrityFindings.length, 1, "the supplied finding must be persisted as-is")
984
+ assert.strictEqual(report.integrityFindings[0].rule, rule)
985
+ assert.strictEqual(
986
+ report.integrityViolations.length,
987
+ expected === "FAIL" ? 1 : 0,
988
+ `${rule} at ${mode}: violations must be the forbidden subset only`,
989
+ )
990
+ if (expected === "FAIL") {
991
+ const violation = report.integrityViolations[0]
992
+ assert.strictEqual(violation.rule, rule)
993
+ assert.strictEqual(violation.forbiddenFrom, INTEGRITY_RULES[rule], "the violation must carry its threshold")
994
+ assert.strictEqual(violation.where, "src/core.ts:1")
995
+ assert.strictEqual(violation.why, "reported by the auditor")
996
+ assert(res.content.includes(rule), `the FAIL message must name ${rule}: ${res.content}`)
997
+ assert(res.content.includes(mode), `the FAIL message must name the mode ${mode}: ${res.content}`)
998
+ }
999
+ matrixCases++
1000
+ }
1001
+ }
1002
+ assert.strictEqual(matrixCases, 15, "the matrix must cover 5 rules x 3 modes")
1003
+
1004
+ // A non-forbidden finding is recorded but never becomes a violation.
1005
+ const nonForbidden = await registeredTools.security_audit.execute({
1006
+ sessionId: modeRuns.demo,
1007
+ status: "PASS",
1008
+ findings: [],
1009
+ integrityFindings: [{ rule: "external_dependency_used", where: "package.json:5", why: "uses a library" }],
1010
+ })
1011
+ assert.strictEqual(nonForbidden.status, "PASS", "a benchmark-only rule must not fail a demo run")
1012
+ const nonForbiddenReport = JSON.parse(readFileSync(auditFileOf(modeRuns.demo), "utf8"))
1013
+ assert.strictEqual(nonForbiddenReport.integrityFindings[0].rule, "external_dependency_used")
1014
+ assert.deepStrictEqual(nonForbiddenReport.integrityViolations, [], "a non-forbidden rule must not be a violation")
1015
+
1016
+ // The input is capped at 50 findings.
1017
+ const capped = await registeredTools.security_audit.execute({
1018
+ sessionId: modeRuns.development,
1019
+ status: "PASS",
1020
+ findings: [],
1021
+ integrityFindings: Array.from({ length: 51 }, (_, i) => ({ rule: "fabricated_output", where: `f${i}` })),
1022
+ })
1023
+ assert.strictEqual(capped.status, "FAIL")
1024
+ assert.strictEqual(JSON.parse(readFileSync(auditFileOf(modeRuns.development), "utf8")).integrityFindings.length, 50, "at most 50 findings are persisted")
1025
+
1026
+ // An unknown rule id is refused before anything is written.
1027
+ const unknownRun = "20261018-000000-integrity-unknown"
1028
+ await registeredTools.plan.execute({
1029
+ sessionId: unknownRun,
1030
+ topology: "iterative-coding",
1031
+ skipInterview: true,
1032
+ request: "Unknown rule.",
1033
+ integrityMode: "development",
1034
+ tasks: [{ id: "I1" }],
1035
+ })
1036
+ assert(!existsSync(auditFileOf(unknownRun)), "fixture must start with no audit artifact")
1037
+ const unknownRule = await registeredTools.security_audit.execute({
1038
+ sessionId: unknownRun,
1039
+ status: "PASS",
1040
+ findings: [],
1041
+ integrityFindings: [{ rule: "made_up_rule" }],
1042
+ })
1043
+ assert(unknownRule.content.startsWith("refused: unknown integrity rule"), `an unknown rule must be refused: ${unknownRule.content}`)
1044
+ for (const rule of Object.keys(INTEGRITY_RULES)) {
1045
+ assert(unknownRule.content.includes(rule), `the refusal must list ${rule}: ${unknownRule.content}`)
1046
+ }
1047
+ assert(!existsSync(auditFileOf(unknownRun)), "an unknown rule must write no artifact")
1048
+
1049
+ // End-to-end: a violation forces the audit FAIL, and final_verify inherits it.
1050
+ const enforceRun = "20261018-000000-integrity-final"
1051
+ await seedVerifiedRun(enforceRun, ["I1"], { request: "Ship the demo.", integrityMode: "demo" })
1052
+ const enforceAudit = await registeredTools.security_audit.execute({
1053
+ sessionId: enforceRun,
1054
+ status: "PASS",
1055
+ findings: [],
1056
+ integrityFindings: [{ rule: "delegated_core_work", where: "src/gen.ts:9", why: "core produced by an external tool" }],
1057
+ })
1058
+ assert.strictEqual(enforceAudit.status, "FAIL", "a forbidden finding must force FAIL despite status PASS")
1059
+ const enforceReport = JSON.parse(readFileSync(auditFileOf(enforceRun), "utf8"))
1060
+ assert.strictEqual(enforceReport.status, "FAIL")
1061
+ assert.strictEqual(enforceReport.integrityMode, "demo", "the artifact must record the run's mode")
1062
+ assert(
1063
+ enforceReport.integrityViolations.some((v) => v.rule === "delegated_core_work" && v.forbiddenFrom === "demo"),
1064
+ "the artifact must persist the rule and its threshold",
1065
+ )
1066
+ const enforceFinal = await registeredTools.final_verify.execute({ sessionId: enforceRun })
1067
+ assert.strictEqual(enforceFinal.status, "FAIL", `final_verify must inherit the audit failure: ${enforceFinal.content}`)
1068
+ assert(
1069
+ enforceFinal.reasons.some((r) => r.startsWith("security audit:") && r.includes("FAIL")),
1070
+ `final_verify must name the security audit: ${JSON.stringify(enforceFinal.reasons)}`,
1071
+ )
1072
+ const enforceGate = await registeredTools.next.execute({ sessionId: enforceRun })
1073
+ assert.strictEqual(enforceGate.status, "BLOCKED_BY_SECURITY", "the run must stay blocked after a violation")
1074
+ assert.notStrictEqual(enforceGate.status, "ALL_PASSED")
1075
+
1076
+ console.log("✓ integrity findings enforced per mode, violations persisted with threshold, unknown rules refused")
1077
+
1078
+ // ==========================================
1079
+ // Part 1d: Transition graph + evidence for verified_pass
1080
+ // ==========================================
1081
+ console.log("Testing task transition graph & verified_pass evidence...")
1082
+
1083
+ const transitionRun = "20261018-000000-transitions"
1084
+ await registeredTools.plan.execute({
1085
+ sessionId: transitionRun,
1086
+ topology: "iterative-coding",
1087
+ skipInterview: true,
1088
+ tasks: [{ id: "G1" }, { id: "G2" }],
1089
+ })
1090
+ const transitionState = stateFileOf(transitionRun)
1091
+
1092
+ // (d) pending -> verified_pass is refused, even with inline PASS evidence.
1093
+ const jump = await registeredTools.task_update.execute({
1094
+ sessionId: transitionRun,
1095
+ taskId: "G1",
1096
+ status: "verified_pass",
1097
+ verification: { status: "PASS" },
1098
+ })
1099
+ assert(jump.content.startsWith("Error: Illegal transition"), `pending -> verified_pass must be refused: ${jump.content}`)
1100
+ assert(jump.content.includes("worker_active") && jump.content.includes("blocked"), `refusal must list allowed next states: ${jump.content}`)
1101
+ assert.strictEqual(JSON.parse(readFileSync(transitionState, "utf8")).tasks.G1.status, "pending", "a refused transition must not be persisted")
1102
+
1103
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
1104
+ const r = await registeredTools.task_update.execute({ sessionId: transitionRun, taskId: "G1", status })
1105
+ assert(r.content.includes("updated"), `legal ${status} transition must succeed: ${r.content}`)
1106
+ }
1107
+
1108
+ // (e) verifier_active -> verified_pass without evidence is refused.
1109
+ const noEvidence = await registeredTools.task_update.execute({
1110
+ sessionId: transitionRun,
1111
+ taskId: "G1",
1112
+ status: "verified_pass",
1113
+ })
1114
+ assert(noEvidence.content.startsWith("Error: Refusing verified_pass"), `evidence-free verified_pass must be refused: ${noEvidence.content}`)
1115
+ assert(noEvidence.content.includes("verification.status") && noEvidence.content.includes("report-G1.json"), `refusal must name both evidence paths: ${noEvidence.content}`)
1116
+ assert.strictEqual(JSON.parse(readFileSync(transitionState, "utf8")).tasks.G1.status, "verifier_active", "refusal must leave state unchanged")
1117
+
1118
+ // (f) verifier_active -> verified_pass with an inline PASS is accepted.
1119
+ const withEvidence = await registeredTools.task_update.execute({
1120
+ sessionId: transitionRun,
1121
+ taskId: "G1",
1122
+ status: "verified_pass",
1123
+ verification: { status: "PASS", passedChecks: 2, totalChecks: 2 },
1124
+ })
1125
+ assert.strictEqual(withEvidence.status, "verified_pass", `inline PASS evidence must be accepted: ${withEvidence.content}`)
1126
+ assert.strictEqual(JSON.parse(readFileSync(transitionState, "utf8")).tasks.G1.status, "verified_pass")
1127
+
1128
+ // (g) blocked stays reachable from verified_pass (escalation can never deadlock).
1129
+ const blockFromPass = await registeredTools.task_update.execute({
1130
+ sessionId: transitionRun,
1131
+ taskId: "G1",
1132
+ status: "blocked",
1133
+ })
1134
+ assert.strictEqual(blockFromPass.status, "blocked", `verified_pass -> blocked must be allowed: ${blockFromPass.content}`)
1135
+ assert.strictEqual(JSON.parse(readFileSync(transitionState, "utf8")).tasks.G1.status, "blocked")
1136
+
1137
+ // An on-disk PASS verifier report is equally valid evidence.
1138
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
1139
+ await registeredTools.task_update.execute({ sessionId: transitionRun, taskId: "G2", status })
1140
+ }
1141
+ const reportFile = join(testDir, ".opencode", "teamwork", transitionRun, "verify", "report-G2.json")
1142
+ mkdirSync(dirname(reportFile), { recursive: true })
1143
+ writeFileSync(reportFile, JSON.stringify({ taskId: "G2", status: "PASS", feedbackForWorker: "", fatalFindings: [] }) + "\n")
1144
+ const fromReport = await registeredTools.task_update.execute({
1145
+ sessionId: transitionRun,
1146
+ taskId: "G2",
1147
+ status: "verified_pass",
1148
+ })
1149
+ assert.strictEqual(fromReport.status, "verified_pass", `PASS report evidence must be accepted: ${fromReport.content}`)
1150
+
1151
+ console.log("✓ status jumps refused, verified_pass needs legal predecessor + PASS evidence, blocked reachable everywhere")
1152
+
1153
+ // ==========================================
1154
+ // Part 2: Max Rounds & Deadlock Detection
1155
+ // ==========================================
1156
+ console.log("Testing Max Rounds & Deadlock Detection...")
1157
+
1158
+ await registeredTools.plan.execute({
1159
+ sessionId: "20261018-000000-deadlock",
1160
+ topology: "distributed-coding",
1161
+ skipInterview: true,
1162
+ tasks: [
1163
+ { id: "A", dependsOn: [], maxRounds: 1 },
1164
+ { id: "B", dependsOn: ["A"], maxRounds: 2 },
1165
+ ],
1166
+ })
1167
+
1168
+ // Task A fails at round 1 (maxRounds is 1) -> verifier verdict coerces to blocked.
1169
+ for (const status of ["worker_active", "worker_done", "verifier_active"]) {
1170
+ await registeredTools.task_update.execute({
1171
+ sessionId: "20261018-000000-deadlock",
1172
+ taskId: "A",
1173
+ status,
1174
+ })
1175
+ }
1176
+ const updateBlockRes = await registeredTools.task_update.execute({
1177
+ sessionId: "20261018-000000-deadlock",
1178
+ taskId: "A",
1179
+ status: "verified_fail",
1180
+ round: 1,
1181
+ })
1182
+ assert.strictEqual(updateBlockRes.status, "blocked", "Task should be blocked when round >= maxRounds")
1183
+
1184
+ const deadlockNext = await registeredTools.next.execute({ sessionId: "20261018-000000-deadlock" })
1185
+ assert.strictEqual(deadlockNext.status, "DEADLOCK", "Should report DEADLOCK when all runnable paths are blocked")
1186
+
1187
+ console.log("✓ Max rounds & deadlock detection verified")
1188
+
1189
+ // ==========================================
1190
+ // Part 3: Git Worktree Operations & Synthesizer Conflict Artifact
1191
+ // ==========================================
1192
+ console.log("Testing Git Worktree Tool & Conflict Resolution...")
1193
+
1194
+ const gitRepoDir = mkdtempSync(join(tmpdir(), "teamwork-git-test-"))
1195
+ try {
1196
+ execFileSync("git", ["init"], { cwd: gitRepoDir, stdio: ["pipe", "pipe", "pipe"] })
1197
+ execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: gitRepoDir, stdio: ["pipe", "pipe", "pipe"] })
1198
+ execFileSync("git", ["config", "user.name", "Test Runner"], { cwd: gitRepoDir, stdio: ["pipe", "pipe", "pipe"] })
1199
+ writeFileSync(join(gitRepoDir, "README.md"), "# Teamwork Test Repo\n")
1200
+ execFileSync("git", ["add", "README.md"], { cwd: gitRepoDir, stdio: ["pipe", "pipe", "pipe"] })
1201
+ execFileSync("git", ["commit", "-m", "Initial commit"], { cwd: gitRepoDir, stdio: ["pipe", "pipe", "pipe"] })
1202
+
1203
+ const gitTools = {}
1204
+ await registerTeamworkTools(
1205
+ {
1206
+ tool: {
1207
+ transform: async (cb) => {
1208
+ await cb({
1209
+ namespace: () => {},
1210
+ add: (tool) => {
1211
+ gitTools[tool.name] = tool
1212
+ },
1213
+ })
1214
+ },
1215
+ },
1216
+ },
1217
+ gitRepoDir,
1218
+ )
1219
+
1220
+ const gitSessionId = `20261018-000000-${Math.random().toString(16).slice(2, 6)}`
1221
+ await gitTools.plan.execute({
1222
+ sessionId: gitSessionId,
1223
+ topology: "distributed-coding",
1224
+ skipInterview: true,
1225
+ tasks: [{ id: "feature-1" }],
1226
+ })
1227
+
1228
+ // 1. Setup sentinel worktree
1229
+ const sentinelSetup = await gitTools.worktree.execute({
1230
+ sessionId: gitSessionId,
1231
+ action: "setup",
1232
+ role: "sentinel",
1233
+ })
1234
+ assert(sentinelSetup.worktreePath, "Sentinel worktree path should be returned")
1235
+ assert.strictEqual(sentinelSetup.branch, `teamwork/base-${gitSessionId}`)
1236
+
1237
+ // 2. Setup worker worktree
1238
+ const workerSetup = await gitTools.worktree.execute({
1239
+ sessionId: gitSessionId,
1240
+ action: "setup",
1241
+ role: "worker",
1242
+ taskId: "feature-1",
1243
+ })
1244
+ assert(workerSetup.worktreePath, "Worker worktree path should be returned")
1245
+ assert.strictEqual(workerSetup.branch, `teamwork/${gitSessionId}-feature-1`)
1246
+
1247
+ // 3. Make change in worker worktree and commit
1248
+ writeFileSync(join(workerSetup.worktreePath, "feature.txt"), "hello world\n")
1249
+ execFileSync("git", ["add", "feature.txt"], { cwd: workerSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1250
+ execFileSync("git", ["commit", "-m", "Add feature.txt"], { cwd: workerSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1251
+
1252
+ // 4. Test diff
1253
+ const diffRes = await gitTools.worktree.execute({
1254
+ sessionId: gitSessionId,
1255
+ action: "diff",
1256
+ taskId: "feature-1",
1257
+ })
1258
+ assert(diffRes.hasChanges, "Diff should detect worker changes")
1259
+ assert(diffRes.content.includes("feature.txt"), "Diff content should mention feature.txt")
1260
+
1261
+ // 5. Test merge into sentinel base
1262
+ const mergeRes = await gitTools.worktree.execute({
1263
+ sessionId: gitSessionId,
1264
+ action: "merge",
1265
+ taskId: "feature-1",
1266
+ })
1267
+ assert(mergeRes.merged, "Merge should succeed without conflict")
1268
+ assert(!mergeRes.conflict)
1269
+
1270
+ // 6. Test conflict handling: worker modifies file differently than sentinel
1271
+ writeFileSync(join(sentinelSetup.worktreePath, "conflict.txt"), "sentinel version\n")
1272
+ execFileSync("git", ["add", "conflict.txt"], { cwd: sentinelSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1273
+ execFileSync("git", ["commit", "-m", "Sentinel commit"], { cwd: sentinelSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1274
+
1275
+ writeFileSync(join(workerSetup.worktreePath, "conflict.txt"), "worker conflicting version\n")
1276
+ execFileSync("git", ["add", "conflict.txt"], { cwd: workerSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1277
+ execFileSync("git", ["commit", "-m", "Worker conflicting commit"], { cwd: workerSetup.worktreePath, stdio: ["pipe", "pipe", "pipe"] })
1278
+
1279
+ const conflictMergeRes = await gitTools.worktree.execute({
1280
+ sessionId: gitSessionId,
1281
+ action: "merge",
1282
+ taskId: "feature-1",
1283
+ })
1284
+ assert(conflictMergeRes.conflict, "Should detect merge conflict")
1285
+ assert(conflictMergeRes.conflictArtifact, "Should generate conflict artifact path")
1286
+ assert(existsSync(conflictMergeRes.conflictArtifact), "Conflict artifact file must exist on disk")
1287
+
1288
+ // 7. Test conflict resolution action
1289
+ writeFileSync(join(sentinelSetup.worktreePath, "conflict.txt"), "synthesized combined version\n")
1290
+ const resolveRes = await gitTools.worktree.execute({
1291
+ sessionId: gitSessionId,
1292
+ action: "resolve",
1293
+ taskId: "feature-1",
1294
+ commitMessage: "Resolve conflict.txt via synthesizer",
1295
+ })
1296
+ assert(resolveRes.resolved, "Resolve action should succeed")
1297
+
1298
+ // 8. Cleanup worktrees
1299
+ const cleanupRes = await gitTools.worktree.execute({
1300
+ sessionId: gitSessionId,
1301
+ action: "cleanup",
1302
+ })
1303
+ assert(cleanupRes.cleaned, "Cleanup should succeed")
1304
+
1305
+ console.log("✓ Git worktree operations, conflict artifact generation & resolve action verified")
1306
+ } finally {
1307
+ rmSync(gitRepoDir, { recursive: true, force: true })
1308
+ }
1309
+
1310
+ // ==========================================
1311
+ // Part 4: CLI Run Management Helpers
1312
+ // ==========================================
1313
+ console.log("Testing CLI Run Management Helpers...")
1314
+
1315
+ const runsList = listTeamworkRuns(testDir)
1316
+ assert(runsList.length >= 2, "Should list created test runs")
1317
+ const testRun = runsList.find((r) => r.sessionId === "20261018-000000-test")
1318
+ assert(testRun, "Test run should be present in list")
1319
+ assert.strictEqual(testRun.securityStatus, "PASS", "Security status should be PASS")
1320
+
1321
+ const inspected = inspectTeamworkRun(testDir, "20261018-000000-test")
1322
+ assert(!inspected.error, "Inspect should succeed")
1323
+ assert.strictEqual(inspected.run.sessionId, "20261018-000000-test")
1324
+ assert(inspected.audit, "Security audit report should be included")
1325
+ assert(inspected.pitfalls.length > 0, "Pitfalls should be included")
1326
+
1327
+ console.log("✓ CLI run management helpers verified")
1328
+
1329
+ // ==========================================
1330
+ // Part 5: Model Map Priority Resolution
1331
+ // ==========================================
1332
+ console.log("Testing Model Map Priority Resolution (teamwork.json vs agent files)...")
1333
+ const configTestDir = mkdtempSync(join(tmpdir(), "teamwork-config-test-"))
1334
+ try {
1335
+ const agentsDir = join(configTestDir, "agents", "team")
1336
+ mkdirSync(agentsDir, { recursive: true })
1337
+ writeFileSync(join(agentsDir, "sentinel.md"), "---\nmodel: old-provider/old-model\n---\n")
1338
+
1339
+ // Without teamwork.json, file model takes precedence over default
1340
+ const modelsFromFile = currentModels(configTestDir)
1341
+ assert.strictEqual(modelsFromFile["team/sentinel"], "old-provider/old-model")
1342
+
1343
+ // When teamwork.json has custom override, it must take precedence over agent file
1344
+ writeModelMap(configTestDir, { "team/sentinel": "new-provider/new-model" })
1345
+ const modelsFromConfig = currentModels(configTestDir)
1346
+ assert.strictEqual(modelsFromConfig["team/sentinel"], "new-provider/new-model")
1347
+
1348
+ console.log("✓ Model map priority resolution verified (teamwork.json > agent files > defaults)")
1349
+ } finally {
1350
+ rmSync(configTestDir, { recursive: true, force: true })
1351
+ }
1352
+
1353
+ // ==========================================
1354
+ // Part 6: Attribution — actor identity, taskId buckets, byTaskTokens
1355
+ // ==========================================
1356
+ console.log("Testing attribution (actor identity, taskId buckets, byTaskTokens)...")
1357
+
1358
+ // Hermetic OpenCode environment: HOME and every XDG/AppData root that
1359
+ // tools.ts consults point at a temp dir, so the real opencode.db and
1360
+ // service.json are never read. The fake session DB lives in there too.
1361
+ const ENV_KEYS = ["HOME", "USERPROFILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "LOCALAPPDATA"]
1362
+ async function withIsolatedOpencodeEnv(fn) {
1363
+ const home = mkdtempSync(join(testDir, "home-"))
1364
+ const saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]))
1365
+ process.env.HOME = home
1366
+ process.env.USERPROFILE = home
1367
+ process.env.XDG_DATA_HOME = join(home, "data")
1368
+ process.env.XDG_STATE_HOME = join(home, "state")
1369
+ process.env.LOCALAPPDATA = join(home, "localappdata")
1370
+ try {
1371
+ return await fn({ dbPath: join(home, "data", "opencode", "opencode.db") })
1372
+ } finally {
1373
+ for (const k of ENV_KEYS) {
1374
+ if (saved[k] === undefined) delete process.env[k]
1375
+ else process.env[k] = saved[k]
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ // Probe ONCE which SQLite backend can seed the session_v2 fixture table:
1381
+ // node:sqlite (preferred) or the sqlite3 CLI. Returns null when neither exists.
1382
+ async function probeSqliteBackend() {
1383
+ try {
1384
+ const mod = await import("node:sqlite")
1385
+ if (typeof mod.DatabaseSync === "function") return "node:sqlite"
1386
+ } catch {}
1387
+ try {
1388
+ execFileSync("sqlite3", ["--version"], { stdio: ["pipe", "pipe", "pipe"] })
1389
+ return "sqlite3"
1390
+ } catch {}
1391
+ return null
1392
+ }
1393
+ const sqliteBackend = await probeSqliteBackend()
1394
+
1395
+ // Seed the session_v2 table that tools.ts reads. Errors propagate: a seeding
1396
+ // failure with a backend present is a real test failure, never a skip.
1397
+ async function seedSessionDb(dbPath, rows) {
1398
+ mkdirSync(dirname(dbPath), { recursive: true })
1399
+ const ddl = `DROP TABLE IF EXISTS session_v2;
1400
+ CREATE TABLE session_v2 (id TEXT PRIMARY KEY, parent_id TEXT, agent TEXT, cost REAL,
1401
+ tokens_input INTEGER, tokens_output INTEGER, tokens_reasoning INTEGER,
1402
+ tokens_cache_read INTEGER, tokens_cache_write INTEGER);`
1403
+ const values = rows.map(
1404
+ (r) =>
1405
+ `INSERT INTO session_v2 VALUES ('${r.id}', ${r.parent ? `'${r.parent}'` : "NULL"}, ${r.agent ? `'${r.agent}'` : "NULL"}, ${r.cost}, ${r.t.input}, ${r.t.output}, ${r.t.reasoning}, ${r.t.read}, ${r.t.write});`,
1406
+ )
1407
+ if (sqliteBackend === "node:sqlite") {
1408
+ const { DatabaseSync } = await import("node:sqlite")
1409
+ const db = new DatabaseSync(dbPath)
1410
+ try {
1411
+ db.exec(ddl + values.join("\n"))
1412
+ } finally {
1413
+ db.close()
1414
+ }
1415
+ } else {
1416
+ execFileSync("sqlite3", [dbPath], { input: ddl + values.join("\n"), stdio: ["pipe", "pipe", "pipe"] })
1417
+ }
1418
+ }
1419
+
1420
+ const ROOT_SES = "ses_attr_root"
1421
+ const CHILD_SES = "ses_attr_worker"
1422
+ const ZERO_T = { input: 0, output: 0, reasoning: 0, read: 0, write: 0 }
1423
+ const rootRow = { id: ROOT_SES, parent: null, agent: "sentinel", cost: 0, t: ZERO_T }
1424
+ const workerRow = (cost, t) => ({ id: CHILD_SES, parent: ROOT_SES, agent: "team/worker", cost, t })
1425
+ const T1 = { input: 1000, output: 200, reasoning: 10, read: 50, write: 5 }
1426
+
1427
+
1428
+ /** A fresh project root with the real tools registered and a run planned by the root session. */
1429
+ async function attrFixture(runId, planAgent = "team/worker", taskIds = ["alpha"], sessionAgent = undefined) {
1430
+ const root = mkdtempSync(join(testDir, "attr-"))
1431
+ const tools = {}
1432
+ await registerTeamworkTools(
1433
+ {
1434
+ tool: {
1435
+ transform: async (cb) => {
1436
+ await cb({
1437
+ namespace: () => {},
1438
+ add: (tool) => {
1439
+ tools[tool.name] = tool
1440
+ },
1441
+ })
1442
+ },
1443
+ },
1444
+ session: { get: async () => (sessionAgent ? { agent: sessionAgent } : undefined) },
1445
+ },
1446
+ root,
1447
+ )
1448
+ await tools.plan.execute(
1449
+ { sessionId: runId, topology: "iterative-coding", skipInterview: true, tasks: taskIds.map((id) => ({ id, agent: planAgent })) },
1450
+ { sessionID: ROOT_SES },
1451
+ )
1452
+ return { root, tools }
1453
+ }
1454
+
1455
+ const RUN_A = "20261018-000000-attr1"
1456
+ const RUN_B = "20261018-000000-attr2"
1457
+ const RUN_C = "20261018-000000-attr3"
1458
+ const RUN_D = "20261018-000000-attr4"
1459
+
1460
+ await withIsolatedOpencodeEnv(async ({ dbPath }) => {
1461
+ if (sqliteBackend === null) {
1462
+ console.log("⊘ skipped attribution DB tests: no node:sqlite and no sqlite3 CLI")
1463
+ return
1464
+ }
1465
+
1466
+ // --- 6a: non-root spend WITH a taskId buckets to the task, not to the agent.
1467
+ {
1468
+ const f = await attrFixture(RUN_A)
1469
+ await seedSessionDb(dbPath, [rootRow, workerRow(0.3, T1)])
1470
+ const res = await f.tools.cost.execute({ sessionId: RUN_A, taskId: "alpha" }, { sessionID: ROOT_SES })
1471
+ assert(res.content.includes("opencode database"), `spend must come from the session DB, got: ${res.content}`)
1472
+ const costs = JSON.parse(readFileSync(runFile(f.root, RUN_A, "costs.json"), "utf8"))
1473
+ assert.strictEqual(costs.byTask.alpha, 0.3, "subagent spend must bucket to the taskId")
1474
+ assert.strictEqual(costs.byTask["team/worker"], undefined, "byTask['team/worker'] must NOT grow when a taskId is given")
1475
+ assert.deepStrictEqual(Object.keys(costs.byTask), ["alpha"])
1476
+ assert.strictEqual(costs.spentUsd, 0.3)
1477
+ console.log("✓ non-root spend with taskId buckets to the task; byTask['team/worker'] does not grow")
1478
+ }
1479
+
1480
+ // --- 6b: the SAME fixture WITHOUT a taskId keeps the legacy agent-name bucket.
1481
+ {
1482
+ const f = await attrFixture(RUN_B)
1483
+ await seedSessionDb(dbPath, [rootRow, workerRow(0.3, T1)])
1484
+ await f.tools.cost.execute({ sessionId: RUN_B }, { sessionID: ROOT_SES })
1485
+ const costs = JSON.parse(readFileSync(runFile(f.root, RUN_B, "costs.json"), "utf8"))
1486
+ assert.strictEqual(costs.byTask["team/worker"], 0.3, "without a taskId, non-root spend must bucket by agent name")
1487
+ assert.deepStrictEqual(Object.keys(costs.byTask), ["team/worker"], "no task bucket may appear without a taskId")
1488
+ assert.deepStrictEqual(Object.keys(costs.byTaskTokens), ["team/worker"], "byTaskTokens keys must mirror byTask")
1489
+ console.log("✓ without taskId, non-root spend still buckets by agent name (legacy regression guard)")
1490
+ }
1491
+
1492
+ // --- 6c: byTaskTokens SUMS per-session token deltas across the whole tree.
1493
+ // Two child sessions and a non-zero root all map to the same taskId, so the
1494
+ // expected bucket is the sum of every contribution. A last-writer-wins
1495
+ // (absolute) write would leave only one session's total and fail here.
1496
+ {
1497
+ const f = await attrFixture(RUN_C)
1498
+ const ROOT_T1 = { input: 400, output: 80, reasoning: 4, read: 20, write: 2 }
1499
+ const CHILD2 = "ses_attr_worker2"
1500
+ const child2Row = (cost, t) => ({ id: CHILD2, parent: ROOT_SES, agent: "team/worker", cost, t })
1501
+ const T2 = { input: 300, output: 60, reasoning: 3, read: 10, write: 1 }
1502
+ // Call 1: root(R1) + child1(T1) + child2(T2) => sum of all three.
1503
+ await seedSessionDb(dbPath, [{ ...rootRow, t: ROOT_T1 }, workerRow(0.3, T1), child2Row(0.2, T2)])
1504
+ await f.tools.cost.execute({ sessionId: RUN_C, taskId: "alpha" }, { sessionID: ROOT_SES })
1505
+ // Call 2: root grows by R2-R1, child1 grows by T1'-T1, child2 unchanged. Only deltas may be added.
1506
+ const ROOT_T2 = { input: 500, output: 100, reasoning: 5, read: 30, write: 3 }
1507
+ const CHILD1_T2 = { input: 1500, output: 300, reasoning: 10, read: 50, write: 5 }
1508
+ await seedSessionDb(dbPath, [
1509
+ { ...rootRow, t: ROOT_T2 },
1510
+ workerRow(0.45, CHILD1_T2),
1511
+ child2Row(0.2, T2),
1512
+ ])
1513
+ await f.tools.cost.execute({ sessionId: RUN_C, taskId: "alpha" }, { sessionID: ROOT_SES })
1514
+ const costs = JSON.parse(readFileSync(runFile(f.root, RUN_C, "costs.json"), "utf8"))
1515
+ assert.strictEqual(costs.byTask.alpha, 0.65, "cost must accumulate 0.3 + 0.2 + 0.15 delta")
1516
+ // Expected = sum of all sessions' current totals: root(R2) + child1(T1') + child2(T2).
1517
+ assert.deepStrictEqual(costs.byTaskTokens.alpha, {
1518
+ input: 500 + 1500 + 300,
1519
+ output: 100 + 300 + 60,
1520
+ reasoning: 5 + 10 + 3,
1521
+ cache: { read: 30 + 50 + 10, write: 3 + 5 + 1 },
1522
+ }, "byTaskTokens must SUM per-session token deltas across the tree")
1523
+ const bucket = costs.byTaskTokens.alpha
1524
+ assert.deepStrictEqual(Object.keys(bucket).sort(), ["cache", "input", "output", "reasoning"])
1525
+ assert.deepStrictEqual(Object.keys(bucket.cache).sort(), ["read", "write"])
1526
+ for (const v of [bucket.input, bucket.output, bucket.reasoning, bucket.cache.read, bucket.cache.write]) {
1527
+ assert(Number.isFinite(v) && Number.isInteger(v) && v >= 0, `token value must be a finite non-negative integer, got ${v}`)
1528
+ }
1529
+ assert.deepStrictEqual(Object.keys(costs.byTaskTokens).sort(), Object.keys(costs.byTask).sort(), "byTaskTokens keys must match byTask keys")
1530
+ console.log("✓ byTaskTokens sums per-session token deltas across the tree (absolute-write mutation is caught)")
1531
+ }
1532
+
1533
+ // --- 6d: a pre-existing costs.json WITHOUT byTaskTokens is tolerated.
1534
+ {
1535
+ const f = await attrFixture(RUN_D)
1536
+ const file = runFile(f.root, RUN_D, "costs.json")
1537
+ const legacy = JSON.parse(readFileSync(file, "utf8"))
1538
+ delete legacy.byTaskTokens
1539
+ writeFileSync(file, JSON.stringify(legacy, null, 2) + "\n")
1540
+ await seedSessionDb(dbPath, [rootRow, workerRow(0.3, T1)])
1541
+ const res = await f.tools.cost.execute({ sessionId: RUN_D, taskId: "alpha" }, { sessionID: ROOT_SES })
1542
+ assert(res.content.includes("Budget:"), `cost must complete without crashing, got: ${res.content}`)
1543
+ const costs = JSON.parse(readFileSync(file, "utf8"))
1544
+ assert.strictEqual(costs.byTask.alpha, 0.3)
1545
+ assert.strictEqual(costs.byTaskTokens.alpha.input, 1000, "a legacy costs.json must gain the byTaskTokens bucket")
1546
+ console.log("✓ pre-existing costs.json without byTaskTokens is tolerated")
1547
+ }
1548
+ })
1549
+
1550
+ // --- 6e: actor identity recorded in events.jsonl (explicit agent wins).
1551
+ {
1552
+ const f = await attrFixture("20261018-000000-actor")
1553
+ const RUN = "20261018-000000-actor"
1554
+ const before = readEvents(f.root, RUN).length
1555
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active", agent: "team/worker" })
1556
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_done", agent: "team/worker" })
1557
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "verifier_active", agent: "team/verifier" })
1558
+ const events = readEvents(f.root, RUN)
1559
+ assert.strictEqual(events.length, before + 3, "exactly one event per transition")
1560
+ const [wa, wd, va] = events.slice(-3)
1561
+ assert.strictEqual(wa.agent, "team/worker", "explicit team/worker must be the recorded actor")
1562
+ assert.strictEqual(wd.agent, "team/worker")
1563
+ assert.strictEqual(va.agent, "team/verifier", "explicit team/verifier must be the recorded actor")
1564
+ assert.strictEqual(wa.agentSource, "explicit", "an input.agent actor must be labelled explicit")
1565
+ assert.strictEqual(wd.agentSource, "explicit")
1566
+ assert.strictEqual(va.agentSource, "explicit")
1567
+ console.log("✓ explicit agent (team/worker and team/verifier) is recorded as the actor in events.jsonl")
1568
+ }
1569
+
1570
+ // --- 6f: with no explicit agent and no calling session, the plan-declared agent is the fallback.
1571
+ {
1572
+ const RUN = "20261018-000000-plan"
1573
+ const f = await attrFixture(RUN, "team/worker")
1574
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active" })
1575
+ const last = readEvents(f.root, RUN).at(-1)
1576
+ assert.strictEqual(last.agent, "team/worker", "plan-declared agent must be the fallback actor")
1577
+ assert.strictEqual(last.agentSource, "plan", "a plan-declared actor must be labelled plan")
1578
+ console.log("✓ plan-declared agent is the fallback actor when none is supplied")
1579
+ }
1580
+
1581
+ // --- 6f(2): the calling session's agent wins over the plan and is labelled session.
1582
+ {
1583
+ const RUN = "20261018-000000-session"
1584
+ const f = await attrFixture(RUN, "team/worker", ["alpha"], "team/scout")
1585
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active" }, { sessionID: ROOT_SES })
1586
+ const last = readEvents(f.root, RUN).at(-1)
1587
+ assert.strictEqual(last.agent, "team/scout", "the session agent must beat the plan-declared agent")
1588
+ assert.strictEqual(last.agentSource, "session", "a session-resolved actor must be labelled session")
1589
+ console.log("✓ session-resolved agent is recorded with agentSource=session")
1590
+ }
1591
+
1592
+ // --- 6g: seq is one monotonic number space per events.jsonl, starting at 1.
1593
+ {
1594
+ const RUN = "20261018-000000-seq"
1595
+ const f = await attrFixture(RUN)
1596
+ rmSync(runFile(f.root, RUN, "events.jsonl"))
1597
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active", agent: "team/worker" })
1598
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_done", agent: "team/worker" })
1599
+ const events = readEvents(f.root, RUN)
1600
+ assert.deepStrictEqual(
1601
+ events.map((e) => [e.event, e.seq]),
1602
+ [["task_transition", 1], ["task_transition", 2]],
1603
+ "two consecutive appends must get seq 1 and 2",
1604
+ )
1605
+ console.log("✓ consecutive task_transition lines get seq 1 and 2")
1606
+ }
1607
+
1608
+ // --- 6h: a legacy events.jsonl without seq still appends the correct next value.
1609
+ {
1610
+ const RUN = "20261018-000000-legacy-seq"
1611
+ const f = await attrFixture(RUN)
1612
+ const file = runFile(f.root, RUN, "events.jsonl")
1613
+ const legacy = [
1614
+ { ts: "2026-10-18T10:00:00.000Z", event: "run_created", sessionId: RUN, taskId: null, from: null, to: "pending", round: 0, agent: null, branch: null, worktree: null, phase: "DAG_BUILD" },
1615
+ { ts: "2026-10-18T10:00:01.000Z", event: "task_transition", sessionId: RUN, taskId: "alpha", from: "pending", to: "worker_active", round: 1, agent: null, branch: null, worktree: null, phase: "DISPATCH" },
1616
+ ]
1617
+ writeFileSync(file, legacy.map((e) => JSON.stringify(e)).join("\n") + "\n")
1618
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active", agent: "team/worker" })
1619
+ const events = readEvents(f.root, RUN)
1620
+ assert.strictEqual(events.length, 3, "the append must leave the two legacy lines and add one")
1621
+ assert(!("seq" in events[0]) && !("seq" in events[1]), "legacy lines must be left untouched")
1622
+ assert.strictEqual(events[2].seq, 3, "the appended line must continue after the two legacy lines")
1623
+ console.log("✓ a legacy events.jsonl without seq appends the correct next seq")
1624
+ }
1625
+
1626
+ // --- 6i: a garbage agent with control characters cannot inject a second JSONL line.
1627
+ {
1628
+ const RUN = "20261018-000000-inject"
1629
+ const f = await attrFixture(RUN)
1630
+ const file = runFile(f.root, RUN, "events.jsonl")
1631
+ const linesBefore = readFileSync(file, "utf8").split("\n").filter((l) => l !== "").length
1632
+ const garbage = 'team/worker\n{"event":"injected"}\u2028FAKE'
1633
+ await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active", agent: garbage })
1634
+ const raw = readFileSync(file, "utf8")
1635
+ const physical = raw.split("\n").filter((l) => l !== "")
1636
+ assert.strictEqual(physical.length, linesBefore + 1, "the garbage agent must add exactly one physical line")
1637
+ for (const line of physical) assert.doesNotThrow(() => JSON.parse(line), `every line must parse: ${line}`)
1638
+ assert(!raw.includes("\u2028"), "no raw line separator may reach events.jsonl")
1639
+ // Sanitised value, not the raw garbage: control characters become spaces.
1640
+ assert.strictEqual(JSON.parse(physical.at(-1)).agent, 'team/worker {"event":"injected"} FAKE', "agent must be recorded sanitised")
1641
+ console.log("✓ garbage agent with newline cannot inject a second JSONL line; recorded value is sanitised")
1642
+ }
1643
+ } finally {
1644
+ rmSync(testDir, { recursive: true, force: true })
1645
+ }
1646
+
1647
+ // ==========================================
1648
+ // Part 1e: cumulative issue ledger (3.6)
1649
+ // ==========================================
1650
+ {
1651
+ console.log("Testing cumulative issue ledger (3.6)...")
1652
+ const ledgerDir = mkdtempSync(join(tmpdir(), "teamwork-ledger-test-"))
1653
+ try {
1654
+ const tools = {}
1655
+ await registerTeamworkTools(
1656
+ {
1657
+ tool: {
1658
+ transform: async (cb) => {
1659
+ await cb({ namespace: () => {}, add: (tool) => (tools[tool.name] = tool) })
1660
+ },
1661
+ },
1662
+ session: { get: async () => undefined },
1663
+ },
1664
+ ledgerDir,
1665
+ )
1666
+ const ledgerRunFile = (runId, name) => join(ledgerDir, ".opencode", "teamwork", runId, name)
1667
+ const ledgerStateOf = (runId) => JSON.parse(readFileSync(ledgerRunFile(runId, "state.json"), "utf8"))
1668
+ const planLedger = async (runId, maxRounds = 3) => {
1669
+ const r = await tools.plan.execute({
1670
+ sessionId: runId,
1671
+ topology: "iterative-coding",
1672
+ skipInterview: true,
1673
+ tasks: [{ id: "L1", maxRounds }],
1674
+ })
1675
+ assert(r.content.startsWith("Planned"), `ledger fixture plan must succeed: ${r.content}`)
1676
+ }
1677
+ const walk = async (runId, statuses, round) => {
1678
+ for (const status of statuses) {
1679
+ await tools.task_update.execute({ sessionId: runId, taskId: "L1", status, round, ...(status === "verified_pass" ? { verification: { status: "PASS" } } : {}) })
1680
+ }
1681
+ }
1682
+
1683
+ // (a) two consecutive failed rounds keep two unresolved entries, in order.
1684
+ const RUN = "20261018-000000-ledger"
1685
+ await planLedger(RUN)
1686
+ await walk(RUN, ["worker_active", "worker_done", "verifier_active"], 1)
1687
+ await tools.task_update.execute({ sessionId: RUN, taskId: "L1", status: "verified_fail", round: 1, feedback: "first issue" })
1688
+ await walk(RUN, ["worker_active", "worker_done", "verifier_active"], 2)
1689
+ await tools.task_update.execute({ sessionId: RUN, taskId: "L1", status: "verified_fail", round: 2, feedback: "second issue" })
1690
+ let st = ledgerStateOf(RUN)
1691
+ assert.deepStrictEqual(
1692
+ st.tasks.L1.feedbackLog.map((e) => [e.round, e.text, e.resolved]),
1693
+ [
1694
+ [1, "first issue", false],
1695
+ [2, "second issue", false],
1696
+ ],
1697
+ "two failed rounds must append two unresolved ledger entries in round order",
1698
+ )
1699
+ assert.strictEqual(st.tasks.L1.feedback, "second issue", "the latest-round feedback field must be unchanged")
1700
+
1701
+ // (b) teamwork_next exposes both entries in one string, each round-prefixed.
1702
+ let nextRes = await tools.next.execute({ sessionId: RUN })
1703
+ let worker = nextRes.readyForWorker.find((t) => t.id === "L1")
1704
+ assert(worker, "L1 must be ready for another worker round after two failures")
1705
+ assert.strictEqual(worker.feedback, "R1: first issue\nR2: second issue", "next must join every unresolved entry, oldest first")
1706
+ assert(!/[\x00-\x1f]/.test(worker.feedback.replace(/\n/g, "")), "only the engine's own newline separators may reach the payload")
1707
+
1708
+ // (c) verified_pass resolves every existing entry, in the same write.
1709
+ await walk(RUN, ["worker_active", "worker_done", "verifier_active", "verified_pass"], 3)
1710
+ st = ledgerStateOf(RUN)
1711
+ assert.strictEqual(st.tasks.L1.feedbackLog.length, 2, "verified_pass must preserve the ledger")
1712
+ assert(st.tasks.L1.feedbackLog.every((e) => e.resolved === true), "verified_pass must resolve every ledger entry")
1713
+
1714
+ // (d) a later teamwork_next no longer surfaces the resolved texts.
1715
+ nextRes = await tools.next.execute({ sessionId: RUN })
1716
+ assert(!(nextRes.readyForWorker || []).some((t) => t.id === "L1"), "a passed task is not dispatched again")
1717
+ const nextJson = JSON.stringify(nextRes)
1718
+ assert(!nextJson.includes("first issue") && !nextJson.includes("second issue"), "resolved feedback must not be surfaced")
1719
+
1720
+ // (e) the ledger caps at the newest 20 entries, dropping the oldest.
1721
+ const CAP_RUN = "20261018-000000-ledgercap"
1722
+ await planLedger(CAP_RUN)
1723
+ await tools.task_update.execute({ sessionId: CAP_RUN, taskId: "L1", status: "worker_active", round: 1 })
1724
+ for (let i = 1; i <= 21; i++) {
1725
+ await tools.task_update.execute({ sessionId: CAP_RUN, taskId: "L1", status: "worker_active", round: 1, feedback: `issue ${i}` })
1726
+ }
1727
+ const capLog = ledgerStateOf(CAP_RUN).tasks.L1.feedbackLog
1728
+ assert.strictEqual(capLog.length, 20, "feedbackLog must be capped at 20 entries")
1729
+ assert.strictEqual(capLog[0].text, "issue 2", "the cap must drop the oldest entry")
1730
+ assert.strictEqual(capLog.at(-1).text, "issue 21", "the cap must keep the newest entry")
1731
+ assert.deepStrictEqual(capLog.map((e) => e.text), Array.from({ length: 20 }, (_, i) => `issue ${i + 2}`), "the newest 20 must be kept in order")
1732
+
1733
+ // (f) a legacy run with only `feedback` (no ledger) still surfaces that text.
1734
+ const LEGACY_RUN = "20261018-000000-ledgerlegacy"
1735
+ await planLedger(LEGACY_RUN)
1736
+ const legacyFile = ledgerRunFile(LEGACY_RUN, "state.json")
1737
+ const legacyState = JSON.parse(readFileSync(legacyFile, "utf8"))
1738
+ legacyState.tasks.L1.feedback = "legacy only feedback"
1739
+ delete legacyState.tasks.L1.feedbackLog
1740
+ writeFileSync(legacyFile, JSON.stringify(legacyState, null, 2) + "\n")
1741
+ nextRes = await tools.next.execute({ sessionId: LEGACY_RUN })
1742
+ worker = nextRes.readyForWorker.find((t) => t.id === "L1")
1743
+ assert(worker, "legacy L1 must still be ready for a worker")
1744
+ assert.strictEqual(worker.feedback, "legacy only feedback", "a run without feedbackLog must fall back to the latest feedback")
1745
+
1746
+ console.log("✓ ledger accumulates per round, next surfaces unresolved entries, verified_pass resolves them, 20-entry cap, legacy fallback")
1747
+ } finally {
1748
+ rmSync(ledgerDir, { recursive: true, force: true })
1749
+ }
1750
+ }
1751
+
1752
+ // ==========================================
1753
+ // Part 7: SEC-1 / SEC-3 — prototype-key integrity and tool-result sanitising
1754
+ // ==========================================
1755
+ {
1756
+ console.log("Testing prototype-key integrity and tool-result sanitising (SEC-1, SEC-3)...")
1757
+ const testDir7 = mkdtempSync(join(tmpdir(), "teamwork-sec1-test-"))
1758
+ const protoSnapshot = () => Reflect.ownKeys(Object.prototype).map(String).sort().join(",")
1759
+ const protoBefore = protoSnapshot()
1760
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
1761
+ const costsOf = (root, runId) => JSON.parse(readFileSync(join(root, ".opencode", "teamwork", runId, "costs.json"), "utf8"))
1762
+ const stateOf = (root, runId) => JSON.parse(readFileSync(join(root, ".opencode", "teamwork", runId, "state.json"), "utf8"))
1763
+ // Any C0/DEL/C1 control character (incl. ESC, BEL, CSI U+009B, U+0085) in tool output.
1764
+ const CTRL = /[\x00-\x1f\x7f-\x9f]/
1765
+ const ENV7 = ["HOME", "USERPROFILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "LOCALAPPDATA"]
1766
+ const saved7 = Object.fromEntries(ENV7.map((k) => [k, process.env[k]]))
1767
+ const home7 = mkdtempSync(join(testDir7, "home-"))
1768
+ // Isolate from the real opencode.db / service.json so the manual addUsd path is deterministic.
1769
+ process.env.HOME = home7
1770
+ process.env.USERPROFILE = home7
1771
+ process.env.XDG_DATA_HOME = join(home7, "data")
1772
+ process.env.XDG_STATE_HOME = join(home7, "state")
1773
+ process.env.LOCALAPPDATA = join(home7, "localappdata")
1774
+
1775
+ try {
1776
+ const fixture = async (runId, taskIds = ["alpha"]) => {
1777
+ const root = mkdtempSync(join(testDir7, "sec1-"))
1778
+ const tools = {}
1779
+ await registerTeamworkTools(
1780
+ {
1781
+ tool: {
1782
+ transform: async (cb) => {
1783
+ await cb({ namespace: () => {}, add: (tool) => (tools[tool.name] = tool) })
1784
+ },
1785
+ },
1786
+ session: { get: async () => undefined },
1787
+ },
1788
+ root,
1789
+ )
1790
+ const planRes = await tools.plan.execute({ sessionId: runId, topology: "iterative-coding", skipInterview: true, tasks: taskIds.map((id) => ({ id })) }, {})
1791
+ assert(planRes.content.startsWith("Planned"), `fixture plan must succeed: ${planRes.content}`)
1792
+ return { root, tools }
1793
+ }
1794
+
1795
+ // --- 7a: a legal but Object.prototype-named task id keeps its spend (no NaN, no loss).
1796
+ {
1797
+ const RUN = "20261018-000000-sec1a"
1798
+ const f = await fixture(RUN)
1799
+ const res = await f.tools.cost.execute({ sessionId: RUN, taskId: "constructor", addUsd: 0.25 }, {})
1800
+ assert(!res.content.includes("NaN"), `breakdown must not contain NaN: ${res.content}`)
1801
+ const costs = costsOf(f.root, RUN)
1802
+ assert.strictEqual(costs.spentUsd, 0.25, "spentUsd must reflect the constructor-bucket spend")
1803
+ assert(hasOwn(costs.byTask, "constructor"), "constructor bucket must be persisted as an own key")
1804
+ assert.strictEqual(costs.byTask.constructor, 0.25, "constructor bucket must hold the amount")
1805
+ // A second spend accumulates into the same bucket.
1806
+ await f.tools.cost.execute({ sessionId: RUN, taskId: "constructor", addUsd: 0.5 }, {})
1807
+ assert.strictEqual(costsOf(f.root, RUN).byTask.constructor, 0.75, "constructor bucket must accumulate")
1808
+ console.log("✓ taskId 'constructor' is recorded: no NaN, spentUsd and bucket reflect the amount")
1809
+ }
1810
+
1811
+ // --- 7b: '__proto__' is REJECTED by the allowlist; nothing is recorded or silently dropped.
1812
+ {
1813
+ const RUN = "20261018-000000-sec1b"
1814
+ const f = await fixture(RUN)
1815
+ const res = await f.tools.cost.execute({ sessionId: RUN, taskId: "__proto__", addUsd: 0.5 }, {})
1816
+ assert(res.content.startsWith("refused"), `'__proto__' must be refused by validation, got: ${res.content}`)
1817
+ const costs = costsOf(f.root, RUN)
1818
+ assert.strictEqual(costs.spentUsd, 0, "a refused spend must not change spentUsd")
1819
+ assert(!hasOwn(costs.byTask, "__proto__"), "'__proto__' must not be stored as a bucket")
1820
+ for (const bad of ["../escape", "a/b", "_sentinel", ""]) {
1821
+ const r = await f.tools.cost.execute({ sessionId: RUN, taskId: bad, addUsd: 0.1 }, {})
1822
+ if (bad === "") {
1823
+ assert(!r.content.startsWith("refused"), "an empty taskId is treated as absent, not refused")
1824
+ } else {
1825
+ assert(r.content.startsWith("refused"), `taskId ${JSON.stringify(bad)} must be refused: ${r.content}`)
1826
+ }
1827
+ }
1828
+ console.log("✓ taskId '__proto__' (and path-like ids) are refused by validation, never silently dropped")
1829
+ }
1830
+
1831
+ // --- 7c: a task absent from the plan cannot be injected via an inherited member name.
1832
+ {
1833
+ const RUN = "20261018-000000-sec1c"
1834
+ const f = await fixture(RUN)
1835
+ for (const id of ["constructor", "__proto__", "toString", "hasOwnProperty"]) {
1836
+ const r = await f.tools.task_update.execute({ sessionId: RUN, taskId: id, status: "worker_active" }, {})
1837
+ assert(r.content.startsWith("Error: Task"), `task_update('${id}') for an absent task must be refused: ${r.content}`)
1838
+ }
1839
+ assert.deepStrictEqual(Object.keys(stateOf(f.root, RUN).tasks), ["alpha"], "state.json must gain no phantom task")
1840
+ console.log("✓ task_update for an absent 'constructor'/'__proto__' injects no phantom task")
1841
+ }
1842
+
1843
+ // --- 7d: a plan CAN declare 'constructor' as a normal task, and it works end to end.
1844
+ {
1845
+ const RUN = "20261018-000000-sec1d"
1846
+ const f = await fixture(RUN, ["constructor"])
1847
+ const st = stateOf(f.root, RUN)
1848
+ assert(hasOwn(st.tasks, "constructor"), "planned 'constructor' task must be an own key in state.json")
1849
+ const upd = await f.tools.task_update.execute({ sessionId: RUN, taskId: "constructor", status: "worker_active" }, {})
1850
+ assert(upd.content.startsWith("Task constructor updated"), `valid 'constructor' task must update: ${upd.content}`)
1851
+ assert.strictEqual(stateOf(f.root, RUN).tasks.constructor.status, "worker_active")
1852
+ console.log("✓ a planned task named 'constructor' is an ordinary task")
1853
+ }
1854
+
1855
+ // --- 7e: plan refuses unsafe ids (task or dependsOn) and writes nothing for the refused plan.
1856
+ {
1857
+ const RUN = "20261018-000000-sec1e"
1858
+ const f = await fixture(RUN, ["ok"])
1859
+ const before = readFileSync(join(f.root, ".opencode", "teamwork", RUN, "plan.dag.json"), "utf8")
1860
+ for (const bad of [
1861
+ { tasks: [{ id: "__proto__" }] },
1862
+ { tasks: [{ id: "constructor/../x" }] },
1863
+ { tasks: [{ id: "ok2" }, { id: "a b" }] },
1864
+ { tasks: [{ id: "ok2", dependsOn: ["../up"] }] },
1865
+ ]) {
1866
+ const r = await f.tools.plan.execute({ sessionId: RUN, topology: "iterative-coding", ...bad }, {})
1867
+ assert(r.content.startsWith("refused"), `plan with unsafe id must be refused: ${r.content}`)
1868
+ }
1869
+ const after = readFileSync(join(f.root, ".opencode", "teamwork", RUN, "plan.dag.json"), "utf8")
1870
+ assert.strictEqual(after, before, "a refused plan must not overwrite plan.dag.json")
1871
+ console.log("✓ teamwork_plan refuses unsafe task ids and dependsOn before writing anything")
1872
+ }
1873
+
1874
+ // --- 7f: SEC-3 — the branch echoed by task_update carries no raw control characters.
1875
+ {
1876
+ const RUN = "20261018-000000-sec3a"
1877
+ const f = await fixture(RUN)
1878
+ const hostile = "feat\x1b]52;c;SGVsbG8=\x07\u009b31m\x7f\u0085\u2028end"
1879
+ const r = await f.tools.task_update.execute({ sessionId: RUN, taskId: "alpha", status: "worker_active", branch: hostile }, {})
1880
+ assert(r.content.includes("branch=feat"), `branch must still be echoed: ${r.content}`)
1881
+ assert(!CTRL.test(r.content), `tool-result content must carry no control character: ${JSON.stringify(r.content)}`)
1882
+ assert(!r.content.includes("\u2028"), "no line separator in content")
1883
+ console.log("✓ task_update echoes the branch with ESC/OSC52/C1/DEL/U+0085 removed")
1884
+ }
1885
+
1886
+ // --- 7g: SEC-3 — a hostile bucket key (legacy costs.json) is not echoed raw by cost.
1887
+ {
1888
+ const RUN = "20261018-000000-sec3b"
1889
+ const f = await fixture(RUN)
1890
+ const file = join(f.root, ".opencode", "teamwork", RUN, "costs.json")
1891
+ const costs = costsOf(f.root, RUN)
1892
+ costs.byTask = { ["k\x1b]52;c;QQ==\x07\u009b\x7f\u0085z"]: 0.1 }
1893
+ costs.spentUsd = 0.1
1894
+ writeFileSync(file, JSON.stringify(costs))
1895
+ const r = await f.tools.cost.execute({ sessionId: RUN }, {})
1896
+ assert(r.content.includes("$0.1"), `breakdown must still show the amount: ${r.content}`)
1897
+ // The template's own "\n" line separators are allowed; nothing else may be control.
1898
+ assert(!CTRL.test(r.content.replace(/\n/g, "")), `cost breakdown must carry no control character: ${JSON.stringify(r.content)}`)
1899
+ console.log("✓ teamwork_cost echoes bucket keys with ESC/OSC52/C1/DEL/U+0085 removed")
1900
+ }
1901
+
1902
+ // --- 7h: per-task tokens through the session tree still accumulate for a 'constructor' bucket.
1903
+ {
1904
+ let haveSqlite = true
1905
+ try {
1906
+ await import("node:sqlite")
1907
+ } catch {
1908
+ haveSqlite = false
1909
+ }
1910
+ if (!haveSqlite) {
1911
+ console.log("⊘ skipped 'constructor' token-tree test: no node:sqlite")
1912
+ } else {
1913
+ const { DatabaseSync } = await import("node:sqlite")
1914
+ const RUN = "20261018-000000-sec1h"
1915
+ const f = await fixture(RUN)
1916
+ const dbPath = join(home7, "data", "opencode", "opencode.db")
1917
+ mkdirSync(dirname(dbPath), { recursive: true })
1918
+ const db = new DatabaseSync(dbPath)
1919
+ try {
1920
+ db.exec(`DROP TABLE IF EXISTS session_v2;
1921
+ CREATE TABLE session_v2 (id TEXT PRIMARY KEY, parent_id TEXT, agent TEXT, cost REAL,
1922
+ tokens_input INTEGER, tokens_output INTEGER, tokens_reasoning INTEGER,
1923
+ tokens_cache_read INTEGER, tokens_cache_write INTEGER);
1924
+ INSERT INTO session_v2 VALUES ('ses_sec1_root', NULL, 'sentinel', 0, 0, 0, 0, 0, 0);
1925
+ INSERT INTO session_v2 VALUES ('ses_sec1_worker', 'ses_sec1_root', 'team/worker', 0.3, 1000, 200, 10, 50, 5);`)
1926
+ } finally {
1927
+ db.close()
1928
+ }
1929
+ const res = await f.tools.cost.execute({ sessionId: RUN, taskId: "constructor" }, { sessionID: "ses_sec1_root" })
1930
+ assert(!res.content.includes("NaN"), `no NaN in breakdown: ${res.content}`)
1931
+ const costs = costsOf(f.root, RUN)
1932
+ assert.strictEqual(costs.byTask.constructor, 0.3, "worker spend must bucket to 'constructor'")
1933
+ assert.strictEqual(costs.spentUsd, 0.3)
1934
+ assert(hasOwn(costs.byTaskTokens, "constructor"), "byTaskTokens must hold an own 'constructor' key")
1935
+ assert.deepStrictEqual(costs.byTaskTokens.constructor, {
1936
+ input: 1000,
1937
+ output: 200,
1938
+ reasoning: 10,
1939
+ cache: { read: 50, write: 5 },
1940
+ })
1941
+ console.log("✓ per-task tokens accumulate through the session tree for a 'constructor' bucket")
1942
+ }
1943
+ }
1944
+
1945
+ // --- 7i: Object.prototype was never modified by any of the above.
1946
+ assert.strictEqual(protoSnapshot(), protoBefore, "Object.prototype must have no new or removed own keys")
1947
+ assert.strictEqual(({}).spentUsd, undefined, "no global pollution via spentUsd")
1948
+ assert.strictEqual(({}).lastCost, undefined, "no global pollution via lastCost")
1949
+ console.log("✓ Object.prototype is unmodified after all SEC-1/SEC-3 cases")
1950
+ } finally {
1951
+ for (const k of ENV7) {
1952
+ if (saved7[k] === undefined) delete process.env[k]
1953
+ else process.env[k] = saved7[k]
1954
+ }
1955
+ rmSync(testDir7, { recursive: true, force: true })
1956
+ }
1957
+ }
1958
+
1959
+ // ==========================================
1960
+ // Part 8: read-only policy drift
1961
+ // ==========================================
1962
+ {
1963
+ console.log("Testing read-only policy drift...")
1964
+ const repoRoot = fileURLToPath(new URL("..", import.meta.url))
1965
+
1966
+ // Source of truth for this test: each agent's code-enforced deny set. The
1967
+ // shell caveat is derived from the deny set, never restated, so the table
1968
+ // cannot disagree with itself.
1969
+ const POLICY = [
1970
+ { id: "team/verifier", deny: ["edit", "subagent", "webfetch"] },
1971
+ { id: "team/falsifier", deny: ["edit", "shell", "subagent"] },
1972
+ { id: "team/scout", deny: ["edit", "subagent"] },
1973
+ { id: "team/security-auditor", deny: ["edit", "subagent", "webfetch"] },
1974
+ ].map((p) => ({ ...p, deny: [...p.deny].sort() }))
1975
+
1976
+ // --- 8a: READ_ONLY_ACTIONS holds exactly the documented deny sets.
1977
+ const toolsSrc = readFileSync(join(repoRoot, "plugins/opencode-teamwork/tools.ts"), "utf8")
1978
+ const table = toolsSrc.match(/const READ_ONLY_ACTIONS[^=]*=\s*\{([\s\S]*?)\n\}/)
1979
+ assert(table, "READ_ONLY_ACTIONS table must exist in tools.ts")
1980
+ const enforced = {}
1981
+ for (const m of table[1].matchAll(/"([^"]+)":\s*new Set\(\[([^\]]*)\]\)/g)) {
1982
+ enforced[m[1]] = [...m[2].matchAll(/"([^"]+)"/g)].map((a) => a[1]).sort()
1983
+ }
1984
+ assert.deepStrictEqual(
1985
+ Object.keys(enforced).sort(),
1986
+ POLICY.map((p) => p.id).sort(),
1987
+ "READ_ONLY_ACTIONS must list exactly the agents covered by this test",
1988
+ )
1989
+ for (const p of POLICY) {
1990
+ assert.deepStrictEqual(enforced[p.id], p.deny, `${p.id}: code deny set drifted: ${JSON.stringify(enforced[p.id])}`)
1991
+ }
1992
+ console.log("✓ READ_ONLY_ACTIONS matches the expected deny set for all four read-only agents")
1993
+
1994
+ // --- 8b: every agent whose code policy denies `edit` is documented in the
1995
+ // README read-only paragraph (parsed, not a duplicate hard-coded list).
1996
+ const readme = readFileSync(join(repoRoot, "README.md"), "utf8")
1997
+ const start = readme.indexOf("per-agent read-only policy")
1998
+ assert(start >= 0, "README must state the per-agent read-only policy")
1999
+ const end = readme.indexOf("\n\n", start)
2000
+ const paragraph = readme.slice(start, end === -1 ? undefined : end)
2001
+ const documented = [...new Set([...paragraph.matchAll(/`(team\/[a-z-]+)`/g)].map((m) => m[1]))].sort()
2002
+ const editDeniers = POLICY.filter((p) => p.deny.includes("edit")).map((p) => p.id).sort()
2003
+ assert.deepStrictEqual(documented, editDeniers, "README must document exactly the edit-denying agents as read-only")
2004
+ assert(/can modify files/i.test(paragraph), "README must state that shell can modify files")
2005
+ assert(
2006
+ /falsifier[^.]*shell|shell[^.]*falsifier/i.test(paragraph),
2007
+ "README must state that the falsifier's deny set includes shell",
2008
+ )
2009
+ console.log("✓ README documents every edit-denying team agent, plus the shell caveat and the falsifier exception")
2010
+
2011
+ // --- 8c: each agent description matches its own deny set.
2012
+ for (const p of POLICY) {
2013
+ const name = p.id.replace(/^team\//, "")
2014
+ const src = readFileSync(join(repoRoot, "agents/team", `${name}.md`), "utf8")
2015
+ const fm = src.match(/^---\r?\n([\s\S]*?)\r?\n---/)
2016
+ assert(fm, `${p.id}: frontmatter must exist`)
2017
+ const desc = fm[1].match(/^description:\s*"([^"]*)"/m)
2018
+ assert(desc, `${p.id}: quoted description must exist`)
2019
+ const text = desc[1]
2020
+ if (p.deny.includes("shell")) {
2021
+ assert(
2022
+ !/shell[^.]*can modify files/i.test(text),
2023
+ `${p.id}: description must not carry the shell caveat (its deny set includes shell): ${text}`,
2024
+ )
2025
+ assert(/shell[^.]*denied|denied[^.]*shell/i.test(text), `${p.id}: description must say shell is denied: ${text}`)
2026
+ } else {
2027
+ assert(
2028
+ /shell[^.]*can modify files/i.test(text),
2029
+ `${p.id}: description must warn that shell is available and can modify files: ${text}`,
2030
+ )
2031
+ }
2032
+ }
2033
+ console.log("✓ each read-only agent description matches its own deny set (shell caveat only where shell is allowed)")
2034
+
2035
+ // --- 8d: GUARDRAILS states the same guarantee.
2036
+ const guardrails = readFileSync(join(repoRoot, "docs/GUARDRAILS.md"), "utf8")
2037
+ const row = guardrails.split("\n").find((line) => line.includes("Read-only enforcement"))
2038
+ assert(row, "GUARDRAILS must keep the read-only enforcement row")
2039
+ assert(/shell/i.test(row) && /can modify files/i.test(row), "GUARDRAILS read-only row must state the shell caveat")
2040
+ console.log("✓ GUARDRAILS read-only row states the edit-only guarantee and the shell caveat")
2041
+ }