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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,806 @@
1
+ # Teamwork artifacts
2
+
3
+ Single source of truth for the files every Teamwork run reads and writes, and
4
+ for the topologies the coordinator may pick. Agents reference this file instead
5
+ of redefining formats.
6
+
7
+ ## Layout
8
+
9
+ Every run writes under one root:
10
+
11
+ ```
12
+ .opencode/teamwork/<session-id>/
13
+ ├── prompt_draft.md # spec (from the crafter, or inlined by the sentinel); required by teamwork_plan unless bypassed
14
+ ├── ORIGINAL_REQUEST.md # verbatim routed request + integrity mode (write-once; absent on legacy runs)
15
+ ├── plan.dag.json # task DAG (+ preflight gate result)
16
+ ├── preflight.json # input-checks report (written by teamwork_preflight)
17
+ ├── state.json # resumable coordinator state
18
+ ├── costs.json # coordinator-maintained budget tracker
19
+ ├── events.jsonl # append-only lifecycle event log (JSON Lines)
20
+ ├── pitfalls.md # answer-agnostic failure registry
21
+ ├── scout-report.md # scout output
22
+ ├── candidates/cand-<n>.md # one per proposer
23
+ ├── critiques/crit-<n>.md # one per falsifier
24
+ ├── synthesis/syn-<n>.md # one per synthesizer run
25
+ ├── synthesis/conflict-<task>.json # git 3-way merge conflict artifact
26
+ ├── verify/report-<task>.json
27
+ ├── verify/summary.json
28
+ ├── verify/security-audit.json # pre-merge security gate report
29
+ ├── final.md # presented result
30
+ ├── report.html / report.md # optional export output (`opencode-teamwork export`)
31
+ └── interrupted.md # present when the user stops a run
32
+ ```
33
+
34
+ `<session-id>` = `YYYYMMDD-HHMMSS-<4 hex>`.
35
+
36
+ Worktrees are created **outside the repository** (nested git worktrees inside
37
+ the repo are a footgun). Default root: `$TEAMWORK_WORKTREES_DIR` or
38
+ `../.teamwork-worktrees/<session-id>/`.
39
+
40
+ ## Topologies
41
+
42
+ | Topology | Shape |
43
+ | --- | --- |
44
+ | `small-focused` | 1 worker + 1 verifier loop |
45
+ | `iterative-coding` | 1 worker, test-driven tight loop on one module |
46
+ | `distributed-coding` | N workers fan-out + merge |
47
+ | `proof` | 1 strategist + 3-5 searchers + 1 formal checker |
48
+ | `massive-proof` | 1 meta-coordinator + 100+ searchers (opt-in) |
49
+ | `document-review` | 1 chair + 3 critics + 1 aggregator |
50
+
51
+ Legacy aliases — accept them, normalize on write:
52
+ `large-swarm` → `distributed-coding`, `doc-review` → `document-review`,
53
+ `long-proof` → `proof`, `massive-proof-swarm` → `massive-proof`.
54
+
55
+ ## Integrity modes
56
+
57
+ Every run is routed with one integrity mode. It is recorded in
58
+ `ORIGINAL_REQUEST.md`, copied to `state.json` and `plan.dag.json`, and read back
59
+ by the security auditor and the final-verification gate from
60
+ `ORIGINAL_REQUEST.md` (never from the caller). The orchestrator records and
61
+ reports it; the auditor reports rule violations and the audit tool makes them
62
+ binding (see [Integrity rules](#integrity-rules)).
63
+
64
+ | Mode | Meaning |
65
+ | --- | --- |
66
+ | `development` | Default. Reuse, libraries and frameworks are allowed; only fabricated outputs and facade implementations are ruled out. |
67
+ | `demo` | Also forbids copying core logic from open source, delegating core work to external tools, and reading test sources to reverse-engineer expected behaviour. |
68
+ | `benchmark` | A fully independent from-scratch implementation using the language standard library only. |
69
+
70
+ `development` is the default: `teamwork_plan` applies it when `integrityMode` is
71
+ omitted, and the auditor and final gate apply it to legacy runs with no
72
+ `ORIGINAL_REQUEST.md`. Any other value is refused before anything is written.
73
+
74
+ ### Integrity rules
75
+
76
+ The auditor reports structured integrity claims as `integrityFindings` on
77
+ `teamwork_security_audit`. Each rule is forbidden from a given mode onward, and
78
+ every stricter mode inherits it:
79
+
80
+ | Rule | Forbidden from |
81
+ | --- | --- |
82
+ | `fabricated_output` | `development` (always blocking) |
83
+ | `core_logic_copied` | `demo` |
84
+ | `delegated_core_work` | `demo` |
85
+ | `test_source_read` | `demo` |
86
+ | `external_dependency_used` | `benchmark` |
87
+
88
+ A finding whose rule is forbidden at the run's mode is a **violation**. Any
89
+ violation forces the audit to `FAIL` regardless of severity counts, so
90
+ `teamwork_final_verify` cannot reach `PASS` and the merge stays blocked; the
91
+ audit result names the violated rules and the mode. An unknown rule id is
92
+ refused before anything is written.
93
+
94
+ **Limitation.** The tool cannot detect dishonesty. It does not inspect the code
95
+ to prove a rule was broken; it takes the auditor's report at face value and
96
+ makes a reported violation binding on the gate.
97
+
98
+ ## Schemas
99
+
100
+ ### `ORIGINAL_REQUEST.md` — verbatim routed request (write-once)
101
+
102
+ `teamwork_plan` writes this file once, **before** `plan.dag.json` and
103
+ `state.json`, when its optional `request` input is provided. It is the artifact
104
+ the auditor reads the integrity mode from, and the path to hand any auditor that
105
+ checks the work against the original request.
106
+
107
+ - **Write-once.** If the file already exists with non-empty content, a second
108
+ plan into the same run is refused ("write-once ... use a new session") and
109
+ writes nothing else.
110
+ - **Verbatim.** The request text is preserved exactly — no reflow, no trimming
111
+ of interior whitespace — and capped at 20,000 characters. A longer request is
112
+ refused, never silently truncated.
113
+ - **Legacy tolerance.** When `request` is omitted, no file is created; the run
114
+ still plans and the mode defaults to `development`.
115
+
116
+ Format:
117
+
118
+ ~~~markdown
119
+ # Original Request
120
+
121
+ - Integrity mode: demo
122
+ - Recorded: 2026-01-12T10:15:00.000Z
123
+ - Session: 20260112-101500-a1b2
124
+
125
+ ## Request
126
+
127
+ <verbatim request>
128
+ ~~~
129
+
130
+ ### `spec.json` — one per dispatched worker (written by the sentinel)
131
+
132
+ ```json
133
+ {
134
+ "taskId": "R1-impl",
135
+ "sessionId": "20260112-101500-a1b2",
136
+ "title": "Implement R1",
137
+ "topology": "distributed-coding",
138
+ "objective": "one sentence",
139
+ "requirements": ["R1", "R2"],
140
+ "acceptanceCriteria": ["- [ ] ...", "- [ ] ..."],
141
+ "localChecks": ["npm test -- foo"],
142
+ "verification": ["how the verifier proves PASS"],
143
+ "dependencies": [{ "taskId": "R0", "artifacts": ["synthesis/syn-1.md"] }],
144
+ "avoidPitfalls": ["assumes input is sorted"],
145
+ "worktree": "/abs/path/to/worktree",
146
+ "baseBranch": "teamwork/base-<session-id>",
147
+ "constraints": { "network": "allowed", "sandbox": "worktree-only" }
148
+ }
149
+ ```
150
+
151
+ `constraints.network`: `allowed | denied | whitelist`.
152
+ `constraints.sandbox`: `full | read-only | worktree-only`.
153
+
154
+ ### `plan.dag.json`
155
+
156
+ ```json
157
+ {
158
+ "sessionId": "20260112-101500-a1b2",
159
+ "topology": "distributed-coding",
160
+ "integrityMode": "development",
161
+ "preflight": { "status": "READY", "bypassed": false },
162
+ "tasks": [
163
+ {
164
+ "id": "R1-impl",
165
+ "dependsOn": [],
166
+ "requirements": ["R1"],
167
+ "agent": "team/worker",
168
+ "status": "pending",
169
+ "round": 0,
170
+ "maxRounds": 4
171
+ }
172
+ ]
173
+ }
174
+ ```
175
+
176
+ ### `state.json` — coordinator checkpoint (rewritten on every transition)
177
+
178
+ ```json
179
+ {
180
+ "version": 1,
181
+ "sessionId": "20260112-101500-a1b2",
182
+ "integrityMode": "development",
183
+ "phase": "LOAD_SPEC|WORKTREE_INIT|DAG_BUILD|DISPATCH|SECURITY_AUDIT|FINAL_VERIFICATION|MERGE|PRESENT_PARTIAL|DONE",
184
+ "tasks": {
185
+ "R1-impl": {
186
+ "status": "pending|worker_active|worker_done|verifier_active|verified_pass|verified_fail|blocked",
187
+ "round": 1,
188
+ "branch": "teamwork/20260112-101500-a1b2-R1-impl",
189
+ "worktree": "../.teamwork-worktrees/20260112-101500-a1b2/R1-impl",
190
+ "summary": "Implemented core validation logic",
191
+ "feedback": "Verifier found edge case in empty inputs",
192
+ "feedbackLog": [
193
+ {
194
+ "round": 1,
195
+ "at": "2026-01-12T10:15:00Z",
196
+ "text": "Verifier found edge case in empty inputs",
197
+ "resolved": false
198
+ }
199
+ ],
200
+ "verification": {
201
+ "status": "PASS|FAIL",
202
+ "passedChecks": 4,
203
+ "totalChecks": 4,
204
+ "fatalFindings": []
205
+ },
206
+ "lastReport": "verify/report-R1-impl.json",
207
+ "updatedAt": "2026-01-12T10:15:00Z"
208
+ }
209
+ },
210
+ "updatedAt": "2026-01-12T10:15:00Z"
211
+ }
212
+ ```
213
+
214
+ Task lifecycle:
215
+ - `pending`: Unstarted, waiting for dependencies to reach `verified_pass`.
216
+ - `worker_active`: Worker subagent is dispatched and coding in its isolated worktree.
217
+ - `worker_done`: Worker has committed changes to its branch; ready for verification.
218
+ - `verifier_active`: Verifier subagent is running tests/rubrics against the branch diff.
219
+ - `verified_pass`: Verification passed; ready for `teamwork_worktree` merge to sentinel base.
220
+ - `verified_fail`: Verification failed; if `round < maxRounds`, ready to re-dispatch worker with feedback; if `round >= maxRounds`, automatically transitions to `blocked`.
221
+ - `blocked`: Max rounds exceeded or upstream dependency blocked.
222
+
223
+ Resume: re-read `state.json`, skip tasks already `verified_pass`, continue the current
224
+ `round` for `verified_fail`/`worker_active`/`worker_done`.
225
+
226
+ **Cumulative feedback ledger (`feedbackLog`).** `feedback` holds only the latest
227
+ round, so it is lossy across repeated review rounds. Each task may therefore also
228
+ carry `feedbackLog`, an ordered array of per-round entries:
229
+
230
+ | Field | Type | Meaning |
231
+ | --- | --- | --- |
232
+ | `round` | integer | The task round the feedback was recorded in. |
233
+ | `at` | string | ISO 8601 time the entry was written. |
234
+ | `text` | string | The feedback, sanitised with `clean()` and capped at 500 chars. |
235
+ | `resolved` | boolean | `true` once the verifier accepted the work. |
236
+
237
+ Every `teamwork_task_update` call carrying a non-empty `feedback` appends one
238
+ entry with `resolved: false`; existing entries are preserved, never overwritten.
239
+ The array is capped at **20 entries**: when a 21st would be added, the oldest is
240
+ dropped, so state stays bounded. A task that has never failed has no
241
+ `feedbackLog` field at all.
242
+
243
+ `verified_pass` marks **every** existing entry `resolved: true` in the same write
244
+ that records the transition, so no second tool call is needed. `verified_fail`
245
+ leaves existing entries unresolved; the verifier's new feedback is appended as
246
+ another unresolved entry. `feedback` continues to hold the latest round only and
247
+ is unchanged by this ledger.
248
+
249
+ `teamwork_next` surfaces the unresolved set to the next worker: for each
250
+ `readyForWorker` entry, `feedback` is the newline-joined list of
251
+ `R<n>: <text>` for every entry with `resolved: false`, oldest first, capped at
252
+ 2000 characters (truncated with `…`). Runs written before the ledger existed — or
253
+ a task with an absent/empty `feedbackLog` — fall back to the single `feedback`
254
+ field, exactly as before.
255
+
256
+ ### Engine Tools
257
+
258
+ The plugin provides deterministic orchestration tools for the Sentinel coordinator:
259
+ - `teamwork_plan`: Creates the run directory and writes `plan.dag.json`, `state.json` and `costs.json`. It is gated on a spec by default (`requireSpec`, see below). `skipInterview` is the explicit, recorded bypass.
260
+ - `teamwork_next`: Evaluates the DAG dependencies against current task lifecycle statuses. Categorizes tasks into `readyForWorker`, `readyForVerifier`, `inProgress`, or terminal conditions (`ALL_TASKS_PASSED` / `DEADLOCK`). Completion additionally requires a stamped `verify/final.json` from `teamwork_final_verify`, unless the caller passes the recorded `allowUnstamped: true` legacy bypass.
261
+ - `teamwork_task_update`: Enforces deterministic state transitions, tracks worker branch names and diff summaries, updates verifier metrics, and advances run `phase` to `MERGE` or `PRESENT_PARTIAL`.
262
+ - `teamwork_final_verify`: Computes the run's final verdict from the artifacts on disk — every task must be `verified_pass`, every `verify/report-<taskId>.json` must be `PASS`, and `verify/security-audit.json` must be `PASS` — then writes `verify/final.json` atomically and appends a `final_verification` event. The verdict is computed from evidence; no input can turn a failing run into `PASS` (a caller-supplied `failReason` can only force `FAIL`). See [`verify/final.json`](#verifyfinaljson-final-verification-verdict).
263
+ - `teamwork_worktree`: Isolates git worktrees outside the project repo (`setup` for sentinel and worker), inspects branch diffs (`diff`), performs clean merges into `teamwork/base-$SESSION_ID` with automatic conflict abort (`merge`), and prunes worktrees (`cleanup`).
264
+ - `teamwork_preflight`: Re-checks the inputs named by an existing run's `ORIGINAL_REQUEST.md` (plus optional `inputs`), writes `<run>/preflight.json`, and appends a `preflight` event. It never throws and never blocks; it reports.
265
+
266
+ **Spec gate (`teamwork_plan`).** A run must start from an approved spec: `<run>/prompt_draft.md`, present and non-empty after trimming. The check runs after topology/task-id validation and **before anything is written**, so a refusal creates no run directory and no plan files. Two inputs control it:
267
+
268
+ | Input | Type | Default | Meaning |
269
+ | --- | --- | --- | --- |
270
+ | `requireSpec` | boolean | `true` | When true, a usable `prompt_draft.md` must exist or the plan is refused. `false` records `specGate: "not_required"`. |
271
+ | `skipInterview` | boolean | `false` | Explicit bypass: plan without an approved prompt. Recorded as `specGate: "bypassed"`, and the tool result says so. |
272
+
273
+ With no spec and neither override, the call is refused with an actionable message naming the expected path, `/teamwork-craft`, and `skipInterview: true`. A whitespace-only `prompt_draft.md` counts as no spec.
274
+
275
+ **Request record & integrity mode (`teamwork_plan`).** Two additive, optional inputs:
276
+
277
+ | Input | Type | Default | Meaning |
278
+ | --- | --- | --- | --- |
279
+ | `request` | string | omitted | The verbatim text the run was routed on (≤20,000 chars). Recorded once in `ORIGINAL_REQUEST.md` before any plan file; omitting it creates no artifact. |
280
+ | `integrityMode` | `development \| demo \| benchmark` | `development` | Recorded in `ORIGINAL_REQUEST.md`, `state.json` and `plan.dag.json`. Any other value refuses the plan before anything is written. |
281
+
282
+ The request record is a separate artifact from the approved spec: it does not
283
+ satisfy the spec gate, and the spec gate does not replace it. `teamwork_security_audit`
284
+ and the final-verification gate read the mode back from `ORIGINAL_REQUEST.md`.
285
+
286
+ **Input preflight (`teamwork_plan`).** Before anything is written, the plan
287
+ inventories the inputs the request names and checks them. The inventory comes
288
+ from the explicit `inputs` array (highest trust) plus the routed `request`
289
+ (when provided): URLs, and path tokens. It is deduplicated, keeps first-seen
290
+ order, and is capped at 100 items.
291
+
292
+ The block list is deliberately **narrow**:
293
+
294
+ | Item | Blocking? | Check |
295
+ | --- | --- | --- |
296
+ | Explicit `inputs` entry | yes (even a relative path) | path or URL as classified |
297
+ | URL (`/https?:\/\/[^\s)>\]}"']+/g`) | yes | `UNCHECKED` unless `checkUrls` |
298
+ | Token starting `/`, `~/` or `file://` | yes | local path |
299
+ | Other path-like token (contains `/`, no whitespace, not a URL) | **no — advisory** | local path, reported only |
300
+
301
+ Path checks report `READY` (with `file`/`dir`) when the path exists and
302
+ `MISSING` otherwise. URL checks record `UNCHECKED` when `checkUrls` is false
303
+ (the default); with `checkUrls: true` each URL gets one `HEAD` request with a
304
+ 3 s timeout and is `READY` on 2xx/3xx or `OUTAGE` on any other status, error or
305
+ timeout. The overall status is `OUTAGE` if any check is an outage, else
306
+ `MISSING` if any **blocking** item is missing, else `READY`. Advisory misses
307
+ never change the overall status.
308
+
309
+ Three additive, optional plan inputs control the gate:
310
+
311
+ | Input | Type | Default | Meaning |
312
+ | --- | --- | --- | --- |
313
+ | `inputs` | string[] | omitted | Extra blocking files/URLs to check (relative entries block too). |
314
+ | `checkUrls` | boolean | `false` | When false URLs are `UNCHECKED`; when true they are HEAD-checked. |
315
+ | `allowMissingInputs` | boolean | `false` | Explicit bypass when the status is `MISSING`/`OUTAGE`. Recorded as `preflight: { status, bypassed: true }` in `plan.dag.json` and as a `run_created` `note`. |
316
+
317
+ When the overall status is `MISSING` or `OUTAGE` and `allowMissingInputs` is
318
+ not `true`, the plan is **refused** with each blocking item and its status, and
319
+ nothing is written (no run dir, no `ORIGINAL_REQUEST.md`, no plan files). When
320
+ `request` and `inputs` are both absent the gate is skipped and `plan.dag.json`
321
+ records `preflight: { status: "SKIPPED" }`; otherwise it records
322
+ `{ status, bypassed }`.
323
+
324
+ ### `preflight.json` — input-checks report
325
+
326
+ Written by `teamwork_preflight` for an existing run (`teamwork_plan` records
327
+ the summary inline in `plan.dag.json` instead). The inventory is re-read from
328
+ this run's `ORIGINAL_REQUEST.md` plus the tool's optional `inputs`.
329
+
330
+ ```json
331
+ {
332
+ "checkedAt": "2026-01-12T10:20:00.000Z",
333
+ "integrityMode": "development",
334
+ "items": [
335
+ { "value": "/abs/path/spec.md", "kind": "path", "blocking": true, "advisory": false, "status": "READY", "detail": "file" },
336
+ { "value": "docs/draft.md", "kind": "path", "blocking": false, "advisory": true, "status": "MISSING" },
337
+ { "value": "https://example.com/issue/1", "kind": "url", "blocking": true, "advisory": false, "status": "UNCHECKED", "detail": "checkUrls: false" }
338
+ ],
339
+ "summary": {
340
+ "status": "READY",
341
+ "total": 3,
342
+ "blocking": 2,
343
+ "missing": 1,
344
+ "blockingMissing": 0,
345
+ "advisoryMissing": 1,
346
+ "outage": 0,
347
+ "unchecked": 1
348
+ }
349
+ }
350
+ ```
351
+
352
+ `summary.status` uses the same rule as the plan gate: `OUTAGE` beats `MISSING`
353
+ beats `READY`, and advisory misses never change it. The tool also appends a
354
+ `preflight` event (`to` is the status) with a `note` when any item is missing or
355
+ unreachable. It reports; it does not block a run.
356
+
357
+ ### `costs.json`
358
+
359
+ ```json
360
+ {
361
+ "sessionId": "...",
362
+ "budgetUsd": 20,
363
+ "budgetSource": "credits|default|manual",
364
+ "spentUsd": 0,
365
+ "byTask": {},
366
+ "byTaskTokens": {},
367
+ "updatedAt": "ISO8601"
368
+ }
369
+ ```
370
+
371
+ `byTask` maps a bucket name to its cumulative spend in USD. `byTaskTokens` is an
372
+ additive key (added after the original schema) keyed by bucket name. Both are
373
+ updated in the same locked section, but their key sets are **not** guaranteed to
374
+ be identical: every `byTaskTokens` key is also a `byTask` key, while a `byTask`
375
+ bucket can have spend and no `byTaskTokens` entry (see the all-zero case below):
376
+
377
+ ```json
378
+ {
379
+ "byTask": { "R1-impl": 0.1234 },
380
+ "byTaskTokens": { "R1-impl": { "input": 1200, "output": 640, "reasoning": 0, "cache": { "read": 300, "write": 40 } } }
381
+ }
382
+ ```
383
+
384
+ Each `byTaskTokens` bucket holds integer token deltas (current session totals
385
+ minus the `lastTokens` recorded in `snapshots.json`), the same way cost deltas
386
+ are computed. A `costs.json` without `byTaskTokens` is valid: readers treat it as
387
+ absent. The manual `addUsd` path has no token data, so it adds dollars to `byTask`
388
+ only and leaves `byTaskTokens` untouched. The session-global `tokens` total is
389
+ unchanged.
390
+
391
+ A token delta whose five components are all zero (for example, a session whose
392
+ cost rose but whose tokens did not change) is skipped **before** either map is
393
+ touched. In that case the bucket still gains its spend in `byTask` but gets no
394
+ `byTaskTokens` key. Readers must treat a missing `byTaskTokens[<bucket>]` as "no
395
+ token data", not as zero.
396
+
397
+ **Bucket names are safe map keys.** A `taskId` must match
398
+ `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`. Both `teamwork_plan` (task ids and
399
+ `dependsOn`) and `teamwork_cost` (`taskId`) refuse anything else, so ids such as
400
+ `__proto__` or `a/b` are never stored. `byTask`, `byTaskTokens` and `state.tasks`
401
+ are null-prototype maps in memory, so an id such as `constructor` is an ordinary
402
+ key. The allowlist is the guard; `clean()` alone does not prevent these ids.
403
+
404
+ **Bucketing rule.** Each session in the run's tree is assigned a bucket when
405
+ `teamwork_cost` finds spend for it:
406
+
407
+ 1. The calling session, when `taskId` is supplied → `taskId`.
408
+ 2. A root session (the run's sentinel) → `taskId` if supplied, else `_sentinel`.
409
+ 3. Any other (non-root, e.g. worker or verifier) session → `taskId` if supplied,
410
+ else its agent name (the legacy behaviour), else `_unattributed`.
411
+
412
+ So when the sentinel calls `teamwork_cost({ taskId })` at a task boundary, the
413
+ spend of the worker and verifier sessions lands on **that task**. Without a
414
+ `taskId`, subagent spend is still bucketed by agent name, exactly as before.
415
+
416
+ **Per-task attribution requires the sentinel to call it.** Per-task cost and
417
+ tokens only populate for runs whose sentinel called `teamwork_cost({ taskId })`
418
+ after each worker return and each verifier report. Spend recorded by calls made
419
+ without a `taskId` stays in agent-name or `_sentinel` buckets.
420
+
421
+ **Timeline `tokens`.** The timeline view (`lib/timeline.mjs`) reports each task's
422
+ `tokens` as `costs.byTaskTokens[<taskId>]`, when that bucket exists and holds
423
+ finite numbers. It is `null` otherwise, and **always `null` for any run recorded
424
+ before `byTaskTokens` existed**. Per-task token counts are not reconstructed for
425
+ older runs.
426
+
427
+ When the session uses `opencode/` (managed) models and the `opencode_console`
428
+ MCP is connected, `teamwork_budget` tells the sentinel to derive `budgetUsd`
429
+ from console credits (`opencode_console_get_usage` →
430
+ `min(limitDollars - spentDollars)`), after asking the user whether to use the
431
+ full remaining budget or a partial (half) amount. `budgetSource` records where
432
+ the budget came from.
433
+
434
+ Cost and token consumption are read directly from OpenCode, not self-reported.
435
+ The engine discovers the full OpenCode session tree rooted at the run's sentinel
436
+ session (`opencode.db` SQLite tree query, background service API, or client get),
437
+ aggregating the root session and all child/subagent sessions (workers, verifiers,
438
+ scouts, auditors). Deltas between calls are tracked in `snapshots.json`. When
439
+ native discovery is unavailable (tests, non-OpenCode host) the tool falls back
440
+ to manual `addUsd`.
441
+
442
+ ### `snapshots.json` — per-session cost baseline for delta tracking
443
+
444
+ ```json
445
+ {
446
+ "sessionId": "20260112-101500-a1b2",
447
+ "rootSessionIds": ["ses_abc123"],
448
+ "bySession": {
449
+ "ses_abc123": {
450
+ "lastCost": 0.62,
451
+ "lastTokens": { "input": 1200, "output": 640, "reasoning": 0, "cache": { "read": 300, "write": 40 } },
452
+ "agent": "team/sentinel",
453
+ "timestamp": "ISO8601"
454
+ }
455
+ }
456
+ }
457
+ ```
458
+
459
+ `lastCost` is the last cumulative cost observed for that OpenCode session.
460
+ Each `teamwork_cost` call queries the entire session tree, computes
461
+ `delta = current_cost - lastCost` for every session (sentinel + all subagents),
462
+ adds new spend to `costs.json`, and advances `lastCost`. Because the running total
463
+ is the sum of these deltas across the entire tree, cumulative cost is never
464
+ double-counted and subagent consumption is never lost or ignored.
465
+
466
+ ### `events.jsonl` — lifecycle event log (JSON Lines)
467
+
468
+ Append-only log of run lifecycle events. Each event is one JSON object on its own
469
+ line, terminated by `\n`. Lines are only ever appended; nothing rewrites earlier
470
+ lines.
471
+
472
+ Every new line has these 12 fields, always present (`null` where not applicable),
473
+ plus `agentSource` when an actor exists:
474
+
475
+ - `ts` (string): ISO 8601 time the event was written
476
+ - `seq` (integer): position in this file's event sequence, starting at `1` and
477
+ increasing by one with every append. The value is assigned inside the same
478
+ `withFileLock` as the append, so concurrent appends cannot duplicate it.
479
+ **Optional on legacy lines**: logs written before `seq` existed have no
480
+ `seq`, and they remain valid.
481
+ - `event` (string): `run_created`, `task_transition`, `security_audit`,
482
+ `final_verification`, `final_verification_bypass`, or `preflight`
483
+ - `sessionId` (string): Run session id (≤64 chars)
484
+ - `taskId` (string or null): Task id (≤64 chars); `null` for run-level events
485
+ - `from` (string or null): Previous task status (≤32 chars)
486
+ - `to` (string): New task status, or `PASS`/`FAIL` for `security_audit` and `final_verification` (≤32 chars)
487
+ - `round` (integer): Task round; `0` when not applicable
488
+ - `agent` (string or null): Actor that performed the transition (≤64 chars). **Caller-reported (self-reported)**, see the **Actor** paragraph below.
489
+ - `agentSource` (string, optional): Provenance of `agent` — `"explicit"` (the
490
+ `agent` input on `teamwork_task_update`), `"session"` (the calling session's
491
+ agent, from the session tree or `snapshots.json`), or `"plan"` (the agent
492
+ declared for the task in `plan.dag.json`). Emitted **only** when `agent` is
493
+ non-null; `run_created` and `security_audit` carry no actor, so they omit it.
494
+ `final_verification` records the calling session's agent (`"session"`) when it
495
+ can be resolved. Legacy lines also omit it.
496
+ - `branch` (string or null): Task branch (≤120 chars)
497
+ - `worktree` (string or null): Task worktree path (≤200 chars)
498
+ - `phase` (string or null): Run phase after the event (≤32 chars)
499
+ - `note` (string, optional): Why a bypass was taken or what input preflight
500
+ found (≤200 chars). Emitted on `final_verification_bypass`, on
501
+ `teamwork_preflight`'s `preflight` event, and on `run_created` when the
502
+ input-preflight gate was bypassed. Every other event omits it. Sanitised with
503
+ `clean()`.
504
+
505
+ The six event kinds:
506
+
507
+ - `run_created`: written by `teamwork_plan` once the run is created. `taskId` and
508
+ `from` are `null`, `to` is `"pending"`, `round` is `0`, `phase` is `"DAG_BUILD"`.
509
+ It additionally carries the spec-gate decision: `specGate`
510
+ (`"satisfied" | "bypassed" | "not_required"`) and, only when satisfied,
511
+ `specPath` (the `prompt_draft.md` path, ≤200 chars). These two fields appear
512
+ **only** on `run_created`; every other event keeps the fields above.
513
+ `specGate` and `specPath` also go through `clean()`. The timeline view parses
514
+ events field by field and does not surface `specGate` (it is visible in
515
+ `events.jsonl` itself). When the input-preflight gate was bypassed with
516
+ `allowMissingInputs: true`, `run_created` also carries `note` (e.g.
517
+ `preflight bypassed: MISSING (2 items)`).
518
+ - `task_transition`: written by `teamwork_task_update` after `state.json` is saved.
519
+ `from` is the previous status and `to` the status that landed. `round`, `branch`,
520
+ `worktree` and `phase` are the values after the transition. `agentSource`
521
+ appears when an actor was resolved.
522
+ - `security_audit`: written by `teamwork_security_audit`. `to` is `"PASS"` or
523
+ `"FAIL"`, and `phase` is the run phase. `taskId`, `from`, `branch`, `worktree` and
524
+ `agent` are `null`, `round` is `0`, and `agentSource` is omitted.
525
+ - `preflight`: written by `teamwork_preflight` after `preflight.json` is
526
+ saved. `to` is the overall preflight status (`READY`, `MISSING`, or
527
+ `OUTAGE`); `taskId` and `from` are `null`, `round` is `0`, and `phase` is the
528
+ run phase. `note` is present when any item is missing or unreachable.
529
+ - `final_verification`: written by `teamwork_final_verify` after
530
+ `verify/final.json` is saved. `to` is `"PASS"` or `"FAIL"`, `taskId` and `from`
531
+ are `null`, `round` is `0`, and `phase` is the run phase. `agent` is the calling
532
+ session's agent when it could be resolved (with `agentSource: "session"`);
533
+ otherwise it is `null` and `agentSource` is omitted.
534
+ - `final_verification_bypass`: written by `teamwork_next` when it accepts an
535
+ **unstamped** `verify/final.json` through the explicit `allowUnstamped: true`
536
+ bypass. `to` is `"ALL_PASSED"`, `taskId` and `from` are `null`, `round` is
537
+ `0`, and `phase` is the run phase after the bypass (normally `"MERGE"`).
538
+ `agent` is the calling session's agent when it could be resolved (with
539
+ `agentSource: "session"`), otherwise `null`. It carries a `note` explaining
540
+ that the verdict was not produced by `teamwork_final_verify`. A stamped
541
+ verdict never emits this event.
542
+
543
+ Example (one `task_transition` line, wrapped here for readability):
544
+
545
+ ```json
546
+ {"ts":"2026-01-12T10:15:00.000Z","seq":12,"event":"task_transition","sessionId":"20260112-101500-a1b2",
547
+ "taskId":"R1-impl","from":"worker_active","to":"worker_done","round":1,
548
+ "agent":"team/worker","agentSource":"explicit","branch":"teamwork/20260112-101500-a1b2-R1-impl",
549
+ "worktree":"../.teamwork-worktrees/20260112-101500-a1b2/R1-impl","phase":"DISPATCH"}
550
+ ```
551
+
552
+ **Actor (`agent`) — caller-reported, not verified.** On `task_transition` the field
553
+ records the actor, resolved in this order: (1) the explicit `agent` input to
554
+ `teamwork_task_update`, (2) the calling session's agent, read from the session
555
+ tree, (3) the agent declared for the task in `plan.dag.json`. `agentSource`
556
+ records which of those three produced the value (`explicit`, `session`, `plan`).
557
+ The sentinel passes `agent: "team/worker"` on `worker_done` and
558
+ `agent: "team/verifier"` on `verified_pass` / `verified_fail`. The value is
559
+ self-reported: the engine does not check that the named agent actually performed
560
+ the transition. No engine decision reads it; the timeline view only displays it.
561
+ Treat it as a label, not as evidence of who acted.
562
+
563
+ **Sanitising.** The caller-supplied and file-derived string fields (`sessionId`,
564
+ `taskId`, `from`, `to`, `agent`, `branch`, `worktree`, `phase`, `note`) are
565
+ passed through `clean()` and truncated to the limit above. `ts` is generated by the engine
566
+ (`new Date().toISOString()`), `seq` is assigned by the engine, `event` is a
567
+ code-supplied literal, and `agentSource` is only emitted for one of the three
568
+ fixed values above, so none of those goes through `clean()`. `clean()` replaces
569
+ C0 control characters, DEL, C1 controls (U+0080–U+009F, including U+0085), and
570
+ U+2028/U+2029 with spaces. A value can therefore never add a second physical
571
+ line. It is a line-safety and display sanitiser, not a complete defence against
572
+ hostile text, and it does not guard against prototype-key collisions (see Bucket
573
+ names above).
574
+
575
+ **Locking and symlinks.** Each append runs inside a per-file, in-process lock
576
+ (`withFileLock` keyed on the `events.jsonl` path). A symlinked
577
+ `events.jsonl` is refused: nothing is written through the link, and the link is left
578
+ in place.
579
+
580
+ **Best-effort, fail-open.** Writing is best-effort. Any error (including a refused
581
+ symlink) is swallowed, and no tool result changes because of it. The DAG engine
582
+ (`teamwork_next`, `teamwork_task_update`) never reads `events.jsonl`, so a run works
583
+ fully without it. Only the timeline view reads it. Without it the timeline falls back
584
+ to derived mode, with start and duration unknown.
585
+
586
+ ### `verify/report-<task>.json` (verifier output)
587
+
588
+ ```json
589
+ {
590
+ "taskId": "R1-impl",
591
+ "verifierAgent": "team/verifier",
592
+ "verifierModel": "<model>",
593
+ "timestamp": "ISO8601",
594
+ "status": "PASS",
595
+ "checks": [
596
+ { "name": "...", "type": "programmatic|adversarial|rubric", "passed": true, "output": "..." }
597
+ ],
598
+ "feedbackForWorker": "...",
599
+ "fatalFindings": [
600
+ { "where": "file:line", "why": "...", "fix": "...", "reproduction": "..." }
601
+ ]
602
+ }
603
+ ```
604
+
605
+ ### `verify/security-audit.json` (pre-merge security gate output)
606
+
607
+ ```json
608
+ {
609
+ "sessionId": "20260112-101500-a1b2",
610
+ "integrityMode": "development",
611
+ "status": "PASS|FAIL",
612
+ "timestamp": "ISO8601",
613
+ "severityCounts": { "critical": 0, "high": 0, "medium": 1, "low": 2 },
614
+ "summary": "Audited base branch diff; no secrets or injection vectors found.",
615
+ "findings": [
616
+ {
617
+ "id": "SEC-1",
618
+ "severity": "Medium",
619
+ "location": "src/api.ts:42",
620
+ "description": "Unbounded payload buffer could allow memory pressure under high concurrency."
621
+ }
622
+ ],
623
+ "integrityFindings": [
624
+ { "rule": "external_dependency_used", "where": "src/parser.ts:3", "why": "uses a third-party parser" }
625
+ ],
626
+ "integrityViolations": [
627
+ {
628
+ "rule": "external_dependency_used",
629
+ "where": "src/parser.ts:3",
630
+ "why": "uses a third-party parser",
631
+ "forbiddenFrom": "benchmark"
632
+ }
633
+ ]
634
+ }
635
+ ```
636
+
637
+ `integrityMode` is read at audit time from `ORIGINAL_REQUEST.md` and recorded
638
+ here; legacy runs with no request artifact record `development` and the tool
639
+ result says the default was applied. The mode itself is disclosed, not enforced,
640
+ by `teamwork_next`'s final-verification gate (whose responses carry the same
641
+ `integrityMode` field); enforcement happens in the audit tool when it records
642
+ `integrityViolations`.
643
+
644
+ `integrityFindings` records the auditor's sanitised claims (rule, optional
645
+ `where`/`why`, capped at 50). `integrityViolations` is the subset whose rule is
646
+ forbidden at the recorded mode; each entry also carries the rule's
647
+ `forbiddenFrom` threshold (see [Integrity rules](#integrity-rules)). Any
648
+ violation forces `status` to `FAIL`, independently of severity counts.
649
+
650
+ If `critical` > 0 or `high` > 0, `status` is forced to `FAIL` and `teamwork_next` blocks final merge (`BLOCKED_BY_SECURITY`).
651
+
652
+ ### `verify/final.json` (final verification verdict)
653
+
654
+ ```json
655
+ {
656
+ "status": "PASS|FAIL",
657
+ "generatedBy": { "agent": "team/verifier", "session": "ses_abc123" },
658
+ "generatedAt": "ISO8601",
659
+ "integrityMode": "development",
660
+ "evidence": {
661
+ "tasks": [
662
+ {
663
+ "id": "R1-impl",
664
+ "status": "verified_pass",
665
+ "report": "verify/report-R1-impl.json",
666
+ "reportStatus": "PASS"
667
+ }
668
+ ],
669
+ "securityAudit": { "path": "verify/security-audit.json", "status": "PASS" },
670
+ "allTasksVerifiedPass": true
671
+ },
672
+ "reasons": [],
673
+ "summary": "Independent final check passed.",
674
+ "findings": [
675
+ { "where": "src/api.ts:42", "why": "...", "fix": "..." }
676
+ ]
677
+ }
678
+ ```
679
+
680
+ `teamwork_final_verify` writes this file atomically. `status` is `PASS` **only**
681
+ when every task in `state.json` is `verified_pass`, every task report
682
+ (`verify/report-<taskId>.json`, task ids validated with the same safe-id
683
+ allowlist) reports `PASS`, and `verify/security-audit.json` reports `PASS`. Any
684
+ unmet condition yields `FAIL` with one entry per condition in `reasons` (capped
685
+ at 100). The verdict is computed from these artifacts and cannot be overridden
686
+ by input: a supplied `failReason` only appends a reason and forces `FAIL`.
687
+
688
+ `generatedBy` records provenance: `agent` is the calling session's agent (or
689
+ `null` when it could not be resolved) and `session` is the calling OpenCode
690
+ session id (or the run id when no caller session is available). `generatedAt` is
691
+ the write time. `integrityMode` is read from `ORIGINAL_REQUEST.md` and defaults
692
+ to `development`. `summary` and `findings` are optional (the verifier's prose and
693
+ up to 50 `{where, why, fix}` entries).
694
+
695
+ **Stamped requirement.** `teamwork_next` treats a report as *stamped* only when
696
+ it has a non-empty `generatedBy` object containing a non-empty `session`, a
697
+ parseable `generatedAt`, and an `evidence` object. A report missing any of those
698
+ was written outside the engine (by hand, or before the stamp existed): it is
699
+ unstamped/legacy and cannot complete a run by default. Recompute it with
700
+ `teamwork_final_verify`.
701
+
702
+ **Completion gate.** With every task `verified_pass` and the security audit
703
+ `PASS`, `teamwork_next` evaluates `verify/final.json`:
704
+
705
+ | Report state | Result | Phase |
706
+ | --- | --- | --- |
707
+ | missing/unreadable/malformed | `READY_FOR_FINAL_VERIFICATION` | `FINAL_VERIFICATION` |
708
+ | `status: "FAIL"` | `BLOCKED_BY_FINAL_VERIFICATION` | unchanged |
709
+ | `status: "PASS"`, stamped | `ALL_PASSED` with `stamped: true` | `MERGE` |
710
+ | `status: "PASS"`, unstamped, default | `FINAL_VERIFICATION_UNVERIFIED` | `FINAL_VERIFICATION` |
711
+ | `status: "PASS"`, unstamped, `allowUnstamped: true` | `ALL_PASSED` with `stamped: false`, `unstampedBypass: true` | `MERGE` |
712
+
713
+ `allowUnstamped` (boolean, default `false`) is a legacy migration escape hatch.
714
+ It accepts a hand-written report and appends one `final_verification_bypass`
715
+ event whose `note` records the acceptance. Use it only to finish runs that
716
+ predate `teamwork_final_verify`; every new run should complete through a stamped
717
+ verdict. `FINAL_VERIFICATION_UNVERIFIED` results carry `finalReport`,
718
+ `passedCount` and `integrityMode`, and the message names both remedies (run the
719
+ tool, or re-call with the bypass).
720
+
721
+ ### `synthesis/conflict-<task>.json` (git 3-way merge conflict artifact)
722
+
723
+ Generated by `teamwork_worktree({ action: "merge" })` when a conflict occurs:
724
+
725
+ ```json
726
+ {
727
+ "taskId": "R2-impl",
728
+ "sessionId": "20260112-101500-a1b2",
729
+ "baseBranch": "teamwork/base-20260112-101500-a1b2",
730
+ "incomingBranch": "teamwork/20260112-101500-a1b2-R2-impl",
731
+ "conflictingFiles": ["src/router.ts"],
732
+ "diffOurs": "...",
733
+ "diffTheirs": "...",
734
+ "timestamp": "ISO8601"
735
+ }
736
+ ```
737
+
738
+ ### `pitfalls.md`
739
+
740
+ One line per entry:
741
+
742
+ ```
743
+ - [round 2] assumes the input is already sorted — seen in R1-impl
744
+ ```
745
+
746
+ ### `scout-report.md`, `candidates/*.md`, `critiques/*.md`, `synthesis/*.md`
747
+
748
+ Free-form markdown following the section structure described in the scout,
749
+ proposer, falsifier and synthesizer agent files.
750
+
751
+ ## Export report (`report.html` / `report.md`)
752
+
753
+ `opencode-teamwork export` writes a human-readable report of one run. It is a
754
+ reporting output only: it is read by no engine tool, no agent, and no gate, and
755
+ deleting it changes nothing about the run.
756
+
757
+ **Where it is written.** Without `-o`, the file goes to the run directory:
758
+
759
+ - HTML (default): `.opencode/teamwork/<session-id>/report.html`
760
+ - Markdown (`-m` / `--markdown`): `.opencode/teamwork/<session-id>/report.md`
761
+
762
+ The CLI prints the **absolute** path of the file it wrote. With `-o <file>` the
763
+ report goes to that path instead. With `-o -` it is streamed to stdout and no file
764
+ is written. The export reads the run directory and never modifies it.
765
+
766
+ **Format: HTML.** A standalone single-file document. CSS is embedded in a `<style>`
767
+ block, and the file has no external CDN, fonts, scripts, or images. It works fully
768
+ offline and is safe to attach to an issue or archive. Dynamic text is HTML-escaped,
769
+ and absolute `http(s)://` URLs in quoted text are defanged, so the file contains no
770
+ live links.
771
+
772
+ **Format: Markdown.** GitHub-flavored Markdown with tables and a checklist. It is
773
+ suitable for pasting into a PR description or an issue comment.
774
+
775
+ **Contents** (both formats, in this order):
776
+
777
+ | Section | Source |
778
+ | --- | --- |
779
+ | Summary | `plan.dag.json`, `state.json`, `costs.json`, `events.jsonl`: session id, topology, overall status, phase, duration, budget, spend, tokens, task totals |
780
+ | Tasks | one row per task: status, worker, verifier, rounds, duration, cost, checks. Details: summary, feedback, fatal findings, branch, worktree |
781
+ | Acceptance checklist | (Markdown) one box per task, ticked when `verified_pass`, plus the security gate |
782
+ | Security audit | `verify/security-audit.json`: pre-merge status, severity counts, findings |
783
+ | Final verification | `verify/final.json`, when present |
784
+ | Pitfalls | `pitfalls.md` entries |
785
+ | Other cost buckets | cost buckets that are not task ids (HTML only, when present) |
786
+ | Warnings | files that were oversize, unreadable, or malformed and were skipped |
787
+
788
+ The overall status is decided from three inputs: the tasks, the security audit, and
789
+ `verify/final.json`. It is checked in this order:
790
+
791
+ 1. `FAIL` when any task is `verified_fail` or `blocked`, when the security audit
792
+ reports `FAIL` or has any `critical` or `high` finding, or when
793
+ `verify/final.json` reports `FAIL`.
794
+ 2. `PASS` when `verify/final.json` reports `PASS` (even if some tasks are not yet
795
+ `verified_pass`).
796
+ 3. `PASS` when there is at least one task, every task is `verified_pass`, and the
797
+ audit did not fail.
798
+ 4. Otherwise `INCOMPLETE`.
799
+
800
+ Missing `events.jsonl` data is shown
801
+ as "timing unknown" rather than guessed.
802
+
803
+ **Errors.** A missing or invalid run (no run directory, or no valid
804
+ `plan.dag.json` / `state.json`) makes `export` exit with code `1`, as does a
805
+ file-write error.
806
+