@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,2912 @@
1
+ // opencode-teamwork — Teamwork engine tools + hooks (V2 plugin API)
2
+ //
3
+ // Turns the mechanics that the prompts used to describe in prose (run dir,
4
+ // plan, state, cost, pitfalls, resume) into real tools, and uses hooks to
5
+ // enforce the read-only guarantee and to inject run context automatically.
6
+ //
7
+ // Security notes:
8
+ // * Every run path is built from a VALIDATED session id and asserted to stay
9
+ // inside the run root (no path traversal / arbitrary file write).
10
+ // * Untrusted run state is sanitised before it is injected into any system
11
+ // prompt (no stored prompt injection).
12
+ // * The read-only policy is an explicit per-agent deny list (fail-closed):
13
+ // an unknown agent is not silently allowed to escalate via subagent/webfetch.
14
+ //
15
+ // No OpenCode imports: tool definitions are plain objects, so the loader never
16
+ // has to resolve node_modules for this package.
17
+
18
+ import {
19
+ existsSync,
20
+ lstatSync,
21
+ mkdirSync,
22
+ readdirSync,
23
+ readFileSync,
24
+ realpathSync,
25
+ writeFileSync,
26
+ appendFileSync,
27
+ renameSync,
28
+ rmSync,
29
+ openSync,
30
+ readSync,
31
+ fstatSync,
32
+ closeSync,
33
+ } from "node:fs"
34
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
35
+ import { homedir } from "node:os"
36
+ import { execFileSync } from "node:child_process"
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // OpenCode native cost tracking
40
+ //
41
+ // Total consumption is computed exactly from OpenCode across the entire
42
+ // session tree: the root Sentinel session + all spawned child/subagent
43
+ // sessions (workers, verifiers, scouts, challengers, etc.).
44
+ //
45
+ // We discover OpenCode session trees via three redundant channels:
46
+ // 1. OpenCode SQLite database (`session_v2` recursive query) via `node:sqlite`
47
+ // 2. OpenCode SQLite database via `sqlite3` CLI
48
+ // 3. OpenCode background service API (`GET /api/session?parentID=...`)
49
+ // 4. Native client fallback (`ctx.session.get({ sessionID })`)
50
+ //
51
+ // We snapshot cumulative cost per session and report deltas, ensuring a run's
52
+ // spend is measured honestly — never self-reported or lost if a worker halts.
53
+ // ---------------------------------------------------------------------------
54
+
55
+ interface TokenUsage {
56
+ input: number
57
+ output: number
58
+ reasoning: number
59
+ cache: { read: number; write: number }
60
+ }
61
+
62
+ interface SessionSnapshot {
63
+ /** Last observed cumulative cost for this OpenCode session, in USD. */
64
+ lastCost: number
65
+ lastTokens: TokenUsage
66
+ agent?: string
67
+ timestamp: string
68
+ }
69
+
70
+ interface SnapshotsFile {
71
+ sessionId: string
72
+ rootSessionIds?: string[]
73
+ bySession: Record<string, SessionSnapshot>
74
+ }
75
+
76
+ interface SessionUsageItem {
77
+ id: string
78
+ parentId?: string
79
+ agent?: string
80
+ cost: number
81
+ tokens: TokenUsage
82
+ }
83
+
84
+ interface TreeUsageResult {
85
+ sessions: SessionUsageItem[]
86
+ source: string
87
+ }
88
+
89
+ function normalizeTokens(t: any): TokenUsage {
90
+ return {
91
+ input: Number(t?.input) || 0,
92
+ output: Number(t?.output) || 0,
93
+ reasoning: Number(t?.reasoning) || 0,
94
+ cache: { read: Number(t?.cache?.read) || 0, write: Number(t?.cache?.write) || 0 },
95
+ }
96
+ }
97
+
98
+ function readSnapshots(file: string): SnapshotsFile | undefined {
99
+ try {
100
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as SnapshotsFile
101
+ if (!parsed || typeof parsed !== "object" || typeof parsed.bySession !== "object") return undefined
102
+ if (!Array.isArray(parsed.rootSessionIds)) parsed.rootSessionIds = []
103
+ return parsed
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ function writeSnapshots(file: string, value: SnapshotsFile) {
110
+ refuseSymlink(file)
111
+ mkdirSync(dirname(file), { recursive: true })
112
+ const tmp = file + ".tmp"
113
+ refuseSymlink(tmp)
114
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n")
115
+ renameSync(tmp, file)
116
+ }
117
+
118
+ function getOpencodeDbPath(): string | undefined {
119
+ const candidates: string[] = []
120
+ if (process.env.XDG_DATA_HOME) {
121
+ candidates.push(join(process.env.XDG_DATA_HOME, "opencode", "opencode.db"))
122
+ }
123
+ const home = homedir()
124
+ candidates.push(join(home, ".local", "share", "opencode", "opencode.db"))
125
+ candidates.push(join(home, "Library", "Application Support", "opencode", "opencode.db"))
126
+ if (process.env.LOCALAPPDATA) {
127
+ candidates.push(join(process.env.LOCALAPPDATA, "opencode", "opencode.db"))
128
+ }
129
+ candidates.push(join(home, "AppData", "Local", "opencode", "opencode.db"))
130
+ for (const p of candidates) {
131
+ try {
132
+ if (existsSync(p)) return p
133
+ } catch {}
134
+ }
135
+ return undefined
136
+ }
137
+
138
+ function getOpencodeService(): { url: string; auth: string } | undefined {
139
+ const candidates: string[] = []
140
+ if (process.env.XDG_STATE_HOME) {
141
+ candidates.push(join(process.env.XDG_STATE_HOME, "opencode", "service.json"))
142
+ }
143
+ const home = homedir()
144
+ candidates.push(join(home, ".local", "state", "opencode", "service.json"))
145
+ candidates.push(join(home, "Library", "Application Support", "opencode", "service.json"))
146
+ if (process.env.LOCALAPPDATA) {
147
+ candidates.push(join(process.env.LOCALAPPDATA, "opencode", "service.json"))
148
+ }
149
+ for (const p of candidates) {
150
+ try {
151
+ if (existsSync(p)) {
152
+ const raw = JSON.parse(readFileSync(p, "utf8"))
153
+ if (raw?.url) {
154
+ const auth = "Basic " + Buffer.from(`opencode:${raw.password ?? ""}`).toString("base64")
155
+ return { url: raw.url, auth }
156
+ }
157
+ }
158
+ } catch {}
159
+ }
160
+ return undefined
161
+ }
162
+
163
+ async function fetchServiceTree(url: string, auth: string, rootIds: string[]): Promise<SessionUsageItem[] | undefined> {
164
+ const sessions: SessionUsageItem[] = []
165
+ const seen = new Set<string>()
166
+ const queue: string[] = [...rootIds]
167
+
168
+ for (const rootId of rootIds) {
169
+ if (seen.has(rootId)) continue
170
+ seen.add(rootId)
171
+ try {
172
+ const res = await fetch(`${url}/api/session/${encodeURIComponent(rootId)}`, {
173
+ headers: { Authorization: auth },
174
+ signal: AbortSignal.timeout(3000),
175
+ })
176
+ if (res.ok) {
177
+ const json: any = await res.json()
178
+ const s = json?.data
179
+ if (s && typeof s.cost === "number") {
180
+ sessions.push({
181
+ id: s.id,
182
+ parentId: s.parentID,
183
+ agent: s.agent,
184
+ cost: s.cost,
185
+ tokens: normalizeTokens(s.tokens),
186
+ })
187
+ }
188
+ }
189
+ } catch {}
190
+ }
191
+
192
+ while (queue.length > 0) {
193
+ const parentId = queue.shift()!
194
+ try {
195
+ const res = await fetch(`${url}/api/session?parentID=${encodeURIComponent(parentId)}`, {
196
+ headers: { Authorization: auth },
197
+ signal: AbortSignal.timeout(3000),
198
+ })
199
+ if (res.ok) {
200
+ const json: any = await res.json()
201
+ const children = Array.isArray(json?.data) ? json.data : []
202
+ for (const c of children) {
203
+ if (c?.id && !seen.has(c.id)) {
204
+ seen.add(c.id)
205
+ queue.push(c.id)
206
+ sessions.push({
207
+ id: c.id,
208
+ parentId: c.parentID,
209
+ agent: c.agent,
210
+ cost: Number(c.cost) || 0,
211
+ tokens: normalizeTokens(c.tokens),
212
+ })
213
+ }
214
+ }
215
+ }
216
+ } catch {}
217
+ }
218
+
219
+ return sessions.length ? sessions : undefined
220
+ }
221
+
222
+ /**
223
+ * Read the real cumulative cost + tokens for an OpenCode session tree (root +
224
+ * all child/subagent sessions).
225
+ */
226
+ async function readSessionTreeUsage(
227
+ ctx: any,
228
+ rootIds: string[],
229
+ fallbackSessionId?: string,
230
+ ): Promise<TreeUsageResult | undefined> {
231
+ const safeIds = Array.from(new Set([...rootIds, ...(fallbackSessionId ? [fallbackSessionId] : [])])).filter(
232
+ (id) => typeof id === "string" && /^[0-9A-Za-z_.-]+$/.test(id),
233
+ )
234
+ if (!safeIds.length) return undefined
235
+
236
+ // 1. Try local SQLite database (node:sqlite)
237
+ const dbPath = getOpencodeDbPath()
238
+ if (dbPath) {
239
+ try {
240
+ const { DatabaseSync } = await import("node:sqlite")
241
+ const db = new DatabaseSync(dbPath, { readOnly: true })
242
+ const placeholders = safeIds.map(() => "?").join(", ")
243
+ const stmt = db.prepare(`
244
+ WITH RECURSIVE tree AS (
245
+ SELECT id, parent_id, agent, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write
246
+ FROM session_v2 WHERE id IN (${placeholders})
247
+ UNION ALL
248
+ SELECT s.id, s.parent_id, s.agent, s.cost, s.tokens_input, s.tokens_output, s.tokens_reasoning, s.tokens_cache_read, s.tokens_cache_write
249
+ FROM session_v2 s JOIN tree t ON s.parent_id = t.id
250
+ )
251
+ SELECT id, parent_id, agent, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM tree;
252
+ `)
253
+ const rows = stmt.all(...safeIds)
254
+ db.close()
255
+ if (rows && rows.length > 0) {
256
+ return {
257
+ sessions: rows.map((r: any) => ({
258
+ id: String(r.id),
259
+ parentId: r.parent_id ? String(r.parent_id) : undefined,
260
+ agent: r.agent ? String(r.agent) : undefined,
261
+ cost: Number(r.cost) || 0,
262
+ tokens: {
263
+ input: Number(r.tokens_input) || 0,
264
+ output: Number(r.tokens_output) || 0,
265
+ reasoning: Number(r.tokens_reasoning) || 0,
266
+ cache: { read: Number(r.tokens_cache_read) || 0, write: Number(r.tokens_cache_write) || 0 },
267
+ },
268
+ })),
269
+ source: "opencode database (node:sqlite)",
270
+ }
271
+ }
272
+ } catch {}
273
+
274
+ // 2. Try sqlite3 CLI fallback
275
+ try {
276
+ const inClause = safeIds.map((id) => `'${id}'`).join(", ")
277
+ const sql = `
278
+ WITH RECURSIVE tree AS (
279
+ SELECT id, parent_id, agent, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write
280
+ FROM session_v2 WHERE id IN (${inClause})
281
+ UNION ALL
282
+ SELECT s.id, s.parent_id, s.agent, s.cost, s.tokens_input, s.tokens_output, s.tokens_reasoning, s.tokens_cache_read, s.tokens_cache_write
283
+ FROM session_v2 s JOIN tree t ON s.parent_id = t.id
284
+ )
285
+ SELECT id, coalesce(parent_id, ''), coalesce(agent, ''), cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM tree;
286
+ `
287
+ const raw = execFileSync("sqlite3", [dbPath, "-separator", "\t", sql], { encoding: "utf8", timeout: 5000 })
288
+ const lines = raw.trim().split("\n").filter(Boolean)
289
+ if (lines.length > 0) {
290
+ return {
291
+ sessions: lines.map((line) => {
292
+ const [id, parentId, agent, cost, inp, out, reas, cr, cw] = line.split("\t")
293
+ return {
294
+ id,
295
+ parentId: parentId || undefined,
296
+ agent: agent || undefined,
297
+ cost: Number(cost) || 0,
298
+ tokens: {
299
+ input: Number(inp) || 0,
300
+ output: Number(out) || 0,
301
+ reasoning: Number(reas) || 0,
302
+ cache: { read: Number(cr) || 0, write: Number(cw) || 0 },
303
+ },
304
+ }
305
+ }),
306
+ source: "opencode database (sqlite3 CLI)",
307
+ }
308
+ }
309
+ } catch {}
310
+ }
311
+
312
+ // 3. Try OpenCode background service API
313
+ const svc = getOpencodeService()
314
+ if (svc) {
315
+ try {
316
+ const items = await fetchServiceTree(svc.url, svc.auth, safeIds)
317
+ if (items && items.length > 0) {
318
+ return {
319
+ sessions: items,
320
+ source: "opencode service API",
321
+ }
322
+ }
323
+ } catch {}
324
+ }
325
+
326
+ // 4. Fallback to client ctx.session.get
327
+ const fallbackSessions: SessionUsageItem[] = []
328
+ for (const id of safeIds) {
329
+ const u = await readSessionUsage(ctx, id)
330
+ if (u) fallbackSessions.push({ id, cost: u.cost, tokens: u.tokens })
331
+ }
332
+ if (fallbackSessions.length > 0) {
333
+ return {
334
+ sessions: fallbackSessions,
335
+ source: `opencode session ${safeIds[0]}`,
336
+ }
337
+ }
338
+
339
+ return undefined
340
+ }
341
+
342
+ /**
343
+ * Read cumulative cost + tokens for a single session from ctx.session.get.
344
+ * Used for baselines or as a single-session fallback.
345
+ */
346
+ async function readSessionUsage(
347
+ ctx: any,
348
+ sessionID: string | undefined,
349
+ ): Promise<{ cost: number; tokens: TokenUsage } | undefined> {
350
+ if (!sessionID || typeof ctx?.session?.get !== "function") return undefined
351
+ try {
352
+ const info = await ctx.session.get({ sessionID })
353
+ if (!info || typeof info.cost !== "number") return undefined
354
+ return { cost: info.cost, tokens: normalizeTokens(info.tokens) }
355
+ } catch {
356
+ return undefined
357
+ }
358
+ }
359
+
360
+ /** Reject if `p` does not settle within `ms`; the timer is always cleared. */
361
+ function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
362
+ let timer: ReturnType<typeof setTimeout> | undefined
363
+ const guard = new Promise<never>((_, reject) => {
364
+ timer = setTimeout(() => reject(new Error("timeout")), ms)
365
+ })
366
+ return Promise.race([p, guard]).finally(() => clearTimeout(timer))
367
+ }
368
+
369
+ /**
370
+ * Best-effort actor lookup for the calling session. Fail-open: never throws and
371
+ * never blocks longer than 2s. Order: the client's session.get agent, then the
372
+ * agent recorded for that session in snapshots.json (same source as
373
+ * bySession[*].agent). Returns the actor with its provenance (`session` for both
374
+ * sources), or undefined when neither is available.
375
+ */
376
+ async function deriveCallerAgent(
377
+ ctx: any,
378
+ run: string,
379
+ sessionID: string | undefined,
380
+ ): Promise<{ agent: string; source: "session" } | undefined> {
381
+ if (!sessionID) return undefined
382
+ try {
383
+ if (typeof ctx?.session?.get === "function") {
384
+ const info: any = await withTimeout(Promise.resolve(ctx.session.get({ sessionID })), 2000)
385
+ const a = typeof info?.agent === "string" ? clean(info.agent, 64).trim() : ""
386
+ if (a) return { agent: a, source: "session" }
387
+ }
388
+ } catch {}
389
+ try {
390
+ const a = readSnapshots(join(run, "snapshots.json"))?.bySession?.[sessionID]?.agent
391
+ if (typeof a === "string") {
392
+ const c = clean(a, 64).trim()
393
+ if (c) return { agent: c, source: "session" }
394
+ }
395
+ } catch {}
396
+ return undefined
397
+ }
398
+
399
+ type TokenTotals = { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
400
+
401
+ /** Non-negative integer, 0 for anything non-finite. */
402
+ function tokenInt(v: unknown): number {
403
+ const n = Math.round(Number(v))
404
+ return Number.isFinite(n) && n > 0 ? n : 0
405
+ }
406
+
407
+ /**
408
+ * Add the token delta (cur - prev.lastTokens) of one session to
409
+ * costs.byTaskTokens[bucket]. Mirrors the cost-delta baseline: no prior snapshot
410
+ * means the full current total is the delta. A prior snapshot without
411
+ * lastTokens cannot yield an honest delta, so it is skipped. An all-zero token
412
+ * delta returns early WITHOUT touching either map, so byTaskTokens and byTask
413
+ * key sets can diverge (a bucket can have spend and no token entry).
414
+ * Both maps are null-prototype (see nullMap) so no bucket name collides.
415
+ */
416
+ function accumulateTokenDelta(costs: any, bucket: string, cur: TokenTotals | undefined, prev: any) {
417
+ if (!cur || typeof cur !== "object") return
418
+ if (prev && !prev.lastTokens) return
419
+ const base: any = prev ? prev.lastTokens : undefined
420
+ const d = {
421
+ input: tokenInt(cur.input) - tokenInt(base?.input),
422
+ output: tokenInt(cur.output) - tokenInt(base?.output),
423
+ reasoning: tokenInt(cur.reasoning) - tokenInt(base?.reasoning),
424
+ cache: {
425
+ read: tokenInt(cur.cache?.read) - tokenInt(base?.cache?.read),
426
+ write: tokenInt(cur.cache?.write) - tokenInt(base?.cache?.write),
427
+ },
428
+ }
429
+ const parts = [d.input, d.output, d.reasoning, d.cache.read, d.cache.write].map((x) => Math.max(0, x))
430
+ if (parts.every((x) => x === 0)) return
431
+ costs.byTaskTokens = nullMap(costs.byTaskTokens)
432
+ costs.byTask = nullMap(costs.byTask)
433
+ if (costs.byTask[bucket] === undefined) costs.byTask[bucket] = 0
434
+ const b = costs.byTaskTokens[bucket]
435
+ const cur2 = b && typeof b === "object" ? b : { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
436
+ costs.byTaskTokens[bucket] = {
437
+ input: tokenInt(cur2.input) + parts[0],
438
+ output: tokenInt(cur2.output) + parts[1],
439
+ reasoning: tokenInt(cur2.reasoning) + parts[2],
440
+ cache: {
441
+ read: tokenInt(cur2.cache?.read) + parts[3],
442
+ write: tokenInt(cur2.cache?.write) + parts[4],
443
+ },
444
+ }
445
+ }
446
+
447
+ /** True when the opencode_console MCP server is connected for this location. */
448
+ async function isConsoleMcpConnected(ctx: any): Promise<boolean> {
449
+ try {
450
+ if (typeof ctx?.mcp?.list !== "function") return false
451
+ const out = await ctx.mcp.list()
452
+ const servers = Array.isArray(out) ? out : (out?.data ?? [])
453
+ return servers.some((s: any) => /console/i.test(String(s?.name ?? "")) && s?.status?.status === "connected")
454
+ } catch {
455
+ return false
456
+ }
457
+ }
458
+
459
+ /** Provider id of a Model.Ref, unwrapping the `{ location, data }` client envelope. */
460
+ function providerOf(value: any): string | undefined {
461
+ const v = value && typeof value === "object" && "data" in value ? value.data : value
462
+ return v?.providerID ?? v?.provider ?? undefined
463
+ }
464
+
465
+ /**
466
+ * True when the run is on managed `opencode/` models — checked against the
467
+ * active session's model, the location default model, and every `team/*`
468
+ * agent's configured model. Any `opencode` provider ⇒ console credits apply.
469
+ */
470
+ async function usesOpencodeModel(ctx: any, sessionID?: string): Promise<boolean> {
471
+ // 1. The active session's model.
472
+ try {
473
+ if (sessionID && typeof ctx?.session?.get === "function") {
474
+ const s: any = await ctx.session.get({ sessionID })
475
+ if (providerOf(s?.model ?? s?.data?.model) === "opencode") return true
476
+ }
477
+ } catch {}
478
+ // 2. The location default model.
479
+ try {
480
+ if (typeof ctx?.model?.default === "function") {
481
+ if (providerOf(await ctx.model.default()) === "opencode") return true
482
+ }
483
+ } catch {}
484
+ // 3. Any team/* agent configured with an opencode/ model.
485
+ try {
486
+ if (typeof ctx?.agent?.list === "function") {
487
+ const out: any = await ctx.agent.list()
488
+ const agents = Array.isArray(out) ? out : (out?.data ?? [])
489
+ return agents.some((a: any) => /^team\//.test(String(a?.id ?? a?.name ?? "")) && providerOf(a?.model) === "opencode")
490
+ }
491
+ } catch {}
492
+ return false
493
+ }
494
+
495
+ const RUN_ROOT = ".opencode/teamwork"
496
+
497
+ // session ids are generated by us; anything else must match this allowlist.
498
+ const SESSION_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
499
+
500
+ /**
501
+ * A task id is used as a single filesystem path segment (worktree dir, verifier
502
+ * dir, report/conflict file names) and inside git branch names. Only allow a
503
+ * conservative single-segment token. `clean()` is NOT sufficient: it keeps `/`
504
+ * and `..`, which let `../../x` escape the worktrees base (SEC-1).
505
+ */
506
+ const TASK_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
507
+ function isSafeTaskId(id: string): boolean {
508
+ return TASK_ID.test(id) && id !== "." && id !== ".."
509
+ }
510
+
511
+ /**
512
+ * Canonical terminal status is `verified_pass`; `pass` is the legacy alias.
513
+ * Every completion count must use this predicate so a finished run is never
514
+ * reported as having zero passed tasks.
515
+ */
516
+ const isPassStatus = (s: any) => s === "pass" || s === "verified_pass"
517
+
518
+ // Canonical topologies (docs/ARTIFACTS.md) and the legacy aliases the plan tool
519
+ // still accepts. Aliases are normalised before they are persisted.
520
+ const TOPOLOGIES = ["small-focused", "iterative-coding", "distributed-coding", "proof", "massive-proof", "document-review"]
521
+ const TOPOLOGY_ALIASES: Record<string, string> = {
522
+ "large-swarm": "distributed-coding",
523
+ "doc-review": "document-review",
524
+ "long-proof": "proof",
525
+ "massive-proof-swarm": "massive-proof",
526
+ }
527
+
528
+ /** Normalise a topology (canonical or legacy alias); undefined when unknown. */
529
+ function normalizeTopology(value: unknown): string | undefined {
530
+ const v = clean(value, 64)
531
+ return TOPOLOGY_ALIASES[v] ?? (TOPOLOGIES.includes(v) ? v : undefined)
532
+ }
533
+
534
+ // Integrity modes (docs/ARTIFACTS.md). Chosen when the run is routed, recorded
535
+ // once in ORIGINAL_REQUEST.md, and read back from that artifact by the audit and
536
+ // final-verification gates. `development` is the default for legacy runs.
537
+ const INTEGRITY_MODES = ["development", "demo", "benchmark"] as const
538
+ type IntegrityMode = (typeof INTEGRITY_MODES)[number]
539
+ const DEFAULT_INTEGRITY_MODE: IntegrityMode = "development"
540
+ const REQUEST_MAX = 20000
541
+
542
+ /**
543
+ * Canonical integrity rules and the lowest mode that forbids each one
544
+ * (docs/ARTIFACTS.md). A higher mode inherits every prohibition below it.
545
+ * These are rules the auditor *reports* as violated; the tool cannot detect
546
+ * dishonesty, it only makes a reported violation binding.
547
+ */
548
+ const INTEGRITY_RULES = {
549
+ fabricated_output: { forbiddenFrom: "development" },
550
+ core_logic_copied: { forbiddenFrom: "demo" },
551
+ delegated_core_work: { forbiddenFrom: "demo" },
552
+ test_source_read: { forbiddenFrom: "demo" },
553
+ external_dependency_used: { forbiddenFrom: "benchmark" },
554
+ } as const satisfies Record<string, { forbiddenFrom: IntegrityMode }>
555
+ type IntegrityRule = keyof typeof INTEGRITY_RULES
556
+ const INTEGRITY_RULE_IDS = Object.keys(INTEGRITY_RULES) as IntegrityRule[]
557
+ const INTEGRITY_FINDINGS_MAX = 50
558
+
559
+ /** Normalise an integrity mode; undefined when it is not one of the three. */
560
+ function normalizeIntegrityMode(value: unknown): IntegrityMode | undefined {
561
+ const v = String(value ?? "").trim()
562
+ return (INTEGRITY_MODES as readonly string[]).includes(v) ? (v as IntegrityMode) : undefined
563
+ }
564
+
565
+ /** Rank a mode by strictness: development < demo < benchmark. */
566
+ function integrityModeRank(mode: IntegrityMode): number {
567
+ return INTEGRITY_MODES.indexOf(mode)
568
+ }
569
+
570
+ /** True when `rule` is forbidden at `mode` (at or above its threshold). */
571
+ function isIntegrityRuleForbidden(rule: IntegrityRule, mode: IntegrityMode): boolean {
572
+ return integrityModeRank(mode) >= integrityModeRank(INTEGRITY_RULES[rule].forbiddenFrom)
573
+ }
574
+
575
+ /**
576
+ * Read the integrity mode from `<run>/ORIGINAL_REQUEST.md`. That artifact is the
577
+ * only source of truth at audit/final-verification time; legacy runs have none,
578
+ * so they default to `development`.
579
+ */
580
+ function readIntegrityMode(run: string): { mode: IntegrityMode; source: "artifact" | "default" } {
581
+ const file = join(run, "ORIGINAL_REQUEST.md")
582
+ try {
583
+ if (existsSync(file)) {
584
+ const text = readFileSync(file, "utf8")
585
+ // Only the metadata block counts: a "- Integrity mode:" line inside the
586
+ // verbatim request body must never override the header.
587
+ const splitAt = text.indexOf("\n## Request")
588
+ const header = splitAt === -1 ? text : text.slice(0, splitAt)
589
+ const m = header.match(/^- Integrity mode:[ \t]*(\S+)[ \t]*$/m)
590
+ const mode = m && normalizeIntegrityMode(m[1])
591
+ if (mode) return { mode, source: "artifact" }
592
+ }
593
+ } catch {}
594
+ return { mode: DEFAULT_INTEGRITY_MODE, source: "default" }
595
+ }
596
+
597
+ // ---------------------------------------------------------------------------
598
+ // Input preflight
599
+ //
600
+ // A routed request often names files or URLs the work depends on. Before a run
601
+ // is created (or on demand for an existing run) the engine inventories those
602
+ // inputs and reports whether they exist / answer. The block list is deliberately
603
+ // narrow: explicit `inputs`, URLs, and tokens starting with `/`, `~/` or
604
+ // `file://`; other path-like tokens are advisory and never block.
605
+ // ---------------------------------------------------------------------------
606
+ const PREFLIGHT_MAX = 100
607
+ // The exact URL token grammar (docs/ARTIFACTS.md): no whitespace, no closing
608
+ // punctuation, no quote characters.
609
+ const PREFLIGHT_URL_RE = /https?:\/\/[^\s)>\]}"']+/g
610
+ const PREFLIGHT_URL_TIMEOUT_MS = 3000
611
+
612
+ type PreflightKind = "path" | "url"
613
+ type PreflightItemStatus = "READY" | "MISSING" | "UNCHECKED" | "OUTAGE"
614
+
615
+ interface PreflightItem {
616
+ /** Token exactly as named by the caller/request (or the local path it maps to). */
617
+ value: string
618
+ kind: PreflightKind
619
+ /** Explicit inputs, URLs and absolute/`~`/`file:` paths block; relative paths do not. */
620
+ blocking: boolean
621
+ /** A path-like relative token: reported, never blocking. */
622
+ advisory: boolean
623
+ status: PreflightItemStatus
624
+ /** `file`/`dir` for paths; an HTTP status or error/timeout for URLs. */
625
+ detail?: string
626
+ }
627
+
628
+ /** Strip surrounding prose punctuation from a whitespace token before checking it. */
629
+ function trimInputToken(token: string): string {
630
+ return token.replace(/^[([`"'<]+/, "").replace(/[)\]`"'>,.;:!?]+$/, "")
631
+ }
632
+
633
+ function isUrlToken(value: string): boolean {
634
+ return /^https?:\/\//i.test(value)
635
+ }
636
+
637
+ /**
638
+ * Build the deduplicated input inventory from the explicit `inputs` (highest
639
+ * trust) and the routed `request`. First-seen order wins; capped at 100 items.
640
+ */
641
+ function extractInventory(request: string | undefined, inputs: string[] | undefined): PreflightItem[] {
642
+ const seen = new Set<string>()
643
+ const items: PreflightItem[] = []
644
+ const add = (rawValue: string, kind: PreflightKind, blocking: boolean, advisory = false) => {
645
+ const value = clean(rawValue, 500).trim()
646
+ if (!value || seen.has(value) || items.length >= PREFLIGHT_MAX) return
647
+ seen.add(value)
648
+ items.push({ value, kind, blocking, advisory, status: kind === "url" ? "UNCHECKED" : "MISSING" })
649
+ }
650
+ // Explicit inputs are taken whole and always block, including relative paths.
651
+ for (const raw of inputs ?? []) {
652
+ if (raw) add(raw, isUrlToken(clean(raw, 500).trim()) ? "url" : "path", true)
653
+ }
654
+ if (typeof request === "string" && request) {
655
+ for (const match of request.matchAll(PREFLIGHT_URL_RE)) add(match[0], "url", true)
656
+ for (const rawToken of request.split(/\s+/)) {
657
+ const token = trimInputToken(rawToken)
658
+ if (!token || isUrlToken(token)) continue // URLs were captured above
659
+ if (token.startsWith("/") || token.startsWith("~/") || token.startsWith("file://")) {
660
+ add(token, "path", true)
661
+ } else if (token.includes("/") && !/\s/.test(token)) {
662
+ add(token, "path", false, true)
663
+ }
664
+ }
665
+ }
666
+ return items
667
+ }
668
+
669
+ /** Map a blocking path token (`~`, `~/`, `file:`) onto a local filesystem path. */
670
+ function localInputPath(value: string): string {
671
+ let p = value
672
+ if (p.startsWith("file://")) {
673
+ p = p.slice("file://".length)
674
+ try {
675
+ p = decodeURIComponent(p)
676
+ } catch {}
677
+ }
678
+ if (p === "~") return homedir()
679
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2))
680
+ return p
681
+ }
682
+
683
+ function checkInputPath(value: string): { status: PreflightItemStatus; detail?: string } {
684
+ const path = localInputPath(value)
685
+ try {
686
+ if (!existsSync(path)) return { status: "MISSING" }
687
+ const st = lstatSync(path)
688
+ return { status: "READY", detail: st.isDirectory() ? "dir" : st.isFile() ? "file" : "other" }
689
+ } catch {
690
+ return { status: "MISSING" }
691
+ }
692
+ }
693
+
694
+ async function checkInputUrl(value: string, checkUrls: boolean): Promise<{ status: PreflightItemStatus; detail?: string }> {
695
+ if (!checkUrls) return { status: "UNCHECKED", detail: "checkUrls: false" }
696
+ const controller = new AbortController()
697
+ const timer = setTimeout(() => controller.abort(), PREFLIGHT_URL_TIMEOUT_MS)
698
+ try {
699
+ // HEAD only: no body is read, and redirects are reported (not followed).
700
+ const res = await fetch(value, { method: "HEAD", signal: controller.signal, redirect: "manual" })
701
+ return {
702
+ status: res.status >= 200 && res.status < 400 ? "READY" : "OUTAGE",
703
+ detail: `HTTP ${res.status}`,
704
+ }
705
+ } catch (err: any) {
706
+ const why = err?.name === "AbortError" ? "timeout" : err?.message || "request failed"
707
+ return { status: "OUTAGE", detail: clean(why, 120) }
708
+ } finally {
709
+ clearTimeout(timer)
710
+ }
711
+ }
712
+
713
+ /** Run every check. Never throws; each item lands on READY/MISSING/UNCHECKED/OUTAGE. */
714
+ async function checkInventory(items: PreflightItem[], checkUrls: boolean): Promise<PreflightItem[]> {
715
+ await Promise.all(
716
+ items.map(async (item) => {
717
+ const result = item.kind === "url" ? await checkInputUrl(item.value, checkUrls) : checkInputPath(item.value)
718
+ item.status = result.status
719
+ if (result.detail) item.detail = result.detail
720
+ }),
721
+ )
722
+ return items
723
+ }
724
+
725
+ function summarizePreflight(items: PreflightItem[]) {
726
+ const missing = items.filter((i) => i.status === "MISSING")
727
+ const outage = items.filter((i) => i.status === "OUTAGE")
728
+ const blockingMissing = missing.filter((i) => i.blocking)
729
+ const advisoryMissing = missing.filter((i) => i.advisory)
730
+ // Advisory misses never change the overall status.
731
+ const status: "READY" | "MISSING" | "OUTAGE" = outage.length
732
+ ? "OUTAGE"
733
+ : blockingMissing.length
734
+ ? "MISSING"
735
+ : "READY"
736
+ return {
737
+ status,
738
+ total: items.length,
739
+ blocking: items.filter((i) => i.blocking).length,
740
+ missing: missing.length,
741
+ blockingMissing: blockingMissing.length,
742
+ advisoryMissing: advisoryMissing.length,
743
+ outage: outage.length,
744
+ unchecked: items.filter((i) => i.status === "UNCHECKED").length,
745
+ }
746
+ }
747
+
748
+ /** Read the verbatim request body back out of `<run>/ORIGINAL_REQUEST.md`. */
749
+ function readRecordedRequest(run: string): string | undefined {
750
+ try {
751
+ const file = join(run, "ORIGINAL_REQUEST.md")
752
+ if (!existsSync(file)) return undefined
753
+ const text = readFileSync(file, "utf8")
754
+ const marker = "\n## Request\n"
755
+ const at = text.indexOf(marker)
756
+ if (at === -1) return undefined
757
+ let body = text.slice(at + marker.length)
758
+ if (body.startsWith("\n")) body = body.slice(1)
759
+ return body
760
+ } catch {
761
+ return undefined
762
+ }
763
+ }
764
+
765
+ /**
766
+ * Write `<run>/ORIGINAL_REQUEST.md` exactly once, before any plan files.
767
+ * `request` is preserved byte-for-byte (no reflow, no trimming). Returns an
768
+ * actionable error string on refusal; the caller must then write nothing else.
769
+ * The open with `wx` makes "once" true even across two concurrent planners.
770
+ */
771
+ function writeOriginalRequest(run: string, request: string, mode: IntegrityMode, sessionId: string): string | undefined {
772
+ const file = join(run, "ORIGINAL_REQUEST.md")
773
+ try {
774
+ refuseSymlink(file)
775
+ } catch (err: any) {
776
+ return `refused: ${clean(err?.message, 160)}; nothing else was written`
777
+ }
778
+ let existing = ""
779
+ try {
780
+ if (existsSync(file)) existing = readFileSync(file, "utf8")
781
+ } catch {
782
+ return `refused: cannot read ${file}; refusing to overwrite a request that may already be recorded`
783
+ }
784
+ if (existing.trim()) {
785
+ return `refused: ${file} already records this run's request and is write-once.\nUse a new session (a new teamwork_plan sessionId) for a different request. Nothing was written.`
786
+ }
787
+ const body = `# Original Request\n\n- Integrity mode: ${mode}\n- Recorded: ${new Date().toISOString()}\n- Session: ${sessionId}\n\n## Request\n\n${request}`
788
+ try {
789
+ writeFileSync(file, body.endsWith("\n") ? body : body + "\n", { flag: "wx" })
790
+ } catch (err: any) {
791
+ if (err?.code === "EEXIST") {
792
+ return `refused: ${file} already records this run's request and is write-once.\nUse a new session (a new teamwork_plan sessionId) for a different request. Nothing was written.`
793
+ }
794
+ return `refused: could not record ${file} (${clean(err?.message, 120)}); nothing else was written`
795
+ }
796
+ return undefined
797
+ }
798
+
799
+ /**
800
+ * Lexical containment check: `child` must be a strict descendant of `parent`.
801
+ * Returns an error string when it is not, `undefined` when it is safe.
802
+ * Must be evaluated BEFORE any mkdir / rmSync / git worktree add on `child`.
803
+ */
804
+ function containmentError(parent: string, child: string): string | undefined {
805
+ const rel = relative(resolve(parent), resolve(child))
806
+ if (!rel || isAbsolute(rel) || rel.startsWith("..")) {
807
+ return "refused: target path escapes the worktrees base"
808
+ }
809
+ return undefined
810
+ }
811
+ const PHASES = new Set(["LOAD_SPEC", "WORKTREE_INIT", "DAG_BUILD", "DISPATCH", "SECURITY_AUDIT", "FINAL_VERIFICATION", "MERGE", "PRESENT_PARTIAL", "DONE"])
812
+
813
+ // Per-agent read-only policy, enforced in code. Keys are agent ids; values are
814
+ // the actions that agent may NOT perform. Anything not listed keeps its
815
+ // frontmatter permissions.
816
+ const READ_ONLY_ACTIONS: Record<string, Set<string>> = {
817
+ // Real OpenCode permission actions only (see the V2 docs): edit covers the
818
+ // write tool too, so "write"/"task" are intentionally not listed.
819
+ "team/verifier": new Set(["edit", "webfetch", "subagent"]),
820
+ "team/falsifier": new Set(["edit", "shell", "subagent"]),
821
+ "team/scout": new Set(["edit", "subagent"]),
822
+ "team/security-auditor": new Set(["edit", "webfetch", "subagent"]),
823
+ }
824
+
825
+ const pad = (n: number) => String(n).padStart(2, "0")
826
+
827
+ function newSessionId(): string {
828
+ const d = new Date()
829
+ const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
830
+ const hex = Math.random().toString(16).slice(2, 6)
831
+ return `${ts}-${hex}`
832
+ }
833
+
834
+ /**
835
+ * Strip control characters (C0, DEL, C1 incl. U+0085) / line separators and cap
836
+ * length. Never inject raw file text. Matches lib/timeline.mjs CONTROL_CHARS.
837
+ * NOT a prototype-safety mechanism: task ids need the TASK_ID allowlist and
838
+ * object-keyed state needs nullMap().
839
+ */
840
+ function clean(value: unknown, max = 64): string {
841
+ return String(value ?? "")
842
+ .replace(/[\r\n\t\x00-\x1f\x7f-\x9f\u0085\u2028\u2029]/g, " ")
843
+ .slice(0, max)
844
+ }
845
+
846
+ /**
847
+ * Multi-line variant of clean() for the cumulative feedback ledger: the same
848
+ * control characters are replaced with spaces, except "\n", which is preserved
849
+ * so one line can hold one round. The result never adds a line that the engine
850
+ * did not join itself. Truncation is marked with "…" and stays within `max`.
851
+ */
852
+ function cleanBlock(value: unknown, max = 2000): string {
853
+ const s = String(value ?? "").replace(/[\r\t\x00-\x09\x0b-\x1f\x7f-\x9f\u0085\u2028\u2029]/g, " ")
854
+ return s.length > max ? s.slice(0, Math.max(0, max - 1)) + "…" : s
855
+ }
856
+
857
+ /**
858
+ * A `verify/final.json` counts as *stamped* only when `teamwork_final_verify`
859
+ * wrote it: a non-empty `generatedBy` object with a non-empty `session`, a
860
+ * parseable `generatedAt`, and an `evidence` object. Anything else was written
861
+ * by hand (or by an engine older than the stamp), and cannot complete a run
862
+ * without the explicit, recorded `allowUnstamped` bypass.
863
+ */
864
+ function isStampedFinalReport(report: any): boolean {
865
+ if (!report || typeof report !== "object" || Array.isArray(report)) return false
866
+ const by = report.generatedBy
867
+ if (!by || typeof by !== "object" || Array.isArray(by)) return false
868
+ if (typeof by.session !== "string" || by.session.trim() === "") return false
869
+ if (typeof report.generatedAt !== "string" || Number.isNaN(Date.parse(report.generatedAt))) return false
870
+ const ev = report.evidence
871
+ return !!ev && typeof ev === "object" && !Array.isArray(ev)
872
+ }
873
+
874
+ /**
875
+ * Null-prototype copy of an object-keyed map (byTask, byTaskTokens, state.tasks).
876
+ * With no prototype, no inherited member name (constructor, __proto__, ...) can
877
+ * collide with a task/bucket key. Own keys are copied with [[Set]] onto a
878
+ * null-prototype target, so a "__proto__" key becomes an ordinary own property.
879
+ * JSON.stringify serialises the result exactly like a plain object.
880
+ */
881
+ function nullMap<T = any>(src?: unknown): Record<string, T> {
882
+ const out: Record<string, T> = Object.create(null)
883
+ if (src && typeof src === "object" && !Array.isArray(src)) {
884
+ for (const k of Object.keys(src as object)) out[k] = (src as Record<string, T>)[k]
885
+ }
886
+ return out
887
+ }
888
+
889
+ function runsDir(root: string) {
890
+ return join(root, RUN_ROOT)
891
+ }
892
+
893
+ function readPitfalls(run: string, taskId?: string): string[] {
894
+ try {
895
+ const file = join(run, "pitfalls.md")
896
+ if (!existsSync(file)) return []
897
+ const content = readFileSync(file, "utf8")
898
+ const lines = content
899
+ .split("\n")
900
+ .map((l) => l.trim())
901
+ .filter((l) => l.startsWith("-"))
902
+ .map((l) => clean(l.replace(/^-\s*/, ""), 200))
903
+ if (!taskId) return lines
904
+ const targetTag = `seen in ${clean(taskId, 64)}`
905
+ return lines.filter((l) => !l.includes("seen in ") || l.includes(targetTag))
906
+ } catch {
907
+ return []
908
+ }
909
+ }
910
+
911
+ /**
912
+ * Validate the run root itself: `.opencode` and `.opencode/teamwork` must not
913
+ * be symlinks, and the resolved base must stay inside the project root. This
914
+ * closes the "commit `.opencode/teamwork` as a symlink" escape that a run-dir
915
+ * check alone misses.
916
+ */
917
+ function runsBase(root: string): { base: string } | { error: string } {
918
+ const parent = join(root, ".opencode")
919
+ const base = join(parent, "teamwork")
920
+ for (const p of [parent, base]) {
921
+ try {
922
+ if (existsSync(p) && lstatSync(p).isSymbolicLink()) return { error: "refused: run root is a symlink" }
923
+ } catch {
924
+ return { error: "refused: run root is not readable" }
925
+ }
926
+ }
927
+ if (existsSync(base)) {
928
+ try {
929
+ const rel = relative(realpathSync(root), realpathSync(base))
930
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return { error: "refused: run root escapes the project" }
931
+ } catch {
932
+ return { error: "refused: run root is not resolvable" }
933
+ }
934
+ }
935
+ return { base }
936
+ }
937
+
938
+ /**
939
+ * Refuse to write through a symlinked file (would escape the run dir).
940
+ * lstat the path directly: existsSync() follows links, so a *dangling* symlink
941
+ * would otherwise be missed and the write would follow it.
942
+ */
943
+ function refuseSymlink(file: string) {
944
+ try {
945
+ if (lstatSync(file).isSymbolicLink()) {
946
+ throw new Error(`refused: refusing to write through symlink "${basename(file)}"`)
947
+ }
948
+ } catch (e: any) {
949
+ if (e?.code !== "ENOENT") throw e
950
+ }
951
+ }
952
+
953
+ function listRuns(root: string) {
954
+ const b = runsBase(root)
955
+ if ("error" in b) return [] as { name: string; path: string; mtime: number }[]
956
+ const dir = b.base
957
+ if (!existsSync(dir)) return [] as { name: string; path: string; mtime: number }[]
958
+ return readdirSync(dir)
959
+ .map((name) => {
960
+ const path = join(dir, name)
961
+ let mtime = 0
962
+ try {
963
+ mtime = lstatSync(path).mtimeMs
964
+ } catch {}
965
+ return { name, path, mtime }
966
+ })
967
+ .filter((e) => {
968
+ try {
969
+ // lstat: a symlinked dir is NOT a run (would escape the root).
970
+ return lstatSync(e.path).isDirectory()
971
+ } catch {
972
+ return false
973
+ }
974
+ })
975
+ .filter((e) => SESSION_ID.test(e.name)) // only names we could have generated
976
+ .sort((a, b) => b.mtime - a.mtime)
977
+ }
978
+
979
+ /**
980
+ * Resolve a run directory. Validates the run root, the session id (allowlist),
981
+ * and asserts — lexically and via realpath — that the result stays inside the
982
+ * run root. Closes `..` traversal and symlink escapes.
983
+ */
984
+ function resolveRun(root: string, sessionId?: string): { run?: string; error?: string } {
985
+ const b = runsBase(root)
986
+ if ("error" in b) return { error: b.error }
987
+ const base = b.base
988
+
989
+ if (sessionId) {
990
+ if (!SESSION_ID.test(sessionId)) return { error: `refused: invalid session id "${clean(sessionId, 32)}"` }
991
+ const run = join(base, sessionId)
992
+ const rel = relative(base, run)
993
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return { error: "refused: session id escapes the run root" }
994
+ if (existsSync(run)) {
995
+ try {
996
+ if (lstatSync(run).isSymbolicLink()) return { error: "refused: run dir is a symlink" }
997
+ const relReal = relative(realpathSync(base), realpathSync(run))
998
+ if (!relReal || relReal.startsWith("..") || isAbsolute(relReal)) return { error: "refused: run dir escapes the run root" }
999
+ } catch {
1000
+ return { error: "refused: run dir is not resolvable" }
1001
+ }
1002
+ }
1003
+ return { run }
1004
+ }
1005
+ const latest = listRuns(root)[0]?.path
1006
+ return latest ? { run: latest } : { error: "no Teamwork run found" }
1007
+ }
1008
+
1009
+ function readJson<T>(file: string, fallback: T): T {
1010
+ try {
1011
+ return JSON.parse(readFileSync(file, "utf8")) as T
1012
+ } catch {
1013
+ return fallback
1014
+ }
1015
+ }
1016
+
1017
+ function writeJson(file: string, value: unknown) {
1018
+ refuseSymlink(file)
1019
+ mkdirSync(dirname(file), { recursive: true })
1020
+ const tmp = file + ".tmp"
1021
+ refuseSymlink(tmp)
1022
+ writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n")
1023
+ renameSync(tmp, file)
1024
+ }
1025
+
1026
+ function touch(file: string, content: string) {
1027
+ refuseSymlink(file)
1028
+ mkdirSync(dirname(file), { recursive: true })
1029
+ if (!existsSync(file)) writeFileSync(file, content)
1030
+ }
1031
+
1032
+ /**
1033
+ * Next sequence number for one `<run>/events.jsonl`: a single number space per
1034
+ * file, starting at 1. Called inside the append lock, so no two appends can
1035
+ * race for the same value. The tail (last 8 KiB) is read rather than the whole
1036
+ * file: the last non-empty line's `seq` + 1 is the answer in the common case.
1037
+ * A legacy line without `seq`, or a malformed / truncated tail, falls back to
1038
+ * counting non-empty lines (correctness over micro-optimisation: a legacy log
1039
+ * still gets a value above every line already present, and nothing is lost).
1040
+ */
1041
+ function nextEventSeq(file: string): number {
1042
+ let tail = ""
1043
+ try {
1044
+ const fd = openSync(file, "r")
1045
+ try {
1046
+ const size = fstatSync(fd).size
1047
+ const len = Math.min(size, 8192)
1048
+ const buf = Buffer.alloc(len)
1049
+ let read = 0
1050
+ while (read < len) {
1051
+ const n = readSync(fd, buf, read, len - read, size - len + read)
1052
+ if (n === 0) break
1053
+ read += n
1054
+ }
1055
+ tail = buf.subarray(0, read).toString("utf8")
1056
+ } finally {
1057
+ closeSync(fd)
1058
+ }
1059
+ } catch {
1060
+ return 1 // absent events.jsonl: this is the first event
1061
+ }
1062
+ const lines = tail.split("\n")
1063
+ for (let i = lines.length - 1; i >= 0; i--) {
1064
+ const l = lines[i].trim()
1065
+ if (!l) continue
1066
+ try {
1067
+ const seq = (JSON.parse(l) as any)?.seq
1068
+ if (Number.isInteger(seq) && seq > 0) return seq + 1
1069
+ } catch {}
1070
+ break // last line is legacy or corrupt: count lines instead
1071
+ }
1072
+ try {
1073
+ let count = 0
1074
+ for (const l of readFileSync(file, "utf8").split("\n")) if (l.trim()) count++
1075
+ return count + 1
1076
+ } catch {
1077
+ return 1
1078
+ }
1079
+ }
1080
+
1081
+ /**
1082
+ * Append one lifecycle event to `<run>/events.jsonl` (append-only, one JSON
1083
+ * object per line). Fail-open: any error is swallowed so the DAG engine never
1084
+ * depends on the event log. Every string field is sanitised with clean() so no
1085
+ * value can inject a second physical line.
1086
+ *
1087
+ * `seq` is assigned here, inside the same lock as the append, and is monotonic
1088
+ * per file. `agentSource` records where the actor came from and is emitted only
1089
+ * when `agent` is non-null.
1090
+ */
1091
+ async function appendEvent(
1092
+ run: string,
1093
+ ev: {
1094
+ event: "run_created" | "task_transition" | "security_audit" | "final_verification" | "final_verification_bypass" | "preflight"
1095
+ sessionId: string
1096
+ taskId?: string | null
1097
+ from?: string | null
1098
+ to: string
1099
+ round?: number
1100
+ agent?: string | null
1101
+ /** Provenance of `agent`: explicit input, session lookup, or plan declaration. */
1102
+ agentSource?: "explicit" | "session" | "plan"
1103
+ branch?: string | null
1104
+ worktree?: string | null
1105
+ phase?: string | null
1106
+ /** run_created only: how the spec gate was decided (3.4). */
1107
+ specGate?: "satisfied" | "bypassed" | "not_required"
1108
+ /** run_created only: the spec file, when the gate was satisfied. */
1109
+ specPath?: string | null
1110
+ /**
1111
+ * final_verification_bypass: why an unstamped verdict was accepted.
1112
+ * preflight / run_created: an input-preflight bypass or missing-input note.
1113
+ */
1114
+ note?: string | null
1115
+ },
1116
+ ) {
1117
+ try {
1118
+ const eventsFile = join(run, "events.jsonl")
1119
+ await withFileLock(eventsFile, () => {
1120
+ refuseSymlink(eventsFile)
1121
+ const opt = (v: unknown, max: number) => (v === null || v === undefined || v === "" ? null : clean(v, max))
1122
+ const agent = opt(ev.agent, 64)
1123
+ const note = opt(ev.note, 200)
1124
+ const source =
1125
+ agent && (ev.agentSource === "explicit" || ev.agentSource === "session" || ev.agentSource === "plan")
1126
+ ? ev.agentSource
1127
+ : null
1128
+ const line = JSON.stringify({
1129
+ ts: new Date().toISOString(),
1130
+ seq: nextEventSeq(eventsFile),
1131
+ event: ev.event,
1132
+ sessionId: clean(ev.sessionId, 64),
1133
+ taskId: opt(ev.taskId, 64),
1134
+ from: opt(ev.from, 32),
1135
+ to: clean(ev.to, 32),
1136
+ round: Number(ev.round) || 0,
1137
+ agent,
1138
+ ...(source ? { agentSource: source } : {}),
1139
+ branch: opt(ev.branch, 120),
1140
+ worktree: opt(ev.worktree, 200),
1141
+ phase: opt(ev.phase, 32),
1142
+ ...(note ? { note } : {}),
1143
+ // Only run_created carries the spec-gate decision. Every line now also
1144
+ // carries seq (and agentSource when an actor exists); legacy lines on
1145
+ // disk keep their old shape and remain valid.
1146
+ ...(ev.specGate
1147
+ ? { specGate: clean(ev.specGate, 16), ...(ev.specPath ? { specPath: clean(ev.specPath, 200) } : {}) }
1148
+ : {}),
1149
+ })
1150
+ appendFileSync(eventsFile, line + "\n")
1151
+ })
1152
+ } catch {
1153
+ // fail-open: an events.jsonl write failure must never alter tool results
1154
+ }
1155
+ }
1156
+
1157
+ // Serialise read-modify-write of a run's cost files within this process, so
1158
+ // concurrent agents (parallel workers calling teamwork_cost at once) cannot
1159
+ // clobber each other's attribution. Keyed by the file path; the whole async
1160
+ // section — including the client read — runs inside the lock.
1161
+ const fileLocks = new Map<string, Promise<unknown>>()
1162
+ function withFileLock<T>(key: string, fn: () => Promise<T> | T): Promise<T> {
1163
+ const prev = fileLocks.get(key) ?? Promise.resolve()
1164
+ const next = prev.then(fn, fn)
1165
+ fileLocks.set(
1166
+ key,
1167
+ next.then(
1168
+ () => undefined,
1169
+ () => undefined,
1170
+ ),
1171
+ )
1172
+ return next as Promise<T>
1173
+ }
1174
+
1175
+ /**
1176
+ * Compact, sanitised run summary injected into team agents' system prompt.
1177
+ * Only whitelisted/enumerated fields are emitted; no raw file content.
1178
+ */
1179
+ export function describeRun(root: string): string | undefined {
1180
+ const { run } = resolveRun(root)
1181
+ if (!run) return undefined
1182
+ const state = readJson<any>(join(run, "state.json"), undefined)
1183
+ if (!state) return undefined
1184
+ const tasks = Object.values(state.tasks || {}) as any[]
1185
+ const pass = tasks.filter((t) => isPassStatus(t?.status)).length
1186
+ const fail = tasks.filter((t) => t?.status === "fail" || t?.status === "verified_fail" || t?.status === "blocked").length
1187
+ const allPitfalls = readPitfalls(run)
1188
+ const pitfalls = allPitfalls.length
1189
+ const recentPitfalls = allPitfalls.slice(-2).map((p) => clean(p, 70))
1190
+ const pitfallSuffix = recentPitfalls.length ? ` (recent: ${recentPitfalls.join("; ")})` : ""
1191
+ const id = basename(run)
1192
+ if (!SESSION_ID.test(id)) return undefined // never inject a non-conforming dir name
1193
+ const phase = PHASES.has(state.phase) ? state.phase : "UNKNOWN"
1194
+ const costs = readJson<any>(join(run, "costs.json"), undefined)
1195
+ let costLine = "Cost: unknown."
1196
+ if (costs && typeof costs.budgetUsd === "number") {
1197
+ const budget = costs.budgetUsd
1198
+ const spent = Number(costs.spentUsd) || 0
1199
+ const pct = budget ? Math.floor((spent / budget) * 100) : 0
1200
+ costLine = `Cost: $${spent} of $${budget} (${pct}%)${pct >= 80 ? " — near budget, halt non-essential workers" : ""}.`
1201
+ }
1202
+ return [
1203
+ `[teamwork] active run ${id} — phase ${phase}.`,
1204
+ `Tasks: ${pass}/${tasks.length} pass, ${fail} fail. Open pitfalls: ${pitfalls}${pitfallSuffix}.`,
1205
+ costLine,
1206
+ `State: ${join(runsDir(root), id, "state.json")} (read it before dispatching).`,
1207
+ ].join("\n")
1208
+ }
1209
+
1210
+ export async function registerTeamworkTools(ctx: any, root: string) {
1211
+ if (!ctx?.tool?.transform) return
1212
+ await ctx.tool.transform((editor: any) => {
1213
+ editor.namespace({
1214
+ name: "teamwork",
1215
+ description: "Deterministic Teamwork run state: plan, status, resume, cost, pitfalls.",
1216
+ })
1217
+
1218
+ editor.add({
1219
+ name: "plan",
1220
+ description:
1221
+ "Create a Teamwork run directory and write plan.dag.json + state.json + costs.json. Returns the run path and the (validated) session id. Call this once before dispatching workers.",
1222
+ input: {
1223
+ type: "object",
1224
+ properties: {
1225
+ sessionId: { type: "string", description: "Reuse an existing session id; omit to create one." },
1226
+ topology: { type: "string", description: "small-focused | iterative-coding | distributed-coding | proof | massive-proof | document-review. Legacy aliases accepted and normalised: large-swarm → distributed-coding, doc-review → document-review, long-proof → proof, massive-proof-swarm → massive-proof." },
1227
+ routingReason: { type: "string", description: "Optional. Why this topology was chosen; persisted in plan.dag.json when provided." },
1228
+ request: { type: "string", description: "Optional. The verbatim text this run was routed on (max 20000 chars); recorded once in ORIGINAL_REQUEST.md. A second plan into the same run with a non-empty request file is refused." },
1229
+ integrityMode: { type: "string", description: "development | demo | benchmark. Default development. Recorded in ORIGINAL_REQUEST.md, state.json and plan.dag.json; the security auditor and final gate read it from ORIGINAL_REQUEST.md." },
1230
+ budgetUsd: { type: "number", description: "Run budget in USD. When using opencode/ models + opencode_console, derive this from credits (full or partial, per the user's choice)." },
1231
+ budgetSource: { type: "string", description: "Where the budget came from: credits | default | manual." },
1232
+ requireSpec: { type: "boolean", description: "Default true. When true, the run must have a non-empty prompt_draft.md (the approved spec) before the plan is written; see skipInterview for the explicit bypass." },
1233
+ skipInterview: { type: "boolean", description: "Default false. Explicit bypass of the spec gate: plan without an approved prompt_draft.md. Recorded in events.jsonl as specGate: bypassed." },
1234
+ inputs: {
1235
+ type: "array",
1236
+ items: { type: "string" },
1237
+ description: "Optional. Files/URLs this run depends on, checked before anything is written. Every entry is blocking, including relative paths (resolved from the engine's cwd).",
1238
+ },
1239
+ checkUrls: {
1240
+ type: "boolean",
1241
+ description: "Default false. When false, URLs are recorded UNCHECKED. When true, each URL gets a HEAD request with a 3 s timeout; failures refuse the plan.",
1242
+ },
1243
+ allowMissingInputs: {
1244
+ type: "boolean",
1245
+ description: "Default false. Explicit bypass: plan even when a blocking input is MISSING/OUTAGE. The bypass is recorded in plan.dag.json and events.jsonl.",
1246
+ },
1247
+ tasks: {
1248
+ type: "array",
1249
+ items: {
1250
+ type: "object",
1251
+ properties: {
1252
+ id: { type: "string" },
1253
+ dependsOn: { type: "array", items: { type: "string" } },
1254
+ requirements: { type: "array", items: { type: "string" } },
1255
+ agent: { type: "string" },
1256
+ maxRounds: { type: "number" },
1257
+ },
1258
+ required: ["id"],
1259
+ additionalProperties: true,
1260
+ },
1261
+ },
1262
+ },
1263
+ required: ["topology", "tasks"],
1264
+ additionalProperties: false,
1265
+ },
1266
+ execute: async (input: any, context: any) => {
1267
+ const sessionId = input.sessionId || newSessionId()
1268
+ const resolved = resolveRun(root, sessionId)
1269
+ if (resolved.error) return { content: resolved.error }
1270
+ const run = resolved.run as string
1271
+ // Refuse an unknown topology before anything is written, so a typo can
1272
+ // never become the run's permanent label.
1273
+ const topology = normalizeTopology(input.topology)
1274
+ if (!topology) {
1275
+ return {
1276
+ content: `refused: invalid topology "${clean(input.topology, 32)}" (accepted: ${TOPOLOGIES.join(", ")}; aliases: ${Object.keys(TOPOLOGY_ALIASES).join(", ")})`,
1277
+ }
1278
+ }
1279
+ // Refuse an unknown integrity mode before anything is written. The mode
1280
+ // is the run's integrity contract, so a typo must never be persisted.
1281
+ const integrityMode =
1282
+ input.integrityMode === undefined || input.integrityMode === null
1283
+ ? DEFAULT_INTEGRITY_MODE
1284
+ : normalizeIntegrityMode(input.integrityMode)
1285
+ if (!integrityMode) {
1286
+ return {
1287
+ content: `refused: invalid integrityMode "${clean(input.integrityMode, 32)}" (accepted: ${INTEGRITY_MODES.join(", ")}; default: ${DEFAULT_INTEGRITY_MODE})`,
1288
+ }
1289
+ }
1290
+ // The request record is verbatim, so refuse rather than truncate. The
1291
+ // length check runs before anything is written.
1292
+ const request = typeof input.request === "string" ? input.request : undefined
1293
+ if (request !== undefined && request.length > REQUEST_MAX) {
1294
+ return {
1295
+ content: `refused: request is ${request.length} chars, over the ${REQUEST_MAX}-char limit; it must be recorded verbatim. Shorten it or start the run from a shorter routed request. Nothing was written.`,
1296
+ }
1297
+ }
1298
+ // SEC-1: task ids become keys of state/costs maps and path/branch segments.
1299
+ // Refuse the whole plan (before anything is written) on any unsafe id.
1300
+ for (const t of input.tasks || []) {
1301
+ const ids = [t?.id, ...(Array.isArray(t?.dependsOn) ? t.dependsOn : [])]
1302
+ const i = ids.findIndex((id: unknown) => typeof id !== "string" || !isSafeTaskId(id))
1303
+ if (i !== -1) {
1304
+ return { content: `refused: invalid task id "${clean(ids[i], 32)}" (must be a single segment matching ${TASK_ID})` }
1305
+ }
1306
+ }
1307
+ // ORIGINAL_REQUEST.md is write-once. Check before the spec gate so a
1308
+ // second request is refused for the right reason and writes nothing.
1309
+ const originalRequestFile = join(run, "ORIGINAL_REQUEST.md")
1310
+ if (request !== undefined) {
1311
+ try {
1312
+ if (existsSync(originalRequestFile) && readFileSync(originalRequestFile, "utf8").trim()) {
1313
+ return {
1314
+ content: `refused: ${originalRequestFile} already records this run's request and is write-once.\nUse a new session (a new teamwork_plan sessionId) for a different request. Nothing was written.`,
1315
+ }
1316
+ }
1317
+ } catch {
1318
+ return { content: `refused: cannot read ${originalRequestFile}; refusing to overwrite a request that may already be recorded. Nothing was written.` }
1319
+ }
1320
+ }
1321
+ // 3.4: a run starts from an approved spec (`<run>/prompt_draft.md`). The
1322
+ // gate runs BEFORE mkdir, so a refusal leaves no run dir and no plan files
1323
+ // behind. `skipInterview` is the explicit, recorded bypass.
1324
+ const specFile = join(run, "prompt_draft.md")
1325
+ let specText = ""
1326
+ try {
1327
+ if (existsSync(specFile)) specText = readFileSync(specFile, "utf8").trim()
1328
+ } catch {
1329
+ specText = "" // unreadable spec = no usable spec
1330
+ }
1331
+ const hasSpec = specText.length > 0
1332
+ const specGate: "satisfied" | "bypassed" | "not_required" | undefined =
1333
+ input.requireSpec === false ? "not_required" : hasSpec ? "satisfied" : input.skipInterview === true ? "bypassed" : undefined
1334
+ if (!specGate) {
1335
+ return {
1336
+ content: `refused: no spec found for this run (expected ${specFile}). Run /teamwork-craft to produce one, or re-call with skipInterview: true to proceed without an approved prompt.`,
1337
+ }
1338
+ }
1339
+ // Input preflight. Runs before mkdir so a refusal writes NOTHING (no run
1340
+ // dir, no ORIGINAL_REQUEST.md, no plan). Only a narrow block list can
1341
+ // refuse: explicit inputs, URLs, and absolute/`~`/`file:` paths. Relative
1342
+ // path-like tokens are advisory and can never block.
1343
+ const explicitInputs = (Array.isArray(input.inputs) ? input.inputs : []).filter(
1344
+ (v: unknown): v is string => typeof v === "string",
1345
+ )
1346
+ let preflight: { status: "READY" | "MISSING" | "OUTAGE" | "SKIPPED"; bypassed?: boolean } = { status: "SKIPPED" }
1347
+ let preflightNote: string | undefined
1348
+ let preflightLine = "Preflight: SKIPPED (no request or explicit inputs)."
1349
+ if (request !== undefined || explicitInputs.length > 0) {
1350
+ const items = await checkInventory(extractInventory(request, explicitInputs), input.checkUrls === true)
1351
+ const summary = summarizePreflight(items)
1352
+ const blockingProblems = items.filter(
1353
+ (i) => i.blocking && (i.status === "MISSING" || i.status === "OUTAGE"),
1354
+ )
1355
+ if (blockingProblems.length > 0 && input.allowMissingInputs !== true) {
1356
+ return {
1357
+ content: [
1358
+ `refused: ${blockingProblems.length} required input(s) are missing or unreachable; nothing was written.`,
1359
+ ...blockingProblems.map((i) => ` ${i.status} ${i.value}${i.detail ? ` (${i.detail})` : ""}`),
1360
+ "Fix the paths/URLs, or re-call with allowMissingInputs: true to proceed and record the bypass.",
1361
+ ].join("\n"),
1362
+ }
1363
+ }
1364
+ if (blockingProblems.length > 0) {
1365
+ preflight = { status: summary.status, bypassed: true }
1366
+ preflightNote = `preflight bypassed: ${summary.status} (${blockingProblems.length} item${blockingProblems.length === 1 ? "" : "s"})`
1367
+ } else {
1368
+ preflight = { status: summary.status, bypassed: false }
1369
+ }
1370
+ const advisory = items.filter((i) => i.advisory && i.status === "MISSING").map((i) => i.value)
1371
+ preflightLine = `Preflight: ${summary.status}${preflight.bypassed ? " (bypassed: allowMissingInputs)" : ""} (${summary.total} item(s); ${summary.unchecked} unchecked)${advisory.length ? `; ${advisory.length} advisory path missing (non-blocking): ${advisory.join(", ")}` : ""}.`
1372
+ }
1373
+ mkdirSync(run, { recursive: true })
1374
+ // The request record goes first: it is the artifact the auditor and the
1375
+ // final gate read the integrity mode from.
1376
+ if (request !== undefined) {
1377
+ const refused = writeOriginalRequest(run, request, integrityMode, sessionId)
1378
+ if (refused) return { content: refused }
1379
+ }
1380
+ const tasks = (input.tasks || []).map((t: any) => ({
1381
+ id: clean(t.id, 64),
1382
+ dependsOn: Array.isArray(t.dependsOn) ? t.dependsOn.map((d: any) => clean(d, 64)) : [],
1383
+ requirements: Array.isArray(t.requirements) ? t.requirements.map((r: any) => clean(r, 120)) : [],
1384
+ agent: clean(t.agent || "team/worker", 64),
1385
+ status: "pending",
1386
+ round: 0,
1387
+ maxRounds: Number.isFinite(t.maxRounds) ? t.maxRounds : 4,
1388
+ }))
1389
+ const routingReason = typeof input.routingReason === "string" ? clean(input.routingReason, 200).trim() : ""
1390
+ writeJson(join(run, "plan.dag.json"), {
1391
+ sessionId,
1392
+ topology,
1393
+ integrityMode,
1394
+ preflight,
1395
+ tasks,
1396
+ ...(routingReason ? { routingReason } : {}),
1397
+ })
1398
+ if (!existsSync(join(run, "state.json"))) {
1399
+ writeJson(join(run, "state.json"), {
1400
+ version: 1,
1401
+ sessionId,
1402
+ integrityMode,
1403
+ phase: "DISPATCH",
1404
+ tasks: nullMap(Object.fromEntries(tasks.map((t: any) => [t.id, { status: "pending", round: 0 }]))),
1405
+ updatedAt: new Date().toISOString(),
1406
+ })
1407
+ } else {
1408
+ // A re-plan keeps the run's checkpoint but must still carry the mode
1409
+ // the caller chose (defaults to development when omitted).
1410
+ const stateFile = join(run, "state.json")
1411
+ const state = readJson<any>(stateFile, undefined)
1412
+ if (state && state.integrityMode !== integrityMode) {
1413
+ state.integrityMode = integrityMode
1414
+ state.updatedAt = new Date().toISOString()
1415
+ writeJson(stateFile, state)
1416
+ }
1417
+ }
1418
+ // Use ?? (nullish coalescing) so budgetUsd: 0 is respected as "no budget"
1419
+ const budget = input.budgetUsd ?? 20
1420
+ const costsFile = join(run, "costs.json")
1421
+ const callSession = typeof context?.sessionID === "string" ? context.sessionID : undefined
1422
+ // Same lock as the cost tool so a re-plan cannot race a concurrent cost call.
1423
+ await withFileLock(costsFile, async () => {
1424
+ const existing = readJson<any>(costsFile, undefined)
1425
+ if (!existing) {
1426
+ writeJson(costsFile, {
1427
+ sessionId,
1428
+ rootSessionIds: callSession ? [callSession] : [],
1429
+ budgetUsd: budget,
1430
+ budgetSource: input.budgetSource ? clean(input.budgetSource, 32) : "default",
1431
+ spentUsd: 0,
1432
+ byTask: nullMap(),
1433
+ byTaskTokens: nullMap(),
1434
+ updatedAt: new Date().toISOString(),
1435
+ })
1436
+ } else {
1437
+ existing.byTaskTokens = nullMap(existing.byTaskTokens)
1438
+ existing.byTask = nullMap(existing.byTask)
1439
+ if (callSession) {
1440
+ const currentRoots = Array.isArray(existing.rootSessionIds) ? existing.rootSessionIds : []
1441
+ if (!currentRoots.includes(callSession)) {
1442
+ existing.rootSessionIds = [...currentRoots, callSession]
1443
+ }
1444
+ }
1445
+ if (
1446
+ existing.budgetUsd !== budget ||
1447
+ (input.budgetSource && existing.budgetSource !== clean(input.budgetSource, 32))
1448
+ ) {
1449
+ // Update the budget/source but PRESERVE accumulated spend and
1450
+ // per-task buckets (a re-plan must not wipe the run's measured cost).
1451
+ existing.budgetUsd = budget
1452
+ if (input.budgetSource) existing.budgetSource = clean(input.budgetSource, 32)
1453
+ }
1454
+ existing.updatedAt = new Date().toISOString()
1455
+ writeJson(costsFile, existing)
1456
+ }
1457
+ // Establish the native cost baseline for the calling session, preserving
1458
+ // any baselines already recorded for other sessions (merge, don't clobber).
1459
+ const now = new Date().toISOString()
1460
+ const snaps = readSnapshots(join(run, "snapshots.json")) ?? { sessionId, rootSessionIds: [], bySession: {} }
1461
+ snaps.sessionId = sessionId
1462
+ if (!snaps.rootSessionIds) snaps.rootSessionIds = []
1463
+ if (callSession && !snaps.rootSessionIds.includes(callSession)) {
1464
+ snaps.rootSessionIds.push(callSession)
1465
+ }
1466
+ const usage = await readSessionUsage(ctx, callSession)
1467
+ if (callSession && usage && !snaps.bySession[callSession]) {
1468
+ snaps.bySession[callSession] = { lastCost: usage.cost, lastTokens: usage.tokens, timestamp: now }
1469
+ }
1470
+ writeSnapshots(join(run, "snapshots.json"), snaps)
1471
+ })
1472
+ touch(join(run, "pitfalls.md"), "# Pitfalls\n\n_answer-agnostic failure modes; one per line_\n")
1473
+ await appendEvent(run, { event: "run_created", sessionId, taskId: null, from: null, to: "pending", round: 0, phase: "DAG_BUILD", specGate, ...(specGate === "satisfied" ? { specPath: specFile } : {}), ...(preflightNote ? { note: preflightNote } : {}) })
1474
+ // Backstop: if console credits apply but the budget wasn't derived from
1475
+ // them, warn (advisory — the sentinel is instructed to run the preflight).
1476
+ let creditWarning = ""
1477
+ if (input.budgetSource !== "credits" && (await isConsoleMcpConnected(ctx)) && (await usesOpencodeModel(ctx, context?.sessionID))) {
1478
+ creditWarning = "\n⚠ opencode/ models + opencode_console connected — run teamwork_budget and derive budgetUsd from credits before dispatching."
1479
+ }
1480
+ return {
1481
+ content: `Planned ${tasks.length} task(s).\nSESSION_ID: ${sessionId}\nRun dir: ${run}\nBudget: $${budget} (source: ${input.budgetSource ? clean(input.budgetSource, 32) : "default"})\nplan.dag.json + state.json + costs.json written.\n${preflightLine}\nIntegrity mode: ${integrityMode}${request !== undefined ? ` (request recorded in ${originalRequestFile})` : ""}.${specGate === "bypassed" ? "\n⚠ Spec gate bypassed (skipInterview: true): planned without an approved prompt_draft.md." : ""}${preflight.bypassed ? `\n⚠ Input preflight bypassed (allowMissingInputs: true): ${preflight.status}.` : ""}${creditWarning}`,
1482
+ }
1483
+ },
1484
+ })
1485
+
1486
+ editor.add({
1487
+ name: "preflight",
1488
+ description:
1489
+ "Re-run the input preflight for an existing run: check the files/URLs named by ORIGINAL_REQUEST.md plus any explicit inputs, write <run>/preflight.json, and append a preflight event. Never throws.",
1490
+ input: {
1491
+ type: "object",
1492
+ properties: {
1493
+ sessionId: { type: "string", description: "Run to check; omit for the latest run." },
1494
+ inputs: {
1495
+ type: "array",
1496
+ items: { type: "string" },
1497
+ description: "Optional additional blocking files/URLs to check alongside the recorded request.",
1498
+ },
1499
+ checkUrls: {
1500
+ type: "boolean",
1501
+ description: "Default false. When false, URLs are recorded UNCHECKED. When true, each gets a HEAD request with a 3 s timeout.",
1502
+ },
1503
+ },
1504
+ additionalProperties: false,
1505
+ },
1506
+ execute: async (input: any) => {
1507
+ const resolved = resolveRun(root, input?.sessionId)
1508
+ if (resolved.error) return { content: resolved.error }
1509
+ const run = resolved.run as string
1510
+ const explicitInputs = (Array.isArray(input?.inputs) ? input.inputs : []).filter(
1511
+ (v: unknown): v is string => typeof v === "string",
1512
+ )
1513
+ const recorded = readRecordedRequest(run)
1514
+ const items = await checkInventory(extractInventory(recorded, explicitInputs), input?.checkUrls === true)
1515
+ const summary = summarizePreflight(items)
1516
+ const integrity = readIntegrityMode(run)
1517
+ const checkedAt = new Date().toISOString()
1518
+ const report = { checkedAt, integrityMode: integrity.mode, items, summary }
1519
+ const file = join(run, "preflight.json")
1520
+ refuseSymlink(file)
1521
+ writeJson(file, report)
1522
+
1523
+ const problems = items.filter((i) => i.status === "MISSING" || i.status === "OUTAGE")
1524
+ const note = problems.length
1525
+ ? `preflight ${summary.status}: ${problems.length} item(s) missing or unreachable`
1526
+ : undefined
1527
+ const state = readJson<any>(join(run, "state.json"), {})
1528
+ await appendEvent(run, {
1529
+ event: "preflight",
1530
+ sessionId: basename(run),
1531
+ taskId: null,
1532
+ from: null,
1533
+ to: summary.status,
1534
+ round: 0,
1535
+ phase: state?.phase ?? null,
1536
+ ...(note ? { note } : {}),
1537
+ })
1538
+
1539
+ const lines = items.map(
1540
+ (i) => ` ${i.status} ${i.value}${i.detail ? ` (${i.detail})` : ""}${i.advisory ? " [advisory]" : ""}`,
1541
+ )
1542
+ return {
1543
+ content: [
1544
+ `Preflight ${summary.status}: ${summary.total} item(s), ${summary.blockingMissing} blocking missing, ${summary.outage} outage, ${summary.unchecked} unchecked.`,
1545
+ ...lines,
1546
+ `Artifact: ${file}`,
1547
+ ].join("\n"),
1548
+ status: summary.status,
1549
+ summary,
1550
+ items,
1551
+ integrityMode: integrity.mode,
1552
+ preflightPath: file,
1553
+ }
1554
+ },
1555
+ })
1556
+
1557
+ editor.add({
1558
+ name: "status",
1559
+ description: "Read the active (or given) Teamwork run and summarize per-task progress.",
1560
+ input: { type: "object", properties: { sessionId: { type: "string" } }, additionalProperties: false },
1561
+ execute: async (input: any) => {
1562
+ const resolved = resolveRun(root, input?.sessionId)
1563
+ if (resolved.error) return { content: resolved.error }
1564
+ const run = resolved.run as string
1565
+ const state = readJson<any>(join(run, "state.json"), {})
1566
+ const tasks = state.tasks || {}
1567
+ const lines = Object.entries(tasks).map(([id, t]: any) => ` ${clean(id, 64)}: ${clean(t?.status, 16)} (round ${Number(t?.round) || 0})`)
1568
+ const pass = Object.values(tasks).filter((t: any) => isPassStatus(t?.status)).length
1569
+ return { content: `Run ${basename(run)} — phase ${PHASES.has(state.phase) ? state.phase : "UNKNOWN"}\n${pass}/${lines.length} pass\n${lines.join("\n")}` }
1570
+ },
1571
+ })
1572
+
1573
+ editor.add({
1574
+ name: "resume",
1575
+ description: "Return the tasks that still need work (pending/running/fail) so a restarted Sentinel can continue where it stopped.",
1576
+ input: { type: "object", properties: { sessionId: { type: "string" } }, additionalProperties: false },
1577
+ execute: async (input: any) => {
1578
+ const resolved = resolveRun(root, input?.sessionId)
1579
+ if (resolved.error) return { content: resolved.error }
1580
+ const run = resolved.run as string
1581
+ const state = readJson<any>(join(run, "state.json"), {})
1582
+ const open = Object.entries(state.tasks || {}).filter(([, t]: any) => !isPassStatus(t?.status))
1583
+ if (!open.length) return { content: `Run ${basename(run)} is complete (all tasks pass).` }
1584
+ return {
1585
+ content: `Resume ${basename(run)} at phase ${PHASES.has(state.phase) ? state.phase : "UNKNOWN"}. Open tasks:\n` + open.map(([id, t]: any) => ` ${clean(id, 64)}: ${clean(t?.status, 16)} round ${Number(t?.round) || 0}`).join("\n"),
1586
+ }
1587
+ },
1588
+ })
1589
+
1590
+ editor.add({
1591
+ name: "cost",
1592
+ description:
1593
+ "Read the run budget and report real spend across the full session tree (Sentinel + all workers/verifiers). Uses OpenCode's native cost and token tracking; falls back to manual addUsd when client/db is unavailable. Warns at 80%.",
1594
+ input: { type: "object", properties: { sessionId: { type: "string" }, addUsd: { type: "number" }, taskId: { type: "string" } }, additionalProperties: false },
1595
+ execute: async (input: any, context: any) => {
1596
+ // SEC-1: the taskId becomes a costs.byTask key. Refuse unsafe ids (e.g.
1597
+ // "__proto__", "a/b") before any read or write.
1598
+ if (input?.taskId && (typeof input.taskId !== "string" || !isSafeTaskId(input.taskId))) {
1599
+ return { content: `refused: invalid task id "${clean(input.taskId, 32)}" (must be a single segment matching ${TASK_ID})` }
1600
+ }
1601
+ const resolved = resolveRun(root, input?.sessionId)
1602
+ if (resolved.error) return { content: resolved.error }
1603
+ const run = resolved.run as string
1604
+ const file = join(run, "costs.json")
1605
+ const snapshotsFile = join(run, "snapshots.json")
1606
+
1607
+ const callSession = typeof context?.sessionID === "string" ? context.sessionID : undefined
1608
+
1609
+ // Serialise the whole read-modify-write (including the client read) so
1610
+ // parallel workers cannot lose each other's attribution.
1611
+ return await withFileLock(file, async () => {
1612
+ const costs = readJson<any>(file, undefined)
1613
+ if (!costs || typeof costs !== "object") {
1614
+ return { content: `No costs.json for run ${basename(run)} — call teamwork_plan first.` }
1615
+ }
1616
+ // Null-prototype maps (SEC-1): no bucket name can collide with an inherited member.
1617
+ costs.byTask = nullMap(costs.byTask)
1618
+ // Additive key: tolerate its absence in costs.json written before it existed.
1619
+ costs.byTaskTokens = nullMap(costs.byTaskTokens)
1620
+ const budget = costs.budgetUsd ?? 20
1621
+
1622
+ const snaps = readSnapshots(snapshotsFile) ?? { sessionId: basename(run), rootSessionIds: [], bySession: {} }
1623
+ snaps.sessionId = basename(run)
1624
+ if (!snaps.rootSessionIds) snaps.rootSessionIds = []
1625
+ if (callSession && !snaps.rootSessionIds.includes(callSession)) {
1626
+ snaps.rootSessionIds.push(callSession)
1627
+ }
1628
+ if (Array.isArray(costs.rootSessionIds)) {
1629
+ for (const r of costs.rootSessionIds) {
1630
+ if (typeof r === "string" && !snaps.rootSessionIds.includes(r)) {
1631
+ snaps.rootSessionIds.push(r)
1632
+ }
1633
+ }
1634
+ }
1635
+
1636
+ const addToBucket = (bucketName: string, amount: number) => {
1637
+ if (amount <= 0) return
1638
+ costs.byTask[bucketName] = Math.round(((costs.byTask[bucketName] || 0) + amount) * 1e4) / 1e4
1639
+ }
1640
+
1641
+ const treeResult = await readSessionTreeUsage(ctx, snaps.rootSessionIds, callSession)
1642
+ let source: string
1643
+
1644
+ if (treeResult && treeResult.sessions.length > 0) {
1645
+ const now = new Date().toISOString()
1646
+ const totalTokens: TokenUsage = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
1647
+
1648
+ for (const s of treeResult.sessions) {
1649
+ const prev = snaps.bySession[s.id]
1650
+ const delta = prev
1651
+ ? Math.round((s.cost - prev.lastCost) * 1e4) / 1e4
1652
+ : Math.round(s.cost * 1e4) / 1e4
1653
+
1654
+ snaps.bySession[s.id] = {
1655
+ lastCost: s.cost,
1656
+ lastTokens: s.tokens,
1657
+ agent: s.agent,
1658
+ timestamp: now,
1659
+ }
1660
+
1661
+ let bucket: string
1662
+ if (s.id === callSession && input.taskId) {
1663
+ bucket = clean(input.taskId, 64)
1664
+ } else if (snaps.rootSessionIds.includes(s.id)) {
1665
+ bucket = input.taskId ? clean(input.taskId, 64) : "_sentinel"
1666
+ } else if (s.agent) {
1667
+ bucket = input.taskId ? clean(input.taskId, 64) : clean(s.agent, 64)
1668
+ } else {
1669
+ bucket = input.taskId ? clean(input.taskId, 64) : "_unattributed"
1670
+ }
1671
+ if (delta > 0) addToBucket(bucket, delta)
1672
+ accumulateTokenDelta(costs, bucket, s.tokens, prev)
1673
+
1674
+ totalTokens.input += s.tokens.input
1675
+ totalTokens.output += s.tokens.output
1676
+ totalTokens.reasoning += s.tokens.reasoning
1677
+ totalTokens.cache.read += s.tokens.cache.read
1678
+ totalTokens.cache.write += s.tokens.cache.write
1679
+ }
1680
+
1681
+ costs.spentUsd =
1682
+ Math.round(Object.values(costs.byTask).reduce((a: number, b: any) => a + (Number(b) || 0), 0) * 1e4) / 1e4
1683
+ costs.tokens = totalTokens
1684
+ costs.rootSessionIds = snaps.rootSessionIds
1685
+ costs.updatedAt = now
1686
+ writeJson(file, costs)
1687
+ writeSnapshots(snapshotsFile, snaps)
1688
+ source = `opencode session tree (${treeResult.sessions.length} sessions, via ${treeResult.source})`
1689
+ } else if (callSession) {
1690
+ const usage = await readSessionUsage(ctx, callSession)
1691
+ if (usage) {
1692
+ const now = new Date().toISOString()
1693
+ const prev = snaps.bySession[callSession]
1694
+ const delta = prev
1695
+ ? Math.round((usage.cost - prev.lastCost) * 1e4) / 1e4
1696
+ : Math.round(usage.cost * 1e4) / 1e4
1697
+ snaps.bySession[callSession] = { lastCost: usage.cost, lastTokens: usage.tokens, timestamp: now }
1698
+ const bucket = input.taskId ? clean(input.taskId, 64) : "_unattributed"
1699
+ if (delta > 0) addToBucket(bucket, delta)
1700
+ accumulateTokenDelta(costs, bucket, usage.tokens, prev)
1701
+ costs.spentUsd =
1702
+ Math.round(Object.values(costs.byTask).reduce((a: number, b: any) => a + (Number(b) || 0), 0) * 1e4) / 1e4
1703
+ costs.updatedAt = now
1704
+ writeJson(file, costs)
1705
+ writeSnapshots(snapshotsFile, snaps)
1706
+ source = `opencode session ${callSession}`
1707
+ } else if (typeof input?.addUsd === "number" && Number.isFinite(input.addUsd)) {
1708
+ if (input.addUsd < 0) return { content: "Error: addUsd must be non-negative" }
1709
+ const bucket = input.taskId ? clean(input.taskId, 64) : "_unattributed"
1710
+ addToBucket(bucket, input.addUsd)
1711
+ costs.spentUsd =
1712
+ Math.round(Object.values(costs.byTask).reduce((a: number, b: any) => a + (Number(b) || 0), 0) * 1e4) / 1e4
1713
+ costs.updatedAt = new Date().toISOString()
1714
+ writeJson(file, costs)
1715
+ source = "manual (client unavailable)"
1716
+ } else {
1717
+ source = "manual (client unavailable)"
1718
+ }
1719
+ } else if (typeof input?.addUsd === "number" && Number.isFinite(input.addUsd)) {
1720
+ if (input.addUsd < 0) return { content: "Error: addUsd must be non-negative" }
1721
+ const bucket = input.taskId ? clean(input.taskId, 64) : "_unattributed"
1722
+ addToBucket(bucket, input.addUsd)
1723
+ costs.spentUsd =
1724
+ Math.round(Object.values(costs.byTask).reduce((a: number, b: any) => a + (Number(b) || 0), 0) * 1e4) / 1e4
1725
+ costs.updatedAt = new Date().toISOString()
1726
+ writeJson(file, costs)
1727
+ source = "manual (client unavailable)"
1728
+ } else {
1729
+ source = "manual (client unavailable)"
1730
+ }
1731
+
1732
+ const pct = budget ? Math.floor((costs.spentUsd / budget) * 100) : 0
1733
+ const warn = pct >= 80 ? `\n⚠ ${pct}% of budget used — halt non-essential workers and ask the user.` : ""
1734
+ // SEC-3: the bucket key is echoed to the caller, so it is sanitised too.
1735
+ const taskBreakdown = Object.entries(costs.byTask).map(([k, v]) => ` ${clean(k, 64)}: $${v}`).join("\n")
1736
+ return {
1737
+ content: `Budget: $${budget} · spent: $${costs.spentUsd} (${pct}%)${warn}${taskBreakdown ? `\nPer-task:\n${taskBreakdown}` : ""}\n(source: ${source})`,
1738
+ shouldHalt: pct >= 80,
1739
+ pct,
1740
+ }
1741
+ })
1742
+ },
1743
+ })
1744
+
1745
+ editor.add({
1746
+ name: "budget",
1747
+ description:
1748
+ "Preflight the run budget BEFORE teamwork_plan. Detects whether the session uses opencode/ (managed) models and whether the opencode_console MCP is connected. When both hold, tells the caller to fetch credits via opencode_console_get_usage and pass a full/partial budgetUsd to teamwork_plan. Otherwise, use the default budget.",
1749
+ input: { type: "object", properties: {}, additionalProperties: false },
1750
+ execute: async (_input: any, context: any) => {
1751
+ const consoleOnline = await isConsoleMcpConnected(ctx)
1752
+ const opencodeModel = await usesOpencodeModel(ctx, context?.sessionID)
1753
+ if (consoleOnline && opencodeModel) {
1754
+ return {
1755
+ content: [
1756
+ "Budget preflight: opencode/ (managed) models detected AND opencode_console is connected.",
1757
+ "1. Call opencode_console_get_usage to read your budgets.",
1758
+ "2. remaining = min over budgets of (limitDollars - spentDollars).",
1759
+ "3. ASK THE USER: use the FULL remaining budget, or PARTIAL (half)?",
1760
+ "4. Pass the chosen budgetUsd to teamwork_plan.",
1761
+ "budgetSource: credits",
1762
+ ].join("\n"),
1763
+ applyCredits: true,
1764
+ }
1765
+ }
1766
+ return {
1767
+ content: `Budget preflight: console-credit budgeting does not apply (consoleOnline=${consoleOnline}, opencodeModel=${opencodeModel}). Use the default budget.`,
1768
+ applyCredits: false,
1769
+ }
1770
+ },
1771
+ })
1772
+
1773
+ editor.add({
1774
+ name: "pitfall",
1775
+ description: "Append an answer-agnostic failure mode to the run's pitfall registry.",
1776
+ input: {
1777
+ type: "object",
1778
+ properties: { sessionId: { type: "string" }, round: { type: "number" }, taskId: { type: "string" }, pitfall: { type: "string" } },
1779
+ required: ["pitfall"],
1780
+ additionalProperties: false,
1781
+ },
1782
+ execute: async (input: any) => {
1783
+ const resolved = resolveRun(root, input?.sessionId)
1784
+ if (resolved.error) return { content: resolved.error }
1785
+ const run = resolved.run as string
1786
+ const file = join(run, "pitfalls.md")
1787
+ refuseSymlink(file)
1788
+ const line = `- [round ${Number(input.round) || "?"}] ${clean(input.pitfall, 200)}${input.taskId ? ` — seen in ${clean(input.taskId, 64)}` : ""}\n`
1789
+ appendFileSync(file, line)
1790
+ return { content: `Logged pitfall: ${line.trim()}` }
1791
+ },
1792
+ })
1793
+
1794
+ editor.add({
1795
+ name: "next",
1796
+ description:
1797
+ "Determine the next actionable tasks in the DAG based on dependencies and current lifecycle states. Returns tasks ready for worker dispatch, tasks ready for verifier dispatch, in-progress tasks, or signals completion/deadlock.",
1798
+ input: {
1799
+ type: "object",
1800
+ properties: {
1801
+ sessionId: { type: "string", description: "Teamwork session id (defaults to active run)." },
1802
+ allowUnstamped: {
1803
+ type: "boolean",
1804
+ description:
1805
+ "Legacy migration escape hatch (default false). When true, a PASS verify/final.json without teamwork_final_verify provenance is accepted for completion and the bypass is recorded as a final_verification_bypass event. Do not use for new runs.",
1806
+ },
1807
+ },
1808
+ additionalProperties: false,
1809
+ },
1810
+ execute: async (input: any, context: any) => {
1811
+ const resolved = resolveRun(root, input?.sessionId)
1812
+ if (resolved.error) return { content: resolved.error }
1813
+ const run = resolved.run as string
1814
+
1815
+ const plan = readJson<any>(join(run, "plan.dag.json"), undefined)
1816
+ const state = readJson<any>(join(run, "state.json"), undefined)
1817
+ if (!plan || !Array.isArray(plan.tasks)) {
1818
+ return { content: `No valid plan.dag.json found for run ${basename(run)}.` }
1819
+ }
1820
+ if (!state || typeof state.tasks !== "object") {
1821
+ return { content: `No valid state.json found for run ${basename(run)}.` }
1822
+ }
1823
+
1824
+ const taskDefs = new Map<string, any>(plan.tasks.map((t: any) => [t.id, t]))
1825
+ const taskStates = nullMap<any>(state.tasks)
1826
+
1827
+ const isPassed = (id: string) => {
1828
+ const s = taskStates[id]?.status
1829
+ return s === "verified_pass" || s === "pass"
1830
+ }
1831
+
1832
+ const isBlocked = (id: string) => {
1833
+ const s = taskStates[id]?.status
1834
+ const r = Number(taskStates[id]?.round) || 0
1835
+ const maxR = Number(taskDefs.get(id)?.maxRounds) || 4
1836
+ return s === "blocked" || (s === "verified_fail" && r >= maxR) || (s === "fail" && r >= maxR)
1837
+ }
1838
+
1839
+ const readyForWorker: any[] = []
1840
+ const readyForVerifier: any[] = []
1841
+ const inProgress: any[] = []
1842
+ const blockedTasks: any[] = []
1843
+ const passedTasks: any[] = []
1844
+
1845
+ for (const [id, def] of taskDefs.entries()) {
1846
+ const st = taskStates[id] || { status: "pending", round: 0 }
1847
+ const status = st.status || "pending"
1848
+ const round = Number(st.round) || 0
1849
+ const maxRounds = Number(def.maxRounds) || 4
1850
+ const deps = Array.isArray(def.dependsOn) ? def.dependsOn : []
1851
+
1852
+ if (isPassed(id)) {
1853
+ passedTasks.push({ id, status, round })
1854
+ continue
1855
+ }
1856
+
1857
+ if (isBlocked(id)) {
1858
+ blockedTasks.push({ id, status, round, reason: "Max rounds exceeded or explicitly blocked" })
1859
+ continue
1860
+ }
1861
+
1862
+ const blockedDep = deps.find(isBlocked)
1863
+ if (blockedDep) {
1864
+ blockedTasks.push({ id, status: "blocked", reason: `Dependency ${blockedDep} failed/blocked` })
1865
+ continue
1866
+ }
1867
+
1868
+ const allDepsPassed = deps.every(isPassed)
1869
+
1870
+ if (status === "worker_done") {
1871
+ readyForVerifier.push({
1872
+ id,
1873
+ agent: "team/verifier",
1874
+ branch: st.branch || `teamwork/${basename(run)}-${id}`,
1875
+ round,
1876
+ summary: st.summary,
1877
+ })
1878
+ } else if (status === "worker_active" || status === "verifier_active" || status === "running") {
1879
+ inProgress.push({
1880
+ id,
1881
+ status,
1882
+ round,
1883
+ branch: st.branch,
1884
+ })
1885
+ } else if (allDepsPassed && (status === "pending" || ((status === "verified_fail" || status === "fail") && round < maxRounds))) {
1886
+ const pitfalls = readPitfalls(run, id)
1887
+ // 3.6: surface the cumulative unresolved issue set, not just the latest
1888
+ // round. Oldest first, one `R<n>: <text>` line per entry, capped.
1889
+ const log = Array.isArray(st.feedbackLog) ? st.feedbackLog : []
1890
+ const unresolved = log
1891
+ .filter((e: any) => e && typeof e === "object" && e.resolved !== true)
1892
+ .map((e: any) => `R${Number(e.round) || 0}: ${clean(e.text, 500)}`)
1893
+ readyForWorker.push({
1894
+ id,
1895
+ agent: def.agent || "team/worker",
1896
+ round: (status === "verified_fail" || status === "fail") ? round + 1 : (round || 1),
1897
+ maxRounds,
1898
+ requirements: def.requirements || [],
1899
+ dependsOn: deps,
1900
+ branch: st.branch || `teamwork/${basename(run)}-${id}`,
1901
+ // A legacy run has no ledger: keep the single latest `feedback` field.
1902
+ feedback: log.length ? cleanBlock(unresolved.join("\n"), 2000) : st.feedback,
1903
+ avoidPitfalls: pitfalls,
1904
+ })
1905
+ }
1906
+ }
1907
+
1908
+ if (passedTasks.length === taskDefs.size) {
1909
+ const auditFile = join(run, "verify", "security-audit.json")
1910
+ const audit = existsSync(auditFile) ? readJson<any>(auditFile, undefined) : undefined
1911
+ // The final gate reports the run's integrity mode, read from the same
1912
+ // artifact the auditor uses (legacy runs default to development). It is
1913
+ // disclosed, never enforced here: enforcement stays with the auditor.
1914
+ const integrity = readIntegrityMode(run)
1915
+ const integrityModeNote =
1916
+ integrity.source === "artifact"
1917
+ ? `Integrity mode: ${integrity.mode} (from ORIGINAL_REQUEST.md).`
1918
+ : `Integrity mode: ${integrity.mode} (default; no ORIGINAL_REQUEST.md for this run).`
1919
+
1920
+ if (!audit || audit.status !== "PASS") {
1921
+ const auditFailed = audit && audit.status === "FAIL"
1922
+ if (state.phase !== "SECURITY_AUDIT" && !auditFailed) {
1923
+ state.phase = "SECURITY_AUDIT"
1924
+ writeJson(join(run, "state.json"), state)
1925
+ }
1926
+
1927
+ if (auditFailed) {
1928
+ const crit = Number(audit?.severityCounts?.critical) || 0
1929
+ const high = Number(audit?.severityCounts?.high) || 0
1930
+ return {
1931
+ content: `BLOCKED_BY_SECURITY: All tasks passed functional verification, but security audit FAILED with ${crit} Critical and ${high} High findings.\nFix findings before final merge.\nReport: ${auditFile}`,
1932
+ status: "BLOCKED_BY_SECURITY",
1933
+ auditReport: auditFile,
1934
+ passedCount: passedTasks.length,
1935
+ }
1936
+ }
1937
+
1938
+ return {
1939
+ content: `READY_FOR_SECURITY_AUDIT: All ${taskDefs.size} tasks passed functional verification and are merged into base.\nMandatory Security Gate: Dispatch team/security-auditor on sentinel worktree before final merge.\nRun teamwork_security_audit tool when audit completes.`,
1940
+ status: "READY_FOR_SECURITY_AUDIT",
1941
+ agent: "team/security-auditor",
1942
+ passedCount: passedTasks.length,
1943
+ }
1944
+ }
1945
+
1946
+ // "Done" needs an independent final verdict, not just per-task PASSes.
1947
+ // Missing, unreadable, or malformed reports are NOT done. A PASS is
1948
+ // only sufficient when `teamwork_final_verify` stamped it; an
1949
+ // unstamped (hand-written or legacy) report needs the explicit,
1950
+ // recorded `allowUnstamped` bypass.
1951
+ const finalFile = join(run, "verify", "final.json")
1952
+ const finalReport = existsSync(finalFile) ? readJson<any>(finalFile, undefined) : undefined
1953
+
1954
+ if (!finalReport || typeof finalReport !== "object" || typeof finalReport.status !== "string") {
1955
+ if (state.phase !== "FINAL_VERIFICATION") {
1956
+ state.phase = "FINAL_VERIFICATION"
1957
+ writeJson(join(run, "state.json"), state)
1958
+ }
1959
+ return {
1960
+ content: `READY_FOR_FINAL_VERIFICATION: All ${taskDefs.size} tasks passed verification and security audit PASSED, but there is no usable final verification report at ${finalFile} (missing, unreadable, or malformed).\nRun an independent final verification of the whole run and write verify/final.json with "status": "PASS" or "FAIL" before merging.\n${integrityModeNote}`,
1961
+ status: "READY_FOR_FINAL_VERIFICATION",
1962
+ integrityMode: integrity.mode,
1963
+ finalReport: finalFile,
1964
+ passedCount: passedTasks.length,
1965
+ }
1966
+ }
1967
+
1968
+ if (finalReport.status !== "PASS") {
1969
+ return {
1970
+ content: `BLOCKED_BY_FINAL_VERIFICATION: Final verification did not pass the run (status ${clean(finalReport.status, 32)}).\nAddress the findings in ${finalFile} and re-run the final verification; merge stays blocked until verify/final.json reports PASS.\n${integrityModeNote}`,
1971
+ status: "BLOCKED_BY_FINAL_VERIFICATION",
1972
+ integrityMode: integrity.mode,
1973
+ finalReport: finalFile,
1974
+ passedCount: passedTasks.length,
1975
+ }
1976
+ }
1977
+
1978
+ const stamped = isStampedFinalReport(finalReport)
1979
+ const allowUnstamped = input?.allowUnstamped === true
1980
+
1981
+ if (!stamped && !allowUnstamped) {
1982
+ if (state.phase !== "FINAL_VERIFICATION") {
1983
+ state.phase = "FINAL_VERIFICATION"
1984
+ writeJson(join(run, "state.json"), state)
1985
+ }
1986
+ return {
1987
+ content: `FINAL_VERIFICATION_UNVERIFIED: verify/final.json reports PASS but is not stamped by teamwork_final_verify (no usable generatedBy.session, generatedAt, or evidence), so it cannot complete the run.\nRun teamwork_final_verify to compute the verdict from the per-task reports and the security audit and stamp provenance. To accept this hand-written or legacy report instead, re-call teamwork_next with allowUnstamped: true; that is recorded as a bypass event.\n${integrityModeNote}`,
1988
+ status: "FINAL_VERIFICATION_UNVERIFIED",
1989
+ finalReport: finalFile,
1990
+ passedCount: passedTasks.length,
1991
+ integrityMode: integrity.mode,
1992
+ }
1993
+ }
1994
+
1995
+ if (state.phase !== "MERGE" && state.phase !== "DONE") {
1996
+ state.phase = "MERGE"
1997
+ writeJson(join(run, "state.json"), state)
1998
+ }
1999
+
2000
+ if (!stamped) {
2001
+ // Explicit legacy escape hatch: accept, but record who did it and why.
2002
+ const callSession = typeof context?.sessionID === "string" ? context.sessionID : undefined
2003
+ const caller = await deriveCallerAgent(ctx, run, callSession)
2004
+ await appendEvent(run, {
2005
+ event: "final_verification_bypass",
2006
+ sessionId: basename(run),
2007
+ taskId: null,
2008
+ to: "ALL_PASSED",
2009
+ round: 0,
2010
+ agent: caller?.agent ?? null,
2011
+ agentSource: caller?.agent ? "session" : undefined,
2012
+ phase: state.phase ?? null,
2013
+ note: "unstamped verify/final.json accepted via allowUnstamped; verdict was not produced by teamwork_final_verify",
2014
+ })
2015
+ return {
2016
+ content: `ALL_TASKS_PASSED: All ${taskDefs.size} tasks have passed verification, security audit PASSED, and verify/final.json reports PASS — but that verdict was not produced by teamwork_final_verify (unstamped hand-written or legacy report). Accepted via allowUnstamped: true; the bypass was recorded in events.jsonl. Ready to merge Sentinel base worktree to user branch and present final artifact.\n${integrityModeNote}`,
2017
+ status: "ALL_PASSED",
2018
+ integrityMode: integrity.mode,
2019
+ passedCount: passedTasks.length,
2020
+ securityAuditPassed: true,
2021
+ finalReport: finalFile,
2022
+ stamped: false,
2023
+ unstampedBypass: true,
2024
+ }
2025
+ }
2026
+
2027
+ return {
2028
+ content: `ALL_TASKS_PASSED: All ${taskDefs.size} tasks have passed verification, security audit PASSED, and final verification PASSED. Ready to merge Sentinel base worktree to user branch and present final artifact.\n${integrityModeNote}`,
2029
+ status: "ALL_PASSED",
2030
+ integrityMode: integrity.mode,
2031
+ passedCount: passedTasks.length,
2032
+ securityAuditPassed: true,
2033
+ finalReport: finalFile,
2034
+ stamped: true,
2035
+ }
2036
+ }
2037
+
2038
+ if (!readyForWorker.length && !readyForVerifier.length && !inProgress.length) {
2039
+ return {
2040
+ content: `DEADLOCK_OR_BLOCKED: No tasks can proceed.\nBlocked tasks (${blockedTasks.length}):\n` +
2041
+ blockedTasks.map((t) => ` - ${t.id}: ${t.reason}`).join("\n"),
2042
+ status: "DEADLOCK",
2043
+ blocked: blockedTasks,
2044
+ }
2045
+ }
2046
+
2047
+ const lines = [`DAG Status for run ${basename(run)}:`]
2048
+ if (readyForWorker.length) {
2049
+ lines.push(`\n▶ READY FOR WORKER (${readyForWorker.length}): Dispatch worker subagent for each in parallel:`)
2050
+ for (const t of readyForWorker) {
2051
+ lines.push(` - Task: ${t.id} (Agent: ${t.agent}, Round: ${t.round}/${t.maxRounds})`)
2052
+ lines.push(` Branch: ${t.branch}`)
2053
+ if (t.feedback) lines.push(` Verifier Feedback: ${clean(t.feedback, 120)}`)
2054
+ if (t.avoidPitfalls?.length) {
2055
+ lines.push(` ⚠ Avoid Known Pitfalls: ${t.avoidPitfalls.slice(0, 3).map((p: string) => clean(p, 80)).join("; ")}`)
2056
+ }
2057
+ }
2058
+ }
2059
+ if (readyForVerifier.length) {
2060
+ lines.push(`\n▶ READY FOR VERIFIER (${readyForVerifier.length}): Dispatch verifier subagent against worker branch:`)
2061
+ for (const t of readyForVerifier) {
2062
+ lines.push(` - Task: ${t.id} (Verifier: ${t.agent}, Branch: ${t.branch})`)
2063
+ }
2064
+ }
2065
+ if (inProgress.length) {
2066
+ lines.push(`\n⏳ IN PROGRESS (${inProgress.length}):`)
2067
+ for (const t of inProgress) {
2068
+ lines.push(` - ${t.id}: ${t.status} (round ${t.round})`)
2069
+ }
2070
+ }
2071
+ lines.push(`\nProgress: ${passedTasks.length}/${taskDefs.size} passed, ${blockedTasks.length} blocked.`)
2072
+
2073
+ return {
2074
+ content: lines.join("\n"),
2075
+ readyForWorker,
2076
+ readyForVerifier,
2077
+ inProgress,
2078
+ passedCount: passedTasks.length,
2079
+ totalTasks: taskDefs.size,
2080
+ }
2081
+ },
2082
+ })
2083
+
2084
+ editor.add({
2085
+ name: "task_update",
2086
+ description:
2087
+ "Update a task's lifecycle status, round, branch, and verification report in state.json. Lifecycle: pending -> worker_active -> worker_done -> verifier_active -> verified_pass | verified_fail | blocked.",
2088
+ input: {
2089
+ type: "object",
2090
+ properties: {
2091
+ sessionId: { type: "string" },
2092
+ taskId: { type: "string", description: "The task ID defined in plan.dag.json." },
2093
+ status: {
2094
+ type: "string",
2095
+ description: "pending | worker_active | worker_done | verifier_active | verified_pass | verified_fail | blocked",
2096
+ },
2097
+ agent: {
2098
+ type: "string",
2099
+ description:
2100
+ "Optional. The actor that performed this transition (e.g. team/worker or team/verifier). Recorded in events.jsonl; when omitted the calling session's agent, then the plan-declared agent, is recorded.",
2101
+ },
2102
+ round: { type: "number" },
2103
+ branch: { type: "string" },
2104
+ worktree: { type: "string" },
2105
+ summary: { type: "string", description: "Short summary of what worker implemented." },
2106
+ feedback: { type: "string", description: "Feedback from verifier for the next worker round." },
2107
+ verification: {
2108
+ type: "object",
2109
+ properties: {
2110
+ status: { type: "string", description: "PASS | FAIL" },
2111
+ passedChecks: { type: "number" },
2112
+ totalChecks: { type: "number" },
2113
+ fatalFindings: { type: "array", items: { type: "string" } },
2114
+ },
2115
+ },
2116
+ },
2117
+ required: ["taskId", "status"],
2118
+ additionalProperties: false,
2119
+ },
2120
+ execute: async (input: any, context: any) => {
2121
+ const resolved = resolveRun(root, input?.sessionId)
2122
+ if (resolved.error) return { content: resolved.error }
2123
+ const run = resolved.run as string
2124
+ const stateFile = join(run, "state.json")
2125
+ const planFile = join(run, "plan.dag.json")
2126
+ const callSession = typeof context?.sessionID === "string" ? context.sessionID : undefined
2127
+
2128
+ const taskId = clean(input.taskId, 64)
2129
+ if (!taskId) return { content: "Error: taskId is required" }
2130
+
2131
+ return await withFileLock(stateFile, async () => {
2132
+ const state = readJson<any>(stateFile, undefined)
2133
+ if (!state || typeof state.tasks !== "object") {
2134
+ return { content: `Error: No state.json found for run ${basename(run)}.` }
2135
+ }
2136
+ // SEC-1: null-prototype task map; existence is an OWN-property check, never truthiness.
2137
+ state.tasks = nullMap(state.tasks)
2138
+ const plan = readJson<any>(planFile, undefined)
2139
+ const def = Array.isArray(plan?.tasks) ? plan.tasks.find((t: any) => t.id === taskId) : undefined
2140
+ if (!def && !Object.prototype.hasOwnProperty.call(state.tasks, taskId)) {
2141
+ return { content: `Error: Task "${taskId}" not found in plan or state.` }
2142
+ }
2143
+
2144
+ let status = clean(input.status, 32)
2145
+ if (status === "pass") status = "verified_pass"
2146
+ else if (status === "fail") status = "verified_fail"
2147
+ else if (status === "running") status = "worker_active"
2148
+
2149
+ const VALID_STATUSES = new Set([
2150
+ "pending",
2151
+ "worker_active",
2152
+ "worker_done",
2153
+ "verifier_active",
2154
+ "verified_pass",
2155
+ "verified_fail",
2156
+ "blocked",
2157
+ ])
2158
+ // Deterministic transition graph. `blocked` is reachable from every state
2159
+ // so escalation can never deadlock; a same-status re-write is always allowed.
2160
+ const ALLOWED_NEXT: Record<string, string[]> = {
2161
+ pending: ["worker_active", "blocked"],
2162
+ worker_active: ["worker_done", "blocked"],
2163
+ worker_done: ["verifier_active", "blocked"],
2164
+ verifier_active: ["verified_pass", "verified_fail", "blocked"],
2165
+ verified_fail: ["worker_active", "blocked"],
2166
+ verified_pass: ["blocked"],
2167
+ blocked: ["worker_active", "pending"],
2168
+ }
2169
+ if (!VALID_STATUSES.has(status)) {
2170
+ return { content: `Error: Invalid status "${status}". Allowed: ${Array.from(VALID_STATUSES).join(", ")}` }
2171
+ }
2172
+
2173
+ const current = state.tasks[taskId] || { status: "pending", round: 0 }
2174
+ const fromStatus = typeof current.status === "string" ? current.status : "pending"
2175
+ const maxRounds = Number(def?.maxRounds) || 4
2176
+ let round = Number.isFinite(input.round) ? Number(input.round) : (Number(current.round) || 0)
2177
+
2178
+ if (status === "worker_active" && !Number.isFinite(input.round)) {
2179
+ round = Math.max(1, (Number(current.round) || 0) + (current.status === "verified_fail" ? 1 : 0))
2180
+ }
2181
+
2182
+ if ((status === "verified_fail" || status === "fail") && round >= maxRounds) {
2183
+ status = "blocked"
2184
+ }
2185
+
2186
+ // Legacy aliases in an existing state.json still resolve to the canonical
2187
+ // node; an unrecognised status is treated as `pending` (same fail-open
2188
+ // default the rest of the engine uses). The event log keeps the raw value.
2189
+ const canonicalFrom =
2190
+ fromStatus === "pass" ? "verified_pass"
2191
+ : fromStatus === "fail" ? "verified_fail"
2192
+ : fromStatus === "running" ? "worker_active"
2193
+ : VALID_STATUSES.has(fromStatus) ? fromStatus
2194
+ : "pending"
2195
+ const allowedNext = ALLOWED_NEXT[canonicalFrom] || []
2196
+ if (status !== canonicalFrom && !allowedNext.includes(status)) {
2197
+ return {
2198
+ content: `Error: Illegal transition for task "${taskId}": ${fromStatus} -> ${status}. Allowed next statuses from ${canonicalFrom}: ${allowedNext.join(", ")} (or ${canonicalFrom} again).`,
2199
+ }
2200
+ }
2201
+
2202
+ // `verified_pass` needs evidence: either an inline PASS verdict or an
2203
+ // on-disk verifier report for THIS task. `verified_fail` needs none.
2204
+ if (status === "verified_pass") {
2205
+ const inlinePass = input.verification?.status === "PASS"
2206
+ const reportFile = isSafeTaskId(taskId) ? join(run, "verify", `report-${taskId}.json`) : undefined
2207
+ const report = reportFile && existsSync(reportFile) ? readJson<any>(reportFile, undefined) : undefined
2208
+ if (!inlinePass && report?.status !== "PASS") {
2209
+ return {
2210
+ content: `Error: Refusing verified_pass for task "${taskId}" without PASS evidence. Provide input.verification.status = "PASS", or write a verifier report at ${reportFile ?? "verify/report-<taskId>.json"} with "status": "PASS".`,
2211
+ }
2212
+ }
2213
+ }
2214
+
2215
+ // 3.6: cumulative feedback ledger. Every non-empty feedback is appended
2216
+ // (sanitised) instead of replacing the previous round; verified_pass
2217
+ // resolves all entries in the same write, verified_fail leaves them open.
2218
+ // The array is capped at 20 entries, oldest dropped first.
2219
+ const priorLog: any[] = Array.isArray(current.feedbackLog)
2220
+ ? current.feedbackLog
2221
+ .filter((e: any) => e && typeof e === "object")
2222
+ .map((e: any) => ({
2223
+ round: Number(e.round) || 0,
2224
+ at: clean(e.at, 32),
2225
+ text: clean(e.text, 500),
2226
+ resolved: e.resolved === true,
2227
+ }))
2228
+ : []
2229
+ const feedbackText = input.feedback ? clean(input.feedback, 500) : ""
2230
+ if (feedbackText) {
2231
+ priorLog.push({ round, at: new Date().toISOString(), text: feedbackText, resolved: false })
2232
+ }
2233
+ if (status === "verified_pass") {
2234
+ for (const e of priorLog) e.resolved = true
2235
+ }
2236
+ const feedbackLog = priorLog.slice(-20)
2237
+
2238
+ state.tasks[taskId] = {
2239
+ ...current,
2240
+ status,
2241
+ round,
2242
+ ...(input.branch ? { branch: clean(input.branch, 120) } : {}),
2243
+ ...(input.worktree ? { worktree: clean(input.worktree, 200) } : {}),
2244
+ ...(input.summary ? { summary: clean(input.summary, 300) } : {}),
2245
+ ...(feedbackText ? { feedback: feedbackText } : {}),
2246
+ // Only tasks that have ledger entries gain the field: the state.json
2247
+ // shape of a task that never failed stays exactly as before.
2248
+ ...(feedbackLog.length || Array.isArray(current.feedbackLog) ? { feedbackLog } : {}),
2249
+ ...(input.verification ? { verification: input.verification } : {}),
2250
+ updatedAt: new Date().toISOString(),
2251
+ }
2252
+
2253
+ const allTasks = Object.values(state.tasks) as any[]
2254
+ const allPassed = allTasks.every((t) => t.status === "verified_pass")
2255
+ const anyActive = allTasks.some((t) => t.status === "worker_active" || t.status === "verifier_active")
2256
+ if (allPassed) {
2257
+ const auditFile = join(run, "verify", "security-audit.json")
2258
+ const audit = existsSync(auditFile) ? readJson<any>(auditFile, undefined) : undefined
2259
+ state.phase = audit?.status === "PASS" ? "MERGE" : "SECURITY_AUDIT"
2260
+ } else if (!anyActive && allTasks.some((t) => t.status === "blocked")) {
2261
+ state.phase = "PRESENT_PARTIAL"
2262
+ }
2263
+
2264
+ state.updatedAt = new Date().toISOString()
2265
+ writeJson(stateFile, state)
2266
+
2267
+ // Actor precedence (best-effort, fail-open): explicit input.agent, then the
2268
+ // calling session's agent, then the plan-declared agent. clean() runs in appendEvent too.
2269
+ const explicitAgent = typeof input.agent === "string" ? clean(input.agent, 64).trim() : ""
2270
+ const caller = explicitAgent ? undefined : await deriveCallerAgent(ctx, run, callSession)
2271
+ const planAgent = def?.agent ? clean(def.agent, 64) : undefined
2272
+ const recordedAgent = explicitAgent || caller?.agent || planAgent || null
2273
+ const agentSource = explicitAgent ? "explicit" : caller?.agent ? "session" : planAgent ? "plan" : undefined
2274
+
2275
+ // Log what actually landed in state.json (post-normalisation, post-coercion).
2276
+ await appendEvent(run, {
2277
+ event: "task_transition",
2278
+ sessionId: basename(run),
2279
+ taskId,
2280
+ from: fromStatus,
2281
+ to: status,
2282
+ round,
2283
+ agent: recordedAgent,
2284
+ agentSource,
2285
+ branch: input.branch ?? current.branch ?? null,
2286
+ worktree: input.worktree ?? current.worktree ?? null,
2287
+ phase: state.phase ?? null,
2288
+ })
2289
+
2290
+ return {
2291
+ // SEC-3: the branch is echoed to the caller, so it is sanitised like every other field.
2292
+ content: `Task ${taskId} updated: status=${status}, round=${round}${input.branch ? `, branch=${clean(input.branch, 120)}` : ""}${status === "blocked" ? " (BLOCKED: max rounds reached)" : ""}`,
2293
+ taskId,
2294
+ status,
2295
+ round,
2296
+ }
2297
+ })
2298
+ },
2299
+ })
2300
+
2301
+ editor.add({
2302
+ name: "security_audit",
2303
+ description:
2304
+ "Record the findings of team/security-auditor and enforce the pre-merge security gate. Writes verify/security-audit.json. If Critical or High findings exist, or the auditor reports an integrity finding forbidden at the run's mode, marks status as FAIL and blocks final merge.",
2305
+ input: {
2306
+ type: "object",
2307
+ properties: {
2308
+ sessionId: { type: "string" },
2309
+ status: { type: "string", description: "PASS | FAIL" },
2310
+ findings: {
2311
+ type: "array",
2312
+ items: {
2313
+ type: "object",
2314
+ properties: {
2315
+ id: { type: "string" },
2316
+ severity: { type: "string", description: "Critical | High | Medium | Low" },
2317
+ location: { type: "string" },
2318
+ description: { type: "string" },
2319
+ },
2320
+ required: ["severity", "description"],
2321
+ },
2322
+ },
2323
+ integrityFindings: {
2324
+ type: "array",
2325
+ description: `Optional. Up to ${INTEGRITY_FINDINGS_MAX} reported integrity-rule violations. An unknown rule refuses the call before anything is written.`,
2326
+ items: {
2327
+ type: "object",
2328
+ properties: {
2329
+ rule: { type: "string", description: INTEGRITY_RULE_IDS.join(" | ") },
2330
+ where: { type: "string" },
2331
+ why: { type: "string" },
2332
+ },
2333
+ required: ["rule"],
2334
+ additionalProperties: false,
2335
+ },
2336
+ },
2337
+ summary: { type: "string", description: "Summary of the security audit." },
2338
+ },
2339
+ required: ["status"],
2340
+ additionalProperties: false,
2341
+ },
2342
+ execute: async (input: any) => {
2343
+ const resolved = resolveRun(root, input?.sessionId)
2344
+ if (resolved.error) return { content: resolved.error }
2345
+ const run = resolved.run as string
2346
+ // The auditor works from the recorded request, not from its caller: the
2347
+ // mode is read from ORIGINAL_REQUEST.md (legacy runs default to development).
2348
+ const integrity = readIntegrityMode(run)
2349
+
2350
+ // Sanitise and validate the reported integrity findings BEFORE anything
2351
+ // is written. An unknown rule id is refused outright (like a topology
2352
+ // typo), listing the accepted ids.
2353
+ const integrityFindings = (Array.isArray(input.integrityFindings) ? input.integrityFindings : [])
2354
+ .slice(0, INTEGRITY_FINDINGS_MAX)
2355
+ .map((f: any) => ({
2356
+ rule: clean(f?.rule, 64).trim(),
2357
+ where: clean(f?.where, 200),
2358
+ why: clean(f?.why, 500),
2359
+ }))
2360
+ const unknownRule = integrityFindings.find(
2361
+ (f: { rule: string }) => !Object.prototype.hasOwnProperty.call(INTEGRITY_RULES, f.rule),
2362
+ )
2363
+ if (unknownRule) {
2364
+ return {
2365
+ content: `refused: unknown integrity rule "${clean(unknownRule.rule, 64)}" (accepted: ${INTEGRITY_RULE_IDS.join(", ")}); nothing was written`,
2366
+ }
2367
+ }
2368
+
2369
+ const integrityViolations = integrityFindings
2370
+ .filter((f: { rule: string }) =>
2371
+ isIntegrityRuleForbidden(f.rule as IntegrityRule, integrity.mode),
2372
+ )
2373
+ .map((f: { rule: string; where: string; why: string }) => ({
2374
+ ...f,
2375
+ forbiddenFrom: INTEGRITY_RULES[f.rule as IntegrityRule].forbiddenFrom,
2376
+ }))
2377
+ const violationRules = [...new Set(integrityViolations.map((v) => v.rule))]
2378
+
2379
+ const verifyDir = join(run, "verify")
2380
+ mkdirSync(verifyDir, { recursive: true })
2381
+ const auditFile = join(verifyDir, "security-audit.json")
2382
+ const integrityModeNote =
2383
+ integrity.source === "artifact"
2384
+ ? `Integrity mode: ${integrity.mode} (from ORIGINAL_REQUEST.md).`
2385
+ : `Integrity mode: ${integrity.mode} (default applied; no ORIGINAL_REQUEST.md for this run).`
2386
+
2387
+ const findings = Array.isArray(input.findings) ? input.findings : []
2388
+ const counts = {
2389
+ critical: findings.filter((f: any) => String(f.severity).toLowerCase() === "critical").length,
2390
+ high: findings.filter((f: any) => String(f.severity).toLowerCase() === "high").length,
2391
+ medium: findings.filter((f: any) => String(f.severity).toLowerCase() === "medium").length,
2392
+ low: findings.filter((f: any) => String(f.severity).toLowerCase() === "low").length,
2393
+ }
2394
+
2395
+ let status = clean(input.status, 16).toUpperCase()
2396
+ // Severity forcing and integrity forcing are independent; either FAILs.
2397
+ if (counts.critical > 0 || counts.high > 0) {
2398
+ status = "FAIL"
2399
+ }
2400
+ if (integrityViolations.length > 0) {
2401
+ status = "FAIL"
2402
+ }
2403
+
2404
+ const report = {
2405
+ sessionId: basename(run),
2406
+ integrityMode: integrity.mode,
2407
+ status,
2408
+ timestamp: new Date().toISOString(),
2409
+ severityCounts: counts,
2410
+ summary: input.summary ? clean(input.summary, 500) : "",
2411
+ findings: findings.map((f: any) => ({
2412
+ id: clean(f.id || "", 32),
2413
+ severity: clean(f.severity, 16),
2414
+ location: clean(f.location || "", 120),
2415
+ description: clean(f.description, 300),
2416
+ })),
2417
+ integrityFindings,
2418
+ integrityViolations,
2419
+ }
2420
+ writeJson(auditFile, report)
2421
+
2422
+ const stateFile = join(run, "state.json")
2423
+ const state = readJson<any>(stateFile, undefined)
2424
+ if (state) {
2425
+ if (status === "PASS") {
2426
+ state.phase = "MERGE"
2427
+ } else {
2428
+ // Append critical/high findings to pitfalls so they become known
2429
+ for (const f of findings) {
2430
+ if (["critical", "high"].includes(String(f.severity).toLowerCase())) {
2431
+ const line = `- [security] ${clean(f.severity, 16).toUpperCase()}: ${clean(f.description, 160)}${f.location ? ` at ${clean(f.location, 64)}` : ""}\n`
2432
+ appendFileSync(join(run, "pitfalls.md"), line)
2433
+ }
2434
+ }
2435
+ }
2436
+ state.updatedAt = new Date().toISOString()
2437
+ writeJson(stateFile, state)
2438
+ }
2439
+
2440
+ await appendEvent(run, {
2441
+ event: "security_audit",
2442
+ sessionId: basename(run),
2443
+ to: status,
2444
+ phase: state?.phase ?? null,
2445
+ })
2446
+
2447
+ if (status === "FAIL") {
2448
+ const violationNote =
2449
+ integrityViolations.length > 0
2450
+ ? `\nIntegrity violation(s) at mode ${integrity.mode}: ${violationRules.join(", ")}.`
2451
+ : ""
2452
+ return {
2453
+ content: `SECURITY AUDIT FAILED: ${counts.critical} Critical, ${counts.high} High, ${counts.medium} Medium findings.${violationNote} Final merge is BLOCKED until remediated.\n${integrityModeNote}\nReport saved to: ${auditFile}`,
2454
+ status: "FAIL",
2455
+ integrityMode: integrity.mode,
2456
+ reportPath: auditFile,
2457
+ }
2458
+ }
2459
+
2460
+ return {
2461
+ content: `SECURITY AUDIT PASSED: ${findings.length} findings (${counts.medium} Medium, ${counts.low} Low, 0 High/Critical); no forbidden integrity findings at mode ${integrity.mode}. Final merge is APPROVED.\n${integrityModeNote}\nReport saved to: ${auditFile}`,
2462
+ status: "PASS",
2463
+ integrityMode: integrity.mode,
2464
+ reportPath: auditFile,
2465
+ }
2466
+ },
2467
+ })
2468
+
2469
+ editor.add({
2470
+ name: "final_verify",
2471
+ description:
2472
+ "Compute and stamp the run's final verdict from artifacts. PASS requires every task to be verified_pass, every verify/report-<taskId>.json to be PASS, and verify/security-audit.json to be PASS. Writes verify/final.json atomically and appends a final_verification event. The verdict is computed from evidence and cannot be overridden by input.",
2473
+ input: {
2474
+ type: "object",
2475
+ properties: {
2476
+ sessionId: { type: "string" },
2477
+ summary: { type: "string", description: "Optional. The verifier's prose; recorded in verify/final.json (max 2000 chars)." },
2478
+ findings: {
2479
+ type: "array",
2480
+ description: "Optional. Up to 50 findings; recorded in verify/final.json.",
2481
+ items: {
2482
+ type: "object",
2483
+ properties: {
2484
+ where: { type: "string" },
2485
+ why: { type: "string" },
2486
+ fix: { type: "string" },
2487
+ },
2488
+ required: ["where", "why", "fix"],
2489
+ additionalProperties: false,
2490
+ },
2491
+ },
2492
+ failReason: { type: "string", description: "Optional. A reason to force FAIL; appended to the computed reasons." },
2493
+ },
2494
+ additionalProperties: false,
2495
+ },
2496
+ execute: async (input: any, context: any) => {
2497
+ const resolved = resolveRun(root, input?.sessionId)
2498
+ if (resolved.error) return { content: resolved.error }
2499
+ const run = resolved.run as string
2500
+ const finalFile = join(run, "verify", "final.json")
2501
+ const callSession = typeof context?.sessionID === "string" ? context.sessionID : undefined
2502
+
2503
+ return await withFileLock(finalFile, async () => {
2504
+ const state = readJson<any>(join(run, "state.json"), undefined)
2505
+ if (!state || typeof state.tasks !== "object") {
2506
+ return { content: `Error: No state.json found for run ${basename(run)}.` }
2507
+ }
2508
+ const plan = readJson<any>(join(run, "plan.dag.json"), undefined)
2509
+ // SEC-1: null-prototype map; ids are read as data, never used as paths
2510
+ // unless they pass isSafeTaskId.
2511
+ const taskStates = nullMap<any>(state.tasks)
2512
+ const planIds: string[] = Array.isArray(plan?.tasks)
2513
+ ? plan.tasks.map((t: any) => t?.id).filter((id: any) => typeof id === "string")
2514
+ : []
2515
+ const ids: string[] = []
2516
+ for (const id of [...planIds, ...Object.keys(taskStates)]) {
2517
+ if (!ids.includes(id)) ids.push(id)
2518
+ }
2519
+
2520
+ // Evidence comes from disk only; no input can supply or alter it.
2521
+ const tasks = ids.map((id) => {
2522
+ const safe = isSafeTaskId(id)
2523
+ const reportRel = safe ? `verify/report-${id}.json` : null
2524
+ const report = reportRel ? readJson<any>(join(run, reportRel), undefined) : undefined
2525
+ const rawStatus = taskStates[id]?.status
2526
+ return {
2527
+ id: clean(id, 64),
2528
+ status: typeof rawStatus === "string" ? clean(rawStatus, 32) : "pending",
2529
+ report: reportRel,
2530
+ reportStatus:
2531
+ report?.status === "PASS" ? "PASS" : report?.status === "FAIL" ? "FAIL" : "MISSING",
2532
+ }
2533
+ })
2534
+ const audit = readJson<any>(join(run, "verify", "security-audit.json"), undefined)
2535
+ const securityAudit = {
2536
+ path: "verify/security-audit.json",
2537
+ status: audit?.status === "PASS" ? "PASS" : audit?.status === "FAIL" ? "FAIL" : "MISSING",
2538
+ }
2539
+ const allTasksVerifiedPass = tasks.length > 0 && tasks.every((t) => t.status === "verified_pass")
2540
+
2541
+ const reasons: string[] = []
2542
+ if (tasks.length === 0) reasons.push("no tasks in plan or state")
2543
+ for (const t of tasks) {
2544
+ if (t.status !== "verified_pass") reasons.push(`task ${t.id}: state status ${t.status} (not verified_pass)`)
2545
+ if (t.reportStatus !== "PASS") reasons.push(`task ${t.id}: report ${t.reportStatus}`)
2546
+ }
2547
+ if (securityAudit.status !== "PASS") reasons.push(`security audit: ${securityAudit.status}`)
2548
+ // A supplied failReason can only make the verdict fail, never pass it.
2549
+ const failReason = typeof input?.failReason === "string" ? clean(input.failReason, 500).trim() : ""
2550
+ if (failReason) reasons.push(failReason)
2551
+
2552
+ const status = reasons.length === 0 ? "PASS" : "FAIL"
2553
+ // Bound both the artifact and the message; 100 conditions is already far
2554
+ // beyond a useful verdict.
2555
+ const cappedReasons = reasons.slice(0, 100)
2556
+ const integrity = readIntegrityMode(run)
2557
+ const caller = await deriveCallerAgent(ctx, run, callSession)
2558
+ const summary = typeof input?.summary === "string" ? clean(input.summary, 2000).trim() : ""
2559
+ const findings = Array.isArray(input?.findings)
2560
+ ? input.findings.slice(0, 50).map((f: any) => ({
2561
+ where: clean(f?.where, 200),
2562
+ why: clean(f?.why, 500),
2563
+ fix: clean(f?.fix, 500),
2564
+ }))
2565
+ : []
2566
+
2567
+ refuseSymlink(finalFile)
2568
+ writeJson(finalFile, {
2569
+ status,
2570
+ generatedBy: { agent: caller?.agent ?? null, session: callSession || basename(run) },
2571
+ generatedAt: new Date().toISOString(),
2572
+ integrityMode: integrity.mode,
2573
+ evidence: { tasks, securityAudit, allTasksVerifiedPass },
2574
+ reasons: cappedReasons,
2575
+ ...(summary ? { summary } : {}),
2576
+ ...(findings.length ? { findings } : {}),
2577
+ })
2578
+
2579
+ await appendEvent(run, {
2580
+ event: "final_verification",
2581
+ sessionId: basename(run),
2582
+ taskId: null,
2583
+ to: status,
2584
+ round: 0,
2585
+ agent: caller?.agent ?? null,
2586
+ agentSource: caller?.agent ? "session" : undefined,
2587
+ phase: state.phase ?? null,
2588
+ })
2589
+
2590
+ const integrityModeNote =
2591
+ integrity.source === "artifact"
2592
+ ? `Integrity mode: ${integrity.mode} (from ORIGINAL_REQUEST.md).`
2593
+ : `Integrity mode: ${integrity.mode} (default applied; no ORIGINAL_REQUEST.md for this run).`
2594
+ const evidenceLine = `Evidence: ${tasks.length} task(s), allTasksVerifiedPass=${allTasksVerifiedPass}, security audit ${securityAudit.status}.`
2595
+
2596
+ if (status === "FAIL") {
2597
+ return {
2598
+ content: `FINAL VERIFICATION FAILED: ${reasons.length} unmet condition(s). Final merge is BLOCKED.\nReasons:\n${cappedReasons.map((r) => ` - ${r}`).join("\n")}\n${evidenceLine}\n${integrityModeNote}\nArtifact: ${finalFile}`,
2599
+ status: "FAIL",
2600
+ finalReport: finalFile,
2601
+ integrityMode: integrity.mode,
2602
+ reasons: cappedReasons,
2603
+ }
2604
+ }
2605
+
2606
+ return {
2607
+ content: `FINAL VERIFICATION PASSED: every task is verified_pass, every task report is PASS, and the security audit is PASS.\n${evidenceLine}\n${integrityModeNote}\nArtifact: ${finalFile}`,
2608
+ status: "PASS",
2609
+ finalReport: finalFile,
2610
+ integrityMode: integrity.mode,
2611
+ }
2612
+ })
2613
+ },
2614
+ })
2615
+
2616
+ editor.add({
2617
+ name: "worktree",
2618
+ description:
2619
+ "Deterministic git worktree manager for Teamwork runs: setup, diff, merge, resolve, and cleanup. Prevents in-repo nesting and isolates worker branches.",
2620
+ input: {
2621
+ type: "object",
2622
+ properties: {
2623
+ sessionId: { type: "string" },
2624
+ action: {
2625
+ type: "string",
2626
+ description: "setup | diff | merge | resolve | cleanup",
2627
+ },
2628
+ role: {
2629
+ type: "string",
2630
+ description: "Role for setup action: sentinel | worker | verifier",
2631
+ },
2632
+ taskId: {
2633
+ type: "string",
2634
+ description: "Task ID (required for worker/verifier setup, diff, merge, and resolve)",
2635
+ },
2636
+ commitMessage: {
2637
+ type: "string",
2638
+ description: "Commit message for resolve action",
2639
+ },
2640
+ },
2641
+ required: ["action"],
2642
+ additionalProperties: false,
2643
+ },
2644
+ execute: async (input: any) => {
2645
+ const resolved = resolveRun(root, input?.sessionId)
2646
+ if (resolved.error) return { content: resolved.error }
2647
+ const run = resolved.run as string
2648
+ const runId = basename(run)
2649
+
2650
+ const action = clean(input.action, 16)
2651
+ // SEC-1: validate at the entry point, before any path or branch is built.
2652
+ // Raw value is checked (not clean()ed) so nothing is silently truncated.
2653
+ const rawTaskId = input.taskId ? String(input.taskId) : undefined
2654
+ if (rawTaskId !== undefined && !isSafeTaskId(rawTaskId)) {
2655
+ return { content: `refused: invalid task id "${clean(rawTaskId, 32)}" (must be a single segment matching ${TASK_ID})` }
2656
+ }
2657
+ const taskId = rawTaskId
2658
+
2659
+ const worktreesBase = process.env.TEAMWORK_WORKTREES_DIR
2660
+ ? process.env.TEAMWORK_WORKTREES_DIR
2661
+ : join(root, "..", ".teamwork-worktrees")
2662
+ const runWorktreesDir = join(worktreesBase, runId)
2663
+ const baseBranch = `teamwork/base-${runId}`
2664
+
2665
+ const execGit = (args: string[], cwd = root) => {
2666
+ try {
2667
+ return {
2668
+ stdout: execFileSync("git", args, { cwd, encoding: "utf8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"] }).trim(),
2669
+ code: 0,
2670
+ }
2671
+ } catch (e: any) {
2672
+ return {
2673
+ stdout: String(e.stdout ?? "").trim(),
2674
+ stderr: String(e.stderr ?? e.message ?? "").trim(),
2675
+ code: typeof e.status === "number" ? e.status : 1,
2676
+ }
2677
+ }
2678
+ }
2679
+
2680
+ const isGit = execGit(["rev-parse", "--is-inside-work-tree"])
2681
+ if (isGit.code !== 0) {
2682
+ return { content: "Skipped worktree operation: current directory is not a git repository." }
2683
+ }
2684
+
2685
+ if (action === "setup") {
2686
+ const role = clean(input.role || "worker", 16)
2687
+ let targetDir: string
2688
+ let branch: string
2689
+
2690
+ if (role === "sentinel") {
2691
+ targetDir = join(runWorktreesDir, "sentinel")
2692
+ branch = baseBranch
2693
+ // SEC-1: containment must hold before ANY mkdir / rmSync / worktree add.
2694
+ const escape = containmentError(runWorktreesDir, targetDir)
2695
+ if (escape) return { content: escape }
2696
+ const branchExists = execGit(["rev-parse", "--verify", branch]).code === 0
2697
+ mkdirSync(dirname(targetDir), { recursive: true })
2698
+ if (existsSync(targetDir)) {
2699
+ const check = execGit(["rev-parse", "--is-inside-work-tree"], targetDir)
2700
+ if (check.code !== 0) {
2701
+ // rmSync only after re-proving containment (defence in depth).
2702
+ if (!containmentError(runWorktreesDir, targetDir)) {
2703
+ try { rmSync(targetDir, { recursive: true, force: true }) } catch {}
2704
+ }
2705
+ execGit(["worktree", "prune"])
2706
+ }
2707
+ }
2708
+ if (!existsSync(targetDir)) {
2709
+ const res = branchExists
2710
+ ? execGit(["worktree", "add", targetDir, branch])
2711
+ : execGit(["worktree", "add", "-b", branch, targetDir])
2712
+ if (res.code !== 0) {
2713
+ return { content: `Error creating sentinel worktree: ${res.stderr || res.stdout}` }
2714
+ }
2715
+ }
2716
+ return {
2717
+ content: `Sentinel worktree ready at: ${targetDir}\nBranch: ${branch}`,
2718
+ worktreePath: targetDir,
2719
+ branch,
2720
+ baseBranch,
2721
+ }
2722
+ } else {
2723
+ if (!taskId) return { content: "Error: taskId is required for worker/verifier setup." }
2724
+ targetDir = join(runWorktreesDir, role === "verifier" ? `verifier-${taskId}` : taskId)
2725
+ branch = `teamwork/${runId}-${taskId}`
2726
+ // SEC-1: containment must hold before ANY mkdir / rmSync / worktree add.
2727
+ const escape = containmentError(runWorktreesDir, targetDir)
2728
+ if (escape) return { content: escape }
2729
+
2730
+ const hasBase = execGit(["rev-parse", "--verify", baseBranch]).code === 0
2731
+ const startPoint = hasBase ? baseBranch : "HEAD"
2732
+
2733
+ mkdirSync(dirname(targetDir), { recursive: true })
2734
+ if (existsSync(targetDir)) {
2735
+ const check = execGit(["rev-parse", "--is-inside-work-tree"], targetDir)
2736
+ if (check.code !== 0) {
2737
+ // rmSync only after re-proving containment (defence in depth).
2738
+ if (!containmentError(runWorktreesDir, targetDir)) {
2739
+ try { rmSync(targetDir, { recursive: true, force: true }) } catch {}
2740
+ }
2741
+ execGit(["worktree", "prune"])
2742
+ }
2743
+ }
2744
+ if (!existsSync(targetDir)) {
2745
+ const branchExists = execGit(["rev-parse", "--verify", branch]).code === 0
2746
+ const res = branchExists
2747
+ ? execGit(["worktree", "add", targetDir, branch])
2748
+ : execGit(["worktree", "add", "-b", branch, targetDir, startPoint])
2749
+ if (res.code !== 0) {
2750
+ return { content: `Error creating ${role} worktree: ${res.stderr || res.stdout}` }
2751
+ }
2752
+ }
2753
+ return {
2754
+ content: `${role} worktree ready at: ${targetDir}\nBranch: ${branch}\nBase: ${startPoint}`,
2755
+ worktreePath: targetDir,
2756
+ branch,
2757
+ baseBranch: startPoint,
2758
+ }
2759
+ }
2760
+ }
2761
+
2762
+ if (action === "diff") {
2763
+ if (!taskId) return { content: "Error: taskId is required for diff." }
2764
+ const branch = `teamwork/${runId}-${taskId}`
2765
+ const hasBranch = execGit(["rev-parse", "--verify", branch]).code === 0
2766
+ if (!hasBranch) {
2767
+ return { content: `Error: branch "${branch}" not found.` }
2768
+ }
2769
+ const hasBase = execGit(["rev-parse", "--verify", baseBranch]).code === 0
2770
+ const baseRef = hasBase ? baseBranch : "HEAD"
2771
+ const diffRes = execGit(["diff", `${baseRef}..${branch}`])
2772
+ const statRes = execGit(["diff", "--stat", `${baseRef}..${branch}`])
2773
+
2774
+ return {
2775
+ content: `Diff for ${taskId} (${baseRef}..${branch}):\n${statRes.stdout || "No changes."}\n\n${diffRes.stdout || ""}`,
2776
+ hasChanges: diffRes.stdout.length > 0,
2777
+ stat: statRes.stdout,
2778
+ }
2779
+ }
2780
+
2781
+ if (action === "merge") {
2782
+ if (!taskId) return { content: "Error: taskId is required for merge." }
2783
+ const branch = `teamwork/${runId}-${taskId}`
2784
+ const sentinelDir = join(runWorktreesDir, "sentinel")
2785
+ const targetCwd = existsSync(sentinelDir) ? sentinelDir : root
2786
+
2787
+ const mergeRes = execGit(["merge", "--no-ff", branch, "-m", `Merge task ${taskId} (${branch})`], targetCwd)
2788
+ if (mergeRes.code !== 0) {
2789
+ const conflictingFiles = mergeRes.stdout
2790
+ .split("\n")
2791
+ .filter((l) => l.includes("CONFLICT"))
2792
+ .map((l) => clean(l.replace(/CONFLICT\s*\([^)]*\):\s*/, ""), 120))
2793
+
2794
+ const oursDiff = execGit(["diff", `${branch}...${baseBranch}`], targetCwd).stdout
2795
+ const theirsDiff = execGit(["diff", `${baseBranch}...${branch}`], targetCwd).stdout
2796
+
2797
+ execGit(["merge", "--abort"], targetCwd)
2798
+
2799
+ const synDir = join(run, "synthesis")
2800
+ mkdirSync(synDir, { recursive: true })
2801
+ const conflictFile = join(synDir, `conflict-${taskId}.json`)
2802
+ const conflictArtifact = {
2803
+ taskId,
2804
+ sessionId: runId,
2805
+ baseBranch,
2806
+ incomingBranch: branch,
2807
+ conflictingFiles,
2808
+ diffOurs: oursDiff.slice(0, 10000),
2809
+ diffTheirs: theirsDiff.slice(0, 10000),
2810
+ timestamp: new Date().toISOString(),
2811
+ }
2812
+ writeJson(conflictFile, conflictArtifact)
2813
+
2814
+ return {
2815
+ content: `MERGE CONFLICT for task ${taskId} into ${baseBranch}:\n${conflictingFiles.join("\n") || mergeRes.stderr || mergeRes.stdout}\n\nConflict artifact generated at: ${conflictFile}\n(Merge was aborted; worktree remains clean. Sentinel should dispatch team/synthesizer to resolve conflict.)`,
2816
+ conflict: true,
2817
+ conflictArtifact: conflictFile,
2818
+ conflictingFiles,
2819
+ output: mergeRes.stdout,
2820
+ }
2821
+ }
2822
+
2823
+ return {
2824
+ content: `Successfully merged ${branch} into ${baseBranch}.\n${mergeRes.stdout}`,
2825
+ conflict: false,
2826
+ merged: true,
2827
+ }
2828
+ }
2829
+
2830
+ if (action === "resolve") {
2831
+ if (!taskId) return { content: "Error: taskId is required for resolve." }
2832
+ const sentinelDir = join(runWorktreesDir, "sentinel")
2833
+ const targetCwd = existsSync(sentinelDir) ? sentinelDir : root
2834
+ const statusRes = execGit(["status", "--porcelain"], targetCwd)
2835
+ if (!statusRes.stdout) {
2836
+ return { content: `No modified files to commit for conflict resolution in ${sentinelDir}.` }
2837
+ }
2838
+ execGit(["add", "-A"], targetCwd)
2839
+ const commitMsg = clean(input.commitMessage || `Resolve merge conflict for task ${taskId}`, 200)
2840
+ const commitRes = execGit(["commit", "-m", commitMsg], targetCwd)
2841
+ return {
2842
+ content: `Committed conflict resolution for ${taskId}:\n${commitRes.stdout}`,
2843
+ resolved: true,
2844
+ }
2845
+ }
2846
+
2847
+ if (action === "cleanup") {
2848
+ if (existsSync(runWorktreesDir)) {
2849
+ execGit(["worktree", "prune"])
2850
+ try {
2851
+ const entries = readdirSync(runWorktreesDir)
2852
+ for (const entry of entries) {
2853
+ const p = join(runWorktreesDir, entry)
2854
+ execGit(["worktree", "remove", "--force", p])
2855
+ }
2856
+ } catch {}
2857
+ execGit(["worktree", "prune"])
2858
+ }
2859
+ return {
2860
+ content: `Cleaned up worktrees for run ${runId} at ${runWorktreesDir}.`,
2861
+ cleaned: true,
2862
+ }
2863
+ }
2864
+
2865
+ return { content: `Error: unknown action "${action}". Allowed: setup | diff | merge | resolve | cleanup` }
2866
+ },
2867
+ })
2868
+ })
2869
+ }
2870
+
2871
+ export async function registerTeamworkHooks(ctx: any, root: string) {
2872
+ // Fail-closed: if the permission API is unavailable we refuse to load rather
2873
+ // than silently dropping the read-only guardrail.
2874
+ if (typeof ctx?.permission?.hook !== "function") {
2875
+ throw new Error("teamwork: permission API unavailable — refusing to load without the read-only guardrail")
2876
+ }
2877
+
2878
+ // Read-only guarantee for critic/verifier/security-auditor agents, enforced in code.
2879
+ await ctx.permission.hook("evaluate", (event: any) => {
2880
+ const deny = READ_ONLY_ACTIONS[event.agent]
2881
+ if (deny && deny.has(event.action)) {
2882
+ event.effect = "deny"
2883
+ event.message = `${event.agent} is restricted during a Teamwork run (${event.action} denied).`
2884
+ return
2885
+ }
2886
+
2887
+ // Network constraint enforcement for worker/verifier
2888
+ if (event.action === "webfetch" && (event.agent === "team/worker" || event.agent === "team/verifier")) {
2889
+ const { run } = resolveRun(root)
2890
+ if (run) {
2891
+ try {
2892
+ const specPath = join(run, "prompt_draft.md")
2893
+ if (existsSync(specPath)) {
2894
+ const specText = readFileSync(specPath, "utf8")
2895
+ if (/network:\s*["']?denied["']?/i.test(specText)) {
2896
+ event.effect = "deny"
2897
+ event.message = "Network access is denied by run spec constraints."
2898
+ }
2899
+ }
2900
+ } catch {}
2901
+ }
2902
+ }
2903
+ })
2904
+
2905
+ // Inject the active run's (sanitised) state into every team agent's context.
2906
+ await ctx.session?.hook?.("context", (event: any) => {
2907
+ if (typeof event.agent === "string" && event.agent.startsWith("team/")) {
2908
+ const text = describeRun(root)
2909
+ if (text) event.system.push({ type: "text", text })
2910
+ }
2911
+ })
2912
+ }