@wrongstack/core 0.272.2 → 0.273.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-bridge-DFQYEeXf.d.ts → agent-bridge-BZ2enORi.d.ts} +1 -1
- package/dist/{agent-subagent-runner-BZa_IEcd.d.ts → agent-subagent-runner-ehb4xGvd.d.ts} +11 -4
- package/dist/{brain-etbcbRwV.d.ts → brain-BxN2k2HP.d.ts} +101 -0
- package/dist/{config-rRS8yorV.d.ts → config-C8IYxlO8.d.ts} +8 -1
- package/dist/coordination/index.d.ts +13 -13
- package/dist/coordination/index.js +79 -25
- package/dist/coordination/index.js.map +1 -1
- package/dist/{default-config-B0cj-Hry.d.ts → default-config-BbX4ojZs.d.ts} +1 -0
- package/dist/defaults/index.d.ts +20 -19
- package/dist/defaults/index.js +2813 -206
- package/dist/defaults/index.js.map +1 -1
- package/dist/execution/index.d.ts +10 -10
- package/dist/execution/index.js +8 -2
- package/dist/execution/index.js.map +1 -1
- package/dist/extension/index.d.ts +4 -4
- package/dist/{global-mailbox-DJ4EoRr0.d.ts → global-mailbox-C9dsc9Y_.d.ts} +1 -1
- package/dist/{goal-preamble-hM8BH7TK.d.ts → goal-preamble-NhflDjYb.d.ts} +6 -6
- package/dist/{goal-store-CWlbT0TO.d.ts → goal-store-Cx363x7Z.d.ts} +1 -1
- package/dist/hq/index.d.ts +4 -4
- package/dist/hq/index.js +1 -0
- package/dist/hq/index.js.map +1 -1
- package/dist/{index-DWm_PE9L.d.ts → index-B7fHDt0B.d.ts} +12 -4
- package/dist/{index-2Lhk5v0o.d.ts → index-BbVprU-9.d.ts} +6 -0
- package/dist/index.d.ts +194 -33
- package/dist/index.js +3222 -681
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/index.d.ts +4 -4
- package/dist/kernel/index.d.ts +94 -14
- package/dist/kernel/index.js.map +1 -1
- package/dist/{mcp-servers-BpWHTKlE.d.ts → mcp-servers-B6fSRNC1.d.ts} +1 -1
- package/dist/models/index.d.ts +3 -3
- package/dist/{models-registry-CXQFUn5t.d.ts → models-registry-4C6Wr91w.d.ts} +1 -1
- package/dist/{multi-agent-coordinator-jyimfo7D.d.ts → multi-agent-coordinator-q1skFeNP.d.ts} +1 -1
- package/dist/{null-fleet-bus-DOGQcvrY.d.ts → null-fleet-bus-C9rrgQwc.d.ts} +15 -5
- package/dist/observability/index.d.ts +1 -1
- package/dist/{parallel-eternal-engine-rItJBYp9.d.ts → parallel-eternal-engine-CtXly2Sf.d.ts} +7 -6
- package/dist/{path-resolver-DrpF5MGK.d.ts → path-resolver-Bim6G5Jz.d.ts} +2 -2
- package/dist/{pipeline-Ckkn3AOA.d.ts → pipeline-CNVKuQDQ.d.ts} +1 -1
- package/dist/{plan-templates-BvHw5Znw.d.ts → plan-templates-C4wXMmiM.d.ts} +3 -3
- package/dist/{provider-model-resolve-nZqnCeaR.d.ts → provider-model-resolve-DFd3IPpw.d.ts} +1 -1
- package/dist/{provider-runner-zVOn1p67.d.ts → provider-runner-BpM0mdBE.d.ts} +1 -1
- package/dist/sdd/index.d.ts +1111 -11
- package/dist/sdd/index.js +5516 -2949
- package/dist/sdd/index.js.map +1 -1
- package/dist/security/index.d.ts +1 -1
- package/dist/security/index.js +6 -0
- package/dist/security/index.js.map +1 -1
- package/dist/storage/index.d.ts +8 -8
- package/dist/storage/index.js +3 -2
- package/dist/storage/index.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/types/index.d.ts +14 -14
- package/dist/types/index.js +3 -0
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +30 -4
- package/dist/utils/index.js +110 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/{index-DqW4o62H.d.ts → worktree-manager-BDuXTaWL.d.ts} +48 -90
- package/dist/{wstack-paths-hOpNLmvf.d.ts → wstack-paths-BqkDAkoh.d.ts} +2 -0
- package/package.json +1 -1
package/dist/sdd/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/atomic-write.ts","../../src/sdd/spec-parser.ts","../../src/sdd/task-generator.ts","../../src/types/task-graph.ts","../../src/utils/assert-never.ts","../../src/utils/error.ts","../../src/utils/expect-defined.ts","../../src/utils/string.ts","../../src/types/errors.ts","../../src/sdd/task-tracker.ts","../../src/sdd/task-flow.ts","../../src/sdd/spec-store.ts","../../src/sdd/task-graph-store.ts","../../src/sdd/spec-builder.ts","../../src/sdd/spec-templates.ts","../../src/sdd/task-visualizer.ts","../../src/sdd/critical-path.ts","../../src/sdd/spec-versioning.ts","../../src/sdd/auto-executor.ts","../../src/sdd/sdd-task-decomposer.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/types/provider.ts","../../src/coordination/coordinator/error-classifier.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/sdd/sdd-parallel-run.ts"],"names":["stat","path2","fsp","path3","fsp2","path","atomicWrite","first","baseMessage","randomUUID","PreemptState"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,WAAA,EAAA,MAAA,WAAA;AAAA,EAAA,SAAA,EAAA,MAAA,SAAA;AAAA,EAAA,YAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAcA,eAAsB,WAAA,CACpB,UAAA,EACA,OAAA,EACA,IAAA,GAA2B,EAAC,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,UAAA,CAAW,SAAA,EAAU,CAAE,UAAA;AAC9B,IAAA,OAAO;AAAA,MACL,IAAA,EAAM,IAAA,CAAK,UAAA,CAAW,YAAA,EAAa;AAAA,MACnC,OAAO,EAAA,CAAG,KAAA;AAAA,MACV,WAAW,EAAA,CAAG,SAAA;AAAA,MACd,YAAY,EAAA,CAAG,UAAA;AAAA,MACf,QAAQ,EAAA,CAAG,MAAA;AAAA,MACX,SAAS,EAAA,CAAG,OAAA;AAAA,MACZ,SAAS,EAAA,CAAG,OAAA;AAAA,MACZ,SAAS,EAAA,CAAG,eAAA;AAAA,MACZ,UAAA,EAAY;AAAA,KACd;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n const timeoutMs = opts.timeoutMs ?? 5_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`Timed out waiting for file lock: ${targetPath}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import type {\n SpecAnalysis,\n SpecRequirement,\n SpecSection,\n SpecValidationResult,\n Specification,\n} from '../types/spec.js';\n\nexport class SpecParser {\n parse(content: string): Specification {\n const lines = content.split('\\n');\n const sections = this.extractSections(lines);\n const requirements = this.extractRequirements(lines);\n const now = Date.now();\n\n return {\n id: crypto.randomUUID(),\n title: this.extractTitle(lines),\n version: this.extractVersion(lines),\n status: 'draft',\n overview: this.extractOverview(lines),\n sections,\n requirements,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n private extractTitle(lines: string[]): string {\n for (const line of lines) {\n const m = /^#\\s+(.+)/.exec(line.trim());\n if (m?.[1]) return m[1];\n }\n return 'Untitled Specification';\n }\n\n private extractVersion(lines: string[]): string {\n for (const line of lines) {\n const m = /version[:\\s]+(\\d+\\.\\d+\\.\\d+)/i.exec(line.trim());\n if (m?.[1]) return m[1];\n }\n return '0.0.1';\n }\n\n private extractOverview(lines: string[]): string {\n const overviewLines: string[] = [];\n let inOverview = false;\n let foundHeading = false;\n\n for (const line of lines) {\n if (/^##\\s+Overview/i.test(line.trim())) {\n inOverview = true;\n foundHeading = true;\n continue;\n }\n if (foundHeading && /^##\\s+/.test(line.trim())) break;\n if (inOverview) overviewLines.push(line);\n }\n\n return overviewLines.join('\\n').trim() || 'No overview provided';\n }\n\n private extractSections(lines: string[]): SpecSection[] {\n const sections: SpecSection[] = [];\n let currentSection: Partial<SpecSection> | null = null;\n let currentLines: string[] = [];\n let depth = 1;\n\n for (const line of lines) {\n const h2 = /^##\\s+(.+)/.exec(line.trim());\n const h3 = /^###\\s+(.+)/.exec(line.trim());\n\n if (h2) {\n if (currentSection && currentLines.length > 0) {\n sections.push({\n type: this.mapSectionType(currentSection.title ?? 'unknown'),\n title: currentSection.title ?? 'Unknown',\n level: depth,\n content: currentLines.join('\\n').trim(),\n });\n }\n currentSection = { title: h2[1] ?? 'Unknown' };\n currentLines = [];\n depth = 2;\n continue;\n }\n\n if (h3) {\n currentLines.push(line);\n continue;\n }\n\n if (currentSection) {\n currentLines.push(line);\n }\n }\n\n if (currentSection && currentLines.length > 0) {\n sections.push({\n type: this.mapSectionType(currentSection.title ?? 'unknown'),\n title: currentSection.title ?? 'Unknown',\n level: depth,\n content: currentLines.join('\\n').trim(),\n });\n }\n\n return sections;\n }\n\n private extractRequirements(lines: string[]): SpecRequirement[] {\n const requirements: SpecRequirement[] = [];\n let inRequirements = false;\n let idCounter = 0;\n\n for (const line of lines) {\n if (/^##\\s+Requirements/i.test(line.trim())) {\n inRequirements = true;\n continue;\n }\n if (inRequirements && /^##\\s+/.test(line.trim())) break;\n\n if (inRequirements) {\n const req = this.parseRequirementLine(line, `REQ-${++idCounter}`);\n if (req) requirements.push(req);\n }\n }\n\n return requirements;\n }\n\n private parseRequirementLine(line: string, id: string): SpecRequirement | null {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) return null;\n\n const lower = trimmed.toLowerCase();\n const types: SpecRequirement['type'][] = [\n 'functional',\n 'non-functional',\n 'security',\n 'performance',\n 'ux',\n ];\n let type: SpecRequirement['type'] = 'functional';\n for (const t of types) {\n if (lower.includes(`[${t}]`)) type = t;\n }\n\n let priority: SpecRequirement['priority'] = 'medium';\n if (trimmed.includes('[critical]') || trimmed.includes('[prio:high]')) {\n priority = 'critical';\n } else if (trimmed.includes('[high]')) {\n priority = 'high';\n } else if (trimmed.includes('[low]')) {\n priority = 'low';\n }\n\n return {\n id,\n type,\n priority,\n description: trimmed.replace(/\\[[^\\]]+\\]/g, '').trim(),\n acceptanceCriteria: [],\n };\n }\n\n private mapSectionType(title: string): SpecSection['type'] {\n const t = title.toLowerCase();\n if (t.includes('overview')) return 'overview';\n if (t.includes('requirement')) return 'requirements';\n if (t.includes('architect')) return 'architecture';\n if (t.includes('api')) return 'api';\n if (t.includes('data')) return 'data';\n if (t.includes('security')) return 'security';\n if (t.includes('acceptance')) return 'acceptance';\n return 'overview';\n }\n\n analyze(spec: Specification): SpecAnalysis {\n const gaps: string[] = [];\n const suggestions: string[] = [];\n const risks: SpecAnalysis['risks'] = [];\n\n // Check completeness\n const hasOverview = spec.sections.some((s) => s.type === 'overview');\n const hasRequirements = spec.sections.some((s) => s.type === 'requirements');\n const hasAcceptance = spec.sections.some((s) => s.type === 'acceptance');\n\n if (!hasOverview) gaps.push('Missing Overview section');\n if (!hasRequirements) gaps.push('Missing Requirements section');\n if (!hasAcceptance) gaps.push('Missing Acceptance Criteria section');\n\n if (spec.requirements.length === 0) {\n gaps.push('No requirements defined');\n suggestions.push('Add specific functional and non-functional requirements');\n }\n\n const unverifiedReqs = spec.requirements.filter((r) => r.acceptanceCriteria.length === 0);\n if (unverifiedReqs.length > 0) {\n gaps.push(`${unverifiedReqs.length} requirements without acceptance criteria`);\n suggestions.push('Define clear acceptance criteria for each requirement');\n }\n\n const criticalUnresolved = spec.requirements.filter(\n (r) => r.priority === 'critical' && r.blockedBy && r.blockedBy.length > 0,\n );\n for (const req of criticalUnresolved) {\n risks.push({\n requirement: req.id,\n risk: `Critical requirement blocked by ${req.blockedBy?.length} other requirements`,\n severity: 'high',\n });\n }\n\n const completeness = Math.round(\n (((hasOverview ? 1 : 0) +\n (hasRequirements ? 1 : 0) +\n (hasAcceptance ? 1 : 0) +\n (spec.requirements.length > 0 ? 1 : 0) +\n (spec.sections.length > 3 ? 1 : 0)) /\n 5) *\n 100,\n );\n\n return {\n specId: spec.id,\n completeness,\n coverage: {\n requirements: spec.requirements.length,\n apiEndpoints: spec.apiEndpoints?.length ?? 0,\n edgeCases: 0,\n errorHandling: 0,\n },\n gaps,\n risks,\n suggestions,\n };\n }\n\n validate(spec: Specification): SpecValidationResult {\n const errors: SpecValidationResult['errors'] = [];\n const warnings: SpecValidationResult['warnings'] = [];\n\n if (!spec.title.trim()) {\n errors.push({ path: 'title', message: 'Title is required' });\n }\n\n if (!spec.version.trim()) {\n errors.push({ path: 'version', message: 'Version is required' });\n }\n\n for (const req of spec.requirements) {\n if (!req.description.trim()) {\n errors.push({ path: `requirement.${req.id}`, message: 'Requirement description is empty' });\n }\n if (req.acceptanceCriteria.length === 0) {\n warnings.push({ path: `requirement.${req.id}`, message: 'No acceptance criteria defined' });\n }\n }\n\n const reqIds = new Set(spec.requirements.map((r) => r.id));\n const blockedByIds = new Set(spec.requirements.flatMap((r) => r.blockedBy ?? []));\n for (const id of blockedByIds) {\n if (!reqIds.has(id)) {\n errors.push({\n path: 'requirements',\n message: `BlockedBy references non-existent requirement: ${id}`,\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n}\n","import type { SpecRequirement, Specification } from '../types/spec.js';\nimport type { TaskGraph, TaskNode, TaskPriority, TaskType } from '../types/task-graph.js';\nimport type { TaskStore, TaskTracker } from './task-tracker.js';\n\nexport interface TaskGeneratorOptions {\n taskTracker: TaskTracker;\n}\n\nexport interface GeneratedTask {\n specRequirementId?: string | undefined;\n title: string;\n description: string;\n type: TaskType;\n priority: TaskPriority;\n estimateHours?: number | undefined;\n tags?: string[] | undefined;\n}\n\nexport class TaskGenerator {\n constructor(private readonly opts: TaskGeneratorOptions) {}\n\n async generateFromSpec(spec: Specification): Promise<TaskGraph> {\n const graph = await this.opts.taskTracker.createGraph(spec.id, spec.title);\n\n const overview = spec.sections.find((s) => s.type === 'overview');\n if (overview) {\n this.opts.taskTracker.addNode({\n title: `Implement ${spec.title}`,\n description: overview.content,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n });\n }\n\n // Group requirements by priority in a single pass, then emit in priority order.\n const byPriority: Record<TaskPriority, SpecRequirement[]> = {\n critical: [],\n high: [],\n medium: [],\n low: [],\n };\n for (const req of spec.requirements) {\n const bucket = byPriority[req.priority] ?? byPriority.medium;\n bucket.push(req);\n }\n\n const order: TaskPriority[] = ['critical', 'high', 'medium', 'low'];\n for (const p of order) {\n for (const req of byPriority[p]) {\n this.opts.taskTracker.addNode(this.createTaskFromRequirement(req));\n }\n }\n\n // API tasks\n if (spec.apiEndpoints && spec.apiEndpoints.length > 0) {\n const apiParent = this.opts.taskTracker.addNode({\n title: 'API Implementation',\n description: `Implement ${spec.apiEndpoints.length} API endpoints`,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n });\n\n for (const endpoint of spec.apiEndpoints) {\n const task = this.createTaskFromEndpoint(endpoint);\n this.opts.taskTracker.addNode({\n ...task,\n parentId: apiParent.id,\n });\n }\n }\n\n // Test tasks\n this.opts.taskTracker.addNode({\n title: 'Write Tests',\n description: 'Comprehensive test coverage for all features',\n type: 'test',\n priority: 'high',\n status: 'pending',\n });\n\n // Documentation tasks\n this.opts.taskTracker.addNode({\n title: 'Update Documentation',\n description: 'Update docs for new features',\n type: 'docs',\n priority: 'medium',\n status: 'pending',\n });\n\n return graph;\n }\n\n private createTaskFromRequirement(\n req: SpecRequirement,\n ): Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'> {\n return {\n title: req.description,\n description: this.buildDescription(req),\n type: this.mapRequirementType(req.type),\n priority: req.priority,\n status: 'pending',\n specRequirementId: req.id,\n tags: [req.type, req.priority],\n estimateHours: this.estimateHours(req),\n };\n }\n\n private createTaskFromEndpoint(\n endpoint: NonNullable<Specification['apiEndpoints']>[number],\n ): Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'> {\n return {\n title: `${endpoint.method} ${endpoint.path}`,\n description: endpoint.description,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n tags: [endpoint.method],\n estimateHours: this.estimateForEndpoint(endpoint),\n };\n }\n\n private buildDescription(req: SpecRequirement): string {\n const lines = [req.description, '', '**Type:** ' + req.type, '**Priority:** ' + req.priority];\n\n if (req.acceptanceCriteria.length > 0) {\n lines.push('', '**Acceptance Criteria:**');\n for (const criterion of req.acceptanceCriteria) {\n lines.push(`- ${criterion}`);\n }\n }\n\n if (req.blockedBy && req.blockedBy.length > 0) {\n lines.push('', `**Blocked by:** ${req.blockedBy.join(', ')}`);\n }\n\n return lines.join('\\n');\n }\n\n private mapRequirementType(type: SpecRequirement['type']): TaskType {\n switch (type) {\n case 'functional':\n return 'feature';\n case 'non-functional':\n return 'feature';\n case 'security':\n return 'feature';\n case 'performance':\n return 'feature';\n case 'ux':\n return 'feature';\n default:\n return 'feature';\n }\n }\n\n private estimateHours(req: SpecRequirement): number {\n switch (req.priority) {\n case 'critical':\n return 8;\n case 'high':\n return 4;\n case 'medium':\n return 2;\n case 'low':\n return 1;\n default:\n return 2;\n }\n }\n\n private estimateForEndpoint(\n endpoint: NonNullable<Specification['apiEndpoints']>[number],\n ): number {\n let hours = 2;\n if (endpoint.auth) hours += 1;\n if (endpoint.request) hours += 1;\n return hours;\n }\n\n async generateSubtasks(parentTaskId: string, spec: Specification): Promise<void> {\n const reqId = this.opts.taskTracker.getNode(parentTaskId)?.specRequirementId;\n if (!reqId) return;\n\n const req = spec.requirements.find((r) => r.id === reqId);\n if (!req) return;\n\n if (req.acceptanceCriteria.length > 0) {\n for (const criterion of req.acceptanceCriteria) {\n this.opts.taskTracker.addNode({\n title: criterion,\n description: `Verify: ${criterion}`,\n type: 'test',\n priority: 'medium',\n status: 'pending',\n parentId: parentTaskId,\n });\n }\n }\n }\n}\n\nexport class DefaultTaskStore implements TaskStore {\n private graphs = new Map<string, TaskGraph>();\n\n async saveGraph(graph: TaskGraph): Promise<void> {\n this.graphs.set(graph.id, this.cloneGraph(graph));\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n const g = this.graphs.get(id);\n return g ? this.cloneGraph(g) : null;\n }\n\n async listGraphs(): Promise<{ id: string; title: string; updatedAt: number }[]> {\n return Array.from(this.graphs.values()).map((g) => ({\n id: g.id,\n title: g.title,\n updatedAt: g.updatedAt,\n }));\n }\n\n async deleteGraph(id: string): Promise<void> {\n this.graphs.delete(id);\n }\n\n private cloneGraph(g: TaskGraph): TaskGraph {\n return {\n ...g,\n nodes: new Map(g.nodes),\n edges: [...g.edges],\n rootNodes: [...g.rootNodes],\n };\n }\n}\n","export type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'failed' | 'review' | 'completed';\r\nexport type TaskPriority = 'critical' | 'high' | 'medium' | 'low';\r\nexport type TaskType = 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'chore';\r\n\r\nexport interface TaskNode {\r\n id: string;\r\n title: string;\r\n description: string;\r\n type: TaskType;\r\n priority: TaskPriority;\r\n status: TaskStatus;\r\n assignee?: string | undefined;\r\n estimateHours?: number | undefined;\r\n actualHours?: number | undefined;\r\n tags?: string[] | undefined;\r\n specRequirementId?: string | undefined;\r\n parentId?: string | undefined;\r\n children?: string[] | undefined;\r\n createdAt: number;\r\n updatedAt: number;\r\n startedAt?: number | undefined; // set when status → in_progress\r\n completedAt?: number | undefined;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface TaskEdge {\r\n id: string;\r\n from: string;\r\n to: string;\r\n type: 'blocks' | 'depends_on' | 'relates_to' | 'implements';\r\n weight?: number | undefined;\r\n}\r\n\r\nexport interface TaskGraph {\r\n id: string;\r\n specId: string;\r\n title: string;\r\n nodes: Map<string, TaskNode>;\r\n edges: TaskEdge[];\r\n rootNodes: string[];\r\n createdAt: number;\r\n updatedAt: number;\r\n}\r\n\r\nexport interface TaskDependency {\r\n taskId: string;\r\n blockedBy: string[];\r\n blocking: string[];\r\n}\r\n\r\nexport interface TaskAssignment {\r\n taskId: string;\r\n assignee: string;\r\n assignedAt: number;\r\n}\r\n\r\nexport interface TaskProgress {\r\n total: number;\r\n pending: number;\r\n inProgress: number;\r\n blocked: number;\r\n failed: number;\r\n review: number;\r\n completed: number;\r\n percentComplete: number;\r\n estimatedHours: number;\r\n actualHours: number;\r\n}\r\n\r\nexport interface TaskFilter {\r\n status?: TaskStatus[] | undefined;\r\n priority?: TaskPriority[] | undefined;\r\n type?: TaskType[] | undefined;\r\n assignee?: string[] | undefined;\r\n tags?: string[] | undefined;\r\n specRequirementId?: string | undefined;\r\n}\r\n\r\nexport interface TaskSort {\r\n field: 'priority' | 'createdAt' | 'updatedAt' | 'status';\r\n direction: 'asc' | 'desc';\r\n}\r\n\r\nexport interface CriticalPathResult {\r\n taskIds: string[];\r\n totalEstimateHours: number;\r\n bottleneckTasks: string[];\r\n}\r\n\r\nexport function computeTaskProgress(graph: TaskGraph): TaskProgress {\r\n let completed = 0;\r\n let pending = 0;\r\n let inProgress = 0;\r\n let blocked = 0;\r\n let failed = 0;\r\n let review = 0;\r\n let estimatedHours = 0;\r\n let actualHours = 0;\r\n for (const n of graph.nodes.values()) {\r\n switch (n.status) {\r\n case 'completed':\r\n completed++;\r\n break;\r\n case 'pending':\r\n pending++;\r\n break;\r\n case 'in_progress':\r\n inProgress++;\r\n break;\r\n case 'blocked':\r\n blocked++;\r\n break;\r\n case 'failed':\r\n failed++;\r\n break;\r\n case 'review':\r\n review++;\r\n break;\r\n }\r\n estimatedHours += n.estimateHours ?? 0;\r\n actualHours += n.actualHours ?? 0;\r\n }\r\n const total = graph.nodes.size;\r\n\r\n return {\r\n total,\r\n pending,\r\n inProgress,\r\n blocked,\r\n failed,\r\n review,\r\n completed,\r\n percentComplete: total > 0 ? Math.round((completed / total) * 100) : 0,\r\n estimatedHours,\r\n actualHours,\r\n };\r\n}\r\n\r\nexport function findCriticalPath(graph: TaskGraph): CriticalPathResult {\r\n const nodes = Array.from(graph.nodes.values());\r\n const criticalNodes = nodes.filter((n) => n.priority === 'critical');\r\n const bottleneckTasks = criticalNodes\r\n .filter((n) => graph.edges.some((e) => e.to === n.id && e.type === 'depends_on'))\r\n .map((n) => n.id);\r\n\r\n const totalEstimateHours = criticalNodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\r\n\r\n return {\r\n taskIds: criticalNodes.map((n) => n.id),\r\n totalEstimateHours,\r\n bottleneckTasks,\r\n };\r\n}\r\n\r\nexport function topologicalSort(graph: TaskGraph): string[] {\r\n const visited = new Set<string>();\r\n const inStack = new Set<string>();\r\n const result: string[] = [];\r\n\r\n function visit(id: string): void {\r\n // Cycle: callers must detect cycles up-front if they care; we just stop recursing.\r\n if (inStack.has(id)) return;\r\n if (visited.has(id)) return;\r\n if (!graph.nodes.has(id)) return;\r\n\r\n visited.add(id);\r\n inStack.add(id);\r\n\r\n for (const edge of graph.edges) {\r\n if (edge.from === id) visit(edge.to);\r\n }\r\n\r\n inStack.delete(id);\r\n result.push(id);\r\n }\r\n\r\n for (const rootId of graph.rootNodes) {\r\n visit(rootId);\r\n }\r\n\r\n return result;\r\n}\r\n","/**\n * Exhaustiveness check for discriminated union switches.\n * Place in the `default` branch of a switch over a union type\n * to get a compile-time error when a new variant is added.\n *\n * @example\n * switch (block.type) {\n * case 'text': return renderText(block);\n * case 'tool_use': return renderToolUse(block);\n * default: return assertNever(block);\n * }\n */\nexport function assertNever(x: never, message?: string): never {\n const err = new Error(\n message ?? `Unhandled case: ${JSON.stringify(x)}`,\n );\n err.name = 'AssertNeverError';\n throw err;\n}\n","/**\n * Converts an unknown error value to a human-readable string.\n * Used in 40+ files across the codebase to normalize error messaging.\n */\nexport function toErrorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/** Assert a value is neither null nor undefined. Throws if it is.\n * Useful after optional chaining and indexed access when the\n * control flow guarantees the value exists but TypeScript can't\n * prove it (e.g. after a check on a related field). */\nexport function expectDefined<T>(value: T | null | undefined, label?: string): T {\n if (value === null || value === undefined) {\n const err = new Error(label ? `Expected ${label} to be defined` : 'Expected value to be defined');\n err.name = 'ExpectDefinedError';\n throw err;\n }\n return value;\n}\n","/**\n * String utilities shared across the WrongStack codebase.\n */\n\n/**\n * Truncate a string to at most `max` characters, appending an ellipsis if it\n * was longer. Returns the original string unchanged when it fits.\n */\nexport function truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors — spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n","import type {\n TaskFilter,\n TaskGraph,\n TaskNode,\n TaskProgress,\n TaskSort,\n} from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { toErrorMessage } from '../utils/error.js';\n\nexport interface TaskStore {\n saveGraph(graph: TaskGraph): Promise<void>;\n loadGraph(id: string): Promise<TaskGraph | null>;\n listGraphs(): Promise<{ id: string; title: string; updatedAt: number }[]>;\n deleteGraph(id: string): Promise<void>;\n}\n\nexport interface TaskTrackerOptions {\n store: TaskStore;\n /**\n * Called when an in-the-background persistence (`saveGraph`) rejects.\n * The synchronous TaskTracker methods (addNode/addEdge/updateNodeStatus)\n * fire-and-forget their writes; without this, a failing store silently\n * loses graph mutations. Defaults to a console.warn.\n */\n onPersistError?: (((err: unknown) => void)) | undefined;\n}\n\nexport interface TaskTransition {\n from: TaskNode['status'];\n to: TaskNode['status'];\n timestamp: number;\n reason?: string | undefined;\n}\n\nexport class TaskTracker {\n private graph: TaskGraph | null = null;\n private transitions: TaskTransition[] = [];\n\n constructor(private readonly opts: TaskTrackerOptions) {}\n\n /**\n * Attach an existing graph (used by PhaseOrchestrator to associate a tracker\n * with a phase's pre-built task graph without re-creating it).\n */\n setGraph(graph: TaskGraph): void {\n this.graph = graph;\n }\n\n async createGraph(specId: string, title: string): Promise<TaskGraph> {\n this.graph = {\n id: crypto.randomUUID(),\n specId,\n title,\n nodes: new Map(),\n edges: [],\n rootNodes: [],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n await this.opts.store.saveGraph(this.graph);\n return this.graph;\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n this.graph = await this.opts.store.loadGraph(id);\n return this.graph;\n }\n\n addNode(node: Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'>): TaskNode {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const now = Date.now();\n const newNode: TaskNode = {\n ...node,\n id: crypto.randomUUID(),\n status: node.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n\n this.graph.nodes.set(newNode.id, newNode);\n\n if (!node.parentId) {\n this.graph.rootNodes.push(newNode.id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n\n return newNode;\n }\n\n addEdge(from: string, to: string, type: TaskGraph['edges'][0]['type'] = 'depends_on'): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n this.graph.edges.push({\n id: crypto.randomUUID(),\n from,\n to,\n type,\n });\n this.graph.updatedAt = Date.now();\n this.persist();\n }\n\n updateNodeStatus(id: string, status: TaskNode['status'], reason?: string): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node) throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n const from = node.status;\n const now = Date.now();\n node.status = status;\n node.updatedAt = now;\n\n if (status === 'completed') {\n node.completedAt = now;\n node.startedAt = node.startedAt ?? now; // ensure startedAt is set\n }\n if (status === 'in_progress') {\n node.startedAt = now;\n }\n\n this.transitions.push({ from, to: status, timestamp: now, reason });\n\n // Auto-unblock dependents\n if (status === 'completed') {\n this.unblockDependents(id);\n }\n\n // Auto-block blockers\n if (status === 'in_progress') {\n this.checkAndBlockIfNeeded(id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n }\n\n updateNode(id: string, patch: Partial<Pick<TaskNode, 'title' | 'description' | 'priority' | 'estimateHours' | 'tags'>>): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node) throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n if (patch.title !== undefined) node.title = patch.title;\n if (patch.description !== undefined) node.description = patch.description;\n if (patch.priority !== undefined) node.priority = patch.priority;\n if (patch.estimateHours !== undefined) node.estimateHours = patch.estimateHours;\n if (patch.tags !== undefined) node.tags = patch.tags;\n node.updatedAt = Date.now();\n this.graph.updatedAt = node.updatedAt;\n this.persist();\n }\n\n getNode(id: string): TaskNode | undefined {\n return this.graph?.nodes.get(id);\n }\n\n getAllNodes(filter?: TaskFilter, sort?: TaskSort): TaskNode[] {\n if (!this.graph) return [];\n\n let nodes = Array.from(this.graph.nodes.values());\n\n if (filter) {\n nodes = nodes.filter((n) => {\n if (filter.status?.length && !filter.status.includes(n.status)) return false;\n if (filter.priority?.length && !filter.priority.includes(n.priority)) return false;\n if (filter.type?.length && !filter.type.includes(n.type)) return false;\n if (filter.assignee?.length && n.assignee && !filter.assignee.includes(n.assignee))\n return false;\n if (filter.tags?.length && n.tags && !n.tags.some((t) => filter.tags?.includes(t)))\n return false;\n if (filter.specRequirementId && n.specRequirementId !== filter.specRequirementId)\n return false;\n return true;\n });\n }\n\n if (sort) {\n nodes.sort((a, b) => {\n const cmp = compareByField(a, b, sort.field);\n return sort.direction === 'asc' ? cmp : -cmp;\n });\n }\n\n return nodes;\n }\n\n getChildren(parentId: string): TaskNode[] {\n if (!this.graph) return [];\n return Array.from(this.graph.nodes.values()).filter((n) => n.parentId === parentId);\n }\n\n getDependents(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.from === taskId && e.type === 'depends_on')\n .map((e) => e.to);\n }\n\n getBlockers(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.to === taskId && e.type === 'depends_on')\n .map((e) => e.from);\n }\n\n canStart(taskId: string): boolean {\n const blockers = this.getBlockers(taskId);\n return blockers.every((id) => {\n const node = this.graph?.nodes.get(id);\n // A task can start when all blockers are either completed or failed.\n // Failed blockers should not permanently deadlock dependent tasks.\n return node?.status === 'completed' || node?.status === 'failed';\n });\n }\n\n getProgress(): TaskProgress {\n if (!this.graph) {\n return {\n total: 0,\n pending: 0,\n inProgress: 0,\n blocked: 0,\n failed: 0,\n review: 0,\n completed: 0,\n percentComplete: 0,\n estimatedHours: 0,\n actualHours: 0,\n };\n }\n return computeTaskProgress(this.graph);\n }\n\n getTransitions(_taskId?: string): TaskTransition[] {\n return [...this.transitions];\n }\n\n private unblockDependents(completedId: string): void {\n if (!this.graph) return;\n const dependents = this.getDependents(completedId);\n for (const depId of dependents) {\n const dep = this.graph.nodes.get(depId);\n if (dep?.status === 'blocked') {\n // Check if all blockers are now completed\n const remainingBlockers = this.getBlockers(depId);\n const allUnblocked = remainingBlockers.every((id) => {\n const blocker = this.graph?.nodes.get(id);\n return blocker?.status === 'completed' || blocker?.status === 'failed';\n });\n if (allUnblocked) {\n dep.status = 'pending';\n dep.updatedAt = Date.now();\n }\n }\n }\n }\n\n private checkAndBlockIfNeeded(taskId: string): void {\n if (!this.graph) return;\n const blockers = this.getBlockers(taskId);\n const someBlocked = blockers.some((id) => {\n const blocker = this.graph?.nodes.get(id);\n // A task is only blocked by incomplete blockers that haven't failed.\n // Failed tasks should not block their dependents.\n return blocker?.status !== 'completed' && blocker?.status !== 'failed';\n });\n if (someBlocked) {\n const node = this.graph.nodes.get(taskId);\n if (node) {\n node.status = 'blocked';\n node.updatedAt = Date.now();\n }\n }\n }\n\n /**\n * Fire-and-forget persistence with attached error handler.\n * Synchronous mutators (addNode/addEdge/updateNodeStatus) use this to\n * avoid forcing an async cascade through every caller; if the store\n * is missing or throwing, the error is surfaced via onPersistError.\n */\n private persist(): void {\n if (!this.graph) return;\n this.opts.store.saveGraph(this.graph).catch((err) => {\n this.opts.onPersistError\n ? this.opts.onPersistError(err)\n : console.warn(JSON.stringify({\n level: 'warn',\n event: 'task_tracker.save_graph_failed',\n message: toErrorMessage(err),\n timestamp: new Date().toISOString(),\n }));\n });\n }\n}\n\n// Sort comparison helpers\nconst PRIORITY_RANK: Record<TaskNode['priority'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n};\nconst STATUS_RANK: Record<TaskNode['status'], number> = {\n in_progress: 0,\n pending: 1,\n review: 2,\n blocked: 3,\n failed: 4,\n completed: 5,\n};\n\nfunction compareByField(a: TaskNode, b: TaskNode, field: TaskSort['field']): number {\n switch (field) {\n case 'priority': return PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority];\n case 'status': return STATUS_RANK[a.status] - STATUS_RANK[b.status];\n case 'createdAt': return a.createdAt - b.createdAt;\n case 'updatedAt': return a.updatedAt - b.updatedAt;\n }\n}\n","import type { EventBus } from '../kernel/events.js';\nimport type { DoneCondition } from '../types/multi-agent.js';\nimport type { SpecAnalysis, Specification } from '../types/spec.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { SpecParser } from './spec-parser.js';\nimport { DefaultTaskStore, TaskGenerator } from './task-generator.js';\nimport { TaskTracker } from './task-tracker.js';\n\n/**\n * Extended event map used internally by TaskFlow and multi-agent components.\n * These events are emitted on the injected EventBus and are a subset of\n * the full EventMap — they do not require a separate registration.\n */\nexport interface TaskFlowEventMap {\n 'phase.change': { from: TaskFlowPhase; to: TaskFlowPhase };\n 'task.started': { taskId: string };\n 'task.completed': { taskId: string; result?: unknown | undefined };\n 'task.failed': { taskId: string; error: string };\n 'task.review': { taskId: string };\n 'spec.analyzed': { analysis: SpecAnalysis };\n progress: { percent: number; message: string };\n done: { graph: TaskGraph };\n error: { phase: TaskFlowPhase; error: Error };\n}\n\nexport type TaskFlowPhase =\n | 'idle'\n | 'parsing'\n | 'analyzing'\n | 'generating'\n | 'executing'\n | 'reviewing'\n | 'completing'\n | 'done'\n | 'failed';\n\nexport type TaskFlowEventName = keyof TaskFlowEventMap;\n\nexport interface TaskFlowOptions {\n tracker: TaskTracker;\n events: EventBus;\n doneCondition?: DoneCondition | undefined;\n maxConcurrent?: number | undefined;\n}\n\nexport interface TaskFlowExecutionContext {\n executeTask: (task: TaskNode) => Promise<unknown>;\n onTaskComplete?: (task: TaskNode | undefined, result: unknown) => void;\n onTaskFail?: (task: TaskNode | undefined, error: Error) => void;\n}\n\nexport class TaskFlow {\n private phase: TaskFlowPhase = 'idle';\n private spec: Specification | null = null;\n private graph: TaskGraph | null = null;\n private stopped = false;\n\n constructor(private readonly opts: TaskFlowOptions) {\n this.setPhase('idle');\n }\n\n private emit<K extends TaskFlowEventName>(event: K, payload: TaskFlowEventMap[K]): void {\n (this.opts.events.emit as (event: string, payload: unknown) => void)(event, payload);\n }\n\n async fromSpec(specContent: string): Promise<TaskGraph> {\n this.setPhase('parsing');\n\n const parser = new SpecParser();\n this.spec = parser.parse(specContent);\n\n this.setPhase('analyzing');\n const analysis = parser.analyze(this.spec);\n this.emit('spec.analyzed', { analysis });\n\n if (analysis.completeness < 50) {\n const err = new SddError({\n message: `Spec completeness too low: ${analysis.completeness}%`,\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\n context: { completeness: analysis.completeness },\n });\n this.emit('error', { phase: 'analyzing', error: err });\n this.setPhase('failed');\n throw err;\n }\n\n this.setPhase('generating');\n const generator = new TaskGenerator({ taskTracker: this.opts.tracker });\n this.graph = await generator.generateFromSpec(this.spec);\n\n return this.graph;\n }\n\n async execute(ctx: TaskFlowExecutionContext): Promise<TaskGraph> {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded. Call fromSpec first.',\n code: ERROR_CODES.SDD_INVALID_STATE,\n context: { phase: this.phase },\n });\n\n this.setPhase('executing');\n this.stopped = false;\n\n const pendingTasks = this.getExecutableTasks();\n const maxConcurrent = this.opts.maxConcurrent ?? 2;\n\n while (pendingTasks.length > 0 && !this.stopped) {\n const batch = pendingTasks.splice(0, maxConcurrent);\n const results = await Promise.allSettled(\n batch.map((task) => this.executeSingleTask(task, ctx)),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const task = batch[i];\n\n if (!result || !task) continue;\n\n if (result.status === 'rejected') {\n const reason = result.reason as Error | undefined;\n this.opts.tracker.updateNodeStatus(task.id, 'failed', reason?.message);\n this.emit('task.failed', { taskId: task.id, error: reason?.message ?? 'unknown' });\n ctx.onTaskFail?.(task, reason as Error);\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'completed');\n this.emit('task.completed', { taskId: task.id, result: result.value });\n ctx.onTaskComplete?.(task, result.value);\n }\n\n this.emitProgress();\n }\n\n // Re-evaluate pending tasks (some may have become unblocked)\n const stillPending = this.getExecutableTasks();\n pendingTasks.length = 0;\n pendingTasks.push(...stillPending);\n\n // Check done condition\n if (this.checkDoneCondition()) {\n break;\n }\n }\n\n this.setPhase('completing');\n this.emit('done', { graph: this.graph });\n this.setPhase('done');\n\n return this.graph;\n }\n\n async reviewTask(taskId: string, approved: boolean, comment?: string): Promise<void> {\n const task = this.opts.tracker.getNode(taskId);\n if (!task) throw new SddError({\n message: `Task ${taskId} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { taskId },\n });\n\n if (approved) {\n this.opts.tracker.updateNodeStatus(taskId, 'completed', comment);\n this.emit('task.completed', { taskId });\n } else {\n this.opts.tracker.updateNodeStatus(taskId, 'in_progress', comment ?? 'Needs revision');\n this.emit('task.review', { taskId });\n }\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n getPhase(): TaskFlowPhase {\n return this.phase;\n }\n\n getGraph(): TaskGraph | null {\n return this.graph;\n }\n\n getSpec(): Specification | null {\n return this.spec;\n }\n\n private setPhase(phase: TaskFlowPhase): void {\n const from = this.phase;\n this.phase = phase;\n this.emit('phase.change', { from, to: phase });\n }\n\n private getExecutableTasks(): TaskNode[] {\n return this.opts.tracker\n .getAllNodes({ status: ['pending', 'blocked'] })\n .filter((n) => n.status === 'pending' && this.opts.tracker.canStart(n.id))\n .sort((a, b) => {\n const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n return (priorityOrder[a.priority] ?? 4) - (priorityOrder[b.priority] ?? 4);\n });\n }\n\n private async executeSingleTask(task: TaskNode, ctx: TaskFlowExecutionContext): Promise<unknown> {\n this.opts.tracker.updateNodeStatus(task.id, 'in_progress');\n this.emit('task.started', { taskId: task.id });\n return ctx.executeTask(task);\n }\n\n private checkDoneCondition(): boolean {\n const condition = this.opts.doneCondition;\n if (!condition) {\n const progress = this.opts.tracker.getProgress();\n return progress.percentComplete === 100;\n }\n\n switch (condition.type) {\n case 'all_tasks_done': {\n const progress = this.opts.tracker.getProgress();\n return progress.pending === 0 && progress.inProgress === 0;\n }\n case 'iterations':\n return false; // Not tracked here\n case 'tool_calls':\n return false;\n default:\n return false;\n }\n }\n\n private emitProgress(): void {\n const progress = this.opts.tracker.getProgress();\n this.emit('progress', {\n percent: progress.percentComplete,\n message: `${progress.completed}/${progress.total} tasks completed`,\n });\n }\n}\n\nexport interface SpecDrivenDevOptions {\n workingDirectory: string;\n events: EventBus;\n doneCondition?: DoneCondition | undefined;\n}\n\nexport class SpecDrivenDev {\n private store: DefaultTaskStore;\n private tracker: TaskTracker;\n private readonly events: EventBus;\n private flows = new Map<string, TaskFlow>();\n\n constructor(opts: SpecDrivenDevOptions) {\n this.store = new DefaultTaskStore();\n this.tracker = new TaskTracker({ store: this.store });\n this.events = opts.events;\n }\n\n async createFlow(specContent: string, options?: Partial<TaskFlowOptions>): Promise<TaskFlow> {\n const flow = new TaskFlow({\n tracker: this.tracker,\n events: this.events,\n ...options,\n });\n\n const graph = await flow.fromSpec(specContent);\n this.flows.set(graph.id, flow);\n\n return flow;\n }\n\n getTracker(): TaskTracker {\n return this.tracker;\n }\n\n getFlow(graphId: string): TaskFlow | undefined {\n return this.flows.get(graphId);\n }\n\n listFlows(): { id: string; title: string; phase: TaskFlowPhase }[] {\n return Array.from(this.flows.entries()).map(([id, flow]) => ({\n id,\n title: flow.getGraph()?.title ?? 'Untitled',\n phase: flow.getPhase(),\n }));\n }\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport type { Specification, SpecStatus } from '../types/spec.js';\n\nexport interface SpecStoreOptions {\n /** Directory where spec files are stored. Defaults to `.wrongstack/specs`. */\n baseDir: string;\n}\n\nexport interface SpecIndexEntry {\n id: string;\n title: string;\n version: string;\n status: SpecStatus;\n updatedAt: number;\n filePath: string;\n}\n\ninterface SpecIndex {\n version: 1;\n entries: SpecIndexEntry[];\n}\n\n/**\n * File-backed spec storage. Each spec is a JSON file under `baseDir/`.\n * An index file (`_index.json`) tracks all specs for fast listing.\n */\nexport class SpecStore {\n private readonly baseDir: string;\n private readonly indexPath: string;\n\n constructor(opts: SpecStoreOptions) {\n this.baseDir = opts.baseDir;\n this.indexPath = path.join(this.baseDir, '_index.json');\n }\n\n async save(spec: Specification): Promise<void> {\n await ensureDir(this.baseDir);\n const filePath = this.filePath(spec.id);\n await atomicWrite(filePath, JSON.stringify(spec, null, 2), { mode: 0o600 });\n await this.updateIndex(spec);\n }\n\n async load(id: string): Promise<Specification | null> {\n try {\n const raw = await fsp.readFile(this.filePath(id), 'utf8');\n return JSON.parse(raw) as Specification;\n } catch {\n return null;\n }\n }\n\n async list(): Promise<SpecIndexEntry[]> {\n const index = await this.readIndex();\n return index.entries.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n\n async delete(id: string): Promise<boolean> {\n try {\n await fsp.unlink(this.filePath(id));\n await this.removeFromIndex(id);\n return true;\n } catch {\n return false;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n try {\n await fsp.access(this.filePath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n /** Create a new spec with defaults, assign ID, and persist. */\n async createDraft(title: string, overview?: string): Promise<Specification> {\n const now = Date.now();\n const spec: Specification = {\n id: randomUUID(),\n title,\n version: '0.1.0',\n status: 'draft',\n overview: overview ?? '',\n sections: [],\n requirements: [],\n createdAt: now,\n updatedAt: now,\n };\n await this.save(spec);\n return spec;\n }\n\n /** Update spec fields and persist. */\n async update(id: string, patch: Partial<Omit<Specification, 'id' | 'createdAt'>>): Promise<Specification | null> {\n const spec = await this.load(id);\n if (!spec) return null;\n const updated: Specification = {\n ...spec,\n ...patch,\n id: spec.id,\n createdAt: spec.createdAt,\n updatedAt: Date.now(),\n };\n await this.save(updated);\n return updated;\n }\n\n private filePath(id: string): string {\n return path.join(this.baseDir, `${id}.json`);\n }\n\n private async readIndex(): Promise<SpecIndex> {\n try {\n const raw = await fsp.readFile(this.indexPath, 'utf8');\n const parsed = JSON.parse(raw) as SpecIndex;\n if (parsed?.version === 1) return parsed;\n } catch {\n /* no index yet */\n }\n return { version: 1, entries: [] };\n }\n\n private async updateIndex(spec: Specification): Promise<void> {\n const index = await this.readIndex();\n const entry: SpecIndexEntry = {\n id: spec.id,\n title: spec.title,\n version: spec.version,\n status: spec.status,\n updatedAt: spec.updatedAt,\n filePath: this.filePath(spec.id),\n };\n const idx = index.entries.findIndex((e) => e.id === spec.id);\n if (idx >= 0) {\n index.entries[idx] = entry;\n } else {\n index.entries.push(entry);\n }\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n\n private async removeFromIndex(id: string): Promise<void> {\n const index = await this.readIndex();\n index.entries = index.entries.filter((e) => e.id !== id);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\n\nexport interface TaskGraphStoreOptions {\n /** Directory where task graph files are stored. Defaults to `.wrongstack/task-graphs`. */\n baseDir: string;\n}\n\nexport interface TaskGraphIndexEntry {\n id: string;\n specId: string;\n title: string;\n nodeCount: number;\n completedCount: number;\n updatedAt: number;\n filePath: string;\n}\n\ninterface TaskGraphIndex {\n version: 1;\n entries: TaskGraphIndexEntry[];\n}\n\n/**\n * JSON serialisation helpers for TaskGraph (Map → Array round-trip).\n */\nfunction graphToJSON(graph: TaskGraph): string {\n const serialisable = {\n ...graph,\n nodes: Array.from(graph.nodes.entries()),\n };\n return JSON.stringify(serialisable, null, 2);\n}\n\nfunction graphFromJSON(raw: string): TaskGraph {\n const parsed = JSON.parse(raw) as Omit<TaskGraph, 'nodes'> & { nodes: [string, TaskNode][] };\n return {\n ...parsed,\n nodes: new Map(parsed.nodes),\n };\n}\n\n/**\n * File-backed task graph storage. Each graph is a JSON file under `baseDir/`.\n * An index file (`_index.json`) tracks all graphs for fast listing.\n */\nexport class TaskGraphStore {\n private readonly baseDir: string;\n private readonly indexPath: string;\n\n constructor(opts: TaskGraphStoreOptions) {\n this.baseDir = opts.baseDir;\n this.indexPath = path.join(this.baseDir, '_index.json');\n }\n\n async save(graph: TaskGraph): Promise<void> {\n await ensureDir(this.baseDir);\n const filePath = this.filePath(graph.id);\n await atomicWrite(filePath, graphToJSON(graph), { mode: 0o600 });\n await this.updateIndex(graph);\n }\n\n async load(id: string): Promise<TaskGraph | null> {\n try {\n const raw = await fsp.readFile(this.filePath(id), 'utf8');\n return graphFromJSON(raw);\n } catch {\n return null;\n }\n }\n\n async list(): Promise<TaskGraphIndexEntry[]> {\n const index = await this.readIndex();\n return index.entries.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n\n async delete(id: string): Promise<boolean> {\n try {\n await fsp.unlink(this.filePath(id));\n await this.removeFromIndex(id);\n return true;\n } catch {\n return false;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n try {\n await fsp.access(this.filePath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n private filePath(id: string): string {\n return path.join(this.baseDir, `${id}.json`);\n }\n\n private async readIndex(): Promise<TaskGraphIndex> {\n try {\n const raw = await fsp.readFile(this.indexPath, 'utf8');\n const parsed = JSON.parse(raw) as TaskGraphIndex;\n if (parsed?.version === 1) return parsed;\n } catch {\n /* no index yet */\n }\n return { version: 1, entries: [] };\n }\n\n private async updateIndex(graph: TaskGraph): Promise<void> {\n const index = await this.readIndex();\n const completedCount = Array.from(graph.nodes.values()).filter(\n (n) => n.status === 'completed',\n ).length;\n const entry: TaskGraphIndexEntry = {\n id: graph.id,\n specId: graph.specId,\n title: graph.title,\n nodeCount: graph.nodes.size,\n completedCount,\n updatedAt: graph.updatedAt,\n filePath: this.filePath(graph.id),\n };\n const idx = index.entries.findIndex((e) => e.id === graph.id);\n if (idx >= 0) {\n index.entries[idx] = entry;\n } else {\n index.entries.push(entry);\n }\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n\n private async removeFromIndex(id: string): Promise<void> {\n const index = await this.readIndex();\n index.entries = index.entries.filter((e) => e.id !== id);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n}\n","import { expectDefined } from '../utils/expect-defined.js';\r\nimport { toErrorMessage } from '../utils/error.js';\nimport type { Specification, SpecRequirement, SpecSection } from '../types/spec.js';\r\nimport type { SpecStore } from './spec-store.js';\r\nimport { SddError, ERROR_CODES } from '../types/errors.js';\r\n\r\n// ─── Session Types ────────────────────────────────────────────────────────────\r\n\r\nexport type AISpecPhase =\r\n | 'questioning' // AI is asking questions\r\n | 'spec_review' // Spec generated, waiting for user approval\r\n | 'implementation' // Implementation plan phase\r\n | 'task_review' // Tasks generated, waiting for execution\r\n | 'executing' // Running tasks\r\n | 'done'; // Everything complete\r\n\r\nexport interface CollectedAnswer {\r\n question: string;\r\n answer: string;\r\n timestamp: number;\r\n}\r\n\r\nexport interface AISpecSession {\r\n id: string;\r\n phase: AISpecPhase;\r\n title: string;\r\n userIntent: string;\r\n projectContext: string;\r\n answers: CollectedAnswer[];\r\n questionCount: number;\r\n spec?: Specification | undefined;\r\n implementation?: string | undefined;\r\n taskGraphId?: string | undefined;\r\n approved: boolean;\r\n createdAt: number;\r\n updatedAt: number;\r\n}\r\n\r\n// ─── Builder Options ──────────────────────────────────────────────────────────\r\n\r\nexport interface AISpecBuilderOptions {\r\n store: SpecStore;\r\n /** Minimum questions the AI should ask. Default: 2 */\r\n minQuestions?: number | undefined;\r\n /** Maximum questions before forcing spec generation. Default: 10 */\r\n maxQuestions?: number | undefined;\r\n /** Project context string (package.json, file structure, etc.) */\r\n projectContext?: string | undefined;\r\n /** Path to persist session state. If set, session survives process restarts. */\r\n sessionPath?: string | undefined;\r\n}\r\n\r\n// ─── AI Prompts ───────────────────────────────────────────────────────────────\r\n\r\nfunction buildQuestioningPrompt(session: AISpecSession, min: number, max: number): string {\r\n const answered = session.answers.length;\r\n const remaining = Math.max(0, min - answered);\r\n const budget = max - answered;\r\n\r\n const lines: string[] = [\r\n `═══ SDD Spec Builder ═══`,\r\n `Feature: \"${session.title}\"`,\r\n session.userIntent ? `Intent: ${session.userIntent}` : '',\r\n `Phase: Questioning (${answered} answered, ${budget} remaining budget)`,\r\n '',\r\n '**Instructions for AI:**',\r\n '',\r\n 'You are conducting a specification interview. Your job is to ask the user',\r\n 'intelligent, contextual questions to understand what they want to build.',\r\n '',\r\n `You have asked ${answered} questions so far.`,\r\n ];\r\n\r\n if (remaining > 0) {\r\n lines.push(`You MUST ask at least ${remaining} more question(s) before generating the spec.`);\r\n } else if (budget <= 0) {\r\n lines.push('You have reached the maximum question budget. Generate the spec NOW.');\r\n } else {\r\n lines.push(\r\n 'You may ask more questions if needed, or generate the spec if you have enough information.',\r\n 'Ask a question ONLY if it reveals something you genuinely need to know.',\r\n );\r\n }\r\n\r\n lines.push(\r\n '',\r\n '**Rules:**',\r\n '- Ask ONE question at a time',\r\n '- Questions must be specific and contextual — never generic',\r\n '- Adapt based on previous answers',\r\n '- Cover: scope, constraints, edge cases, integrations, security, performance as relevant',\r\n '- When you have enough info, respond with the full specification in JSON format',\r\n '',\r\n `**Question budget:** ${budget}/${max} remaining`,\r\n `**Minimum required:** ${remaining > 0 ? remaining : 'met'}`,\r\n );\r\n\r\n if (session.projectContext) {\r\n lines.push('', '**Project Context:**', '```', session.projectContext, '```');\r\n }\r\n\r\n if (answered > 0) {\r\n lines.push('', '**Conversation so far:**');\r\n for (let i = 0; i < answered; i++) {\r\n const a = expectDefined(session.answers[i]);\r\n lines.push(``, `Q${i + 1}: ${a.question}`, `A${i + 1}: ${a.answer}`);\r\n }\r\n }\r\n\r\n lines.push(\r\n '',\r\n '---',\r\n 'Now either:',\r\n `1. Ask your next question (if you need more info)`,\r\n `2. Generate the complete specification as JSON (if ready)`,\r\n '',\r\n 'If generating spec, output JSON inside ```json code block with this structure:',\r\n '```json',\r\n '{',\r\n ' \"title\": \"...\",',\r\n ' \"overview\": \"...\",',\r\n ' \"sections\": [{ \"type\": \"overview|requirements|architecture|api|data|security|acceptance\", \"title\": \"...\", \"content\": \"...\", \"level\": 1 }],',\r\n ' \"requirements\": [{ \"id\": \"REQ-1\", \"type\": \"functional|non-functional|security|performance|ux\", \"priority\": \"critical|high|medium|low\", \"description\": \"...\", \"acceptanceCriteria\": [\"...\"] }]',\r\n '}',\r\n '```',\r\n );\r\n\r\n return lines.filter(Boolean).join('\\n');\r\n}\r\n\r\nfunction buildSpecReviewPrompt(session: AISpecSession): string {\r\n const spec = session.spec;\r\n if (!spec) return 'No spec generated yet.';\r\n\r\n const reqSummary = spec.requirements\r\n .map((r) => ` [${r.priority}] ${r.description}`)\r\n .join('\\n');\r\n\r\n return [\r\n `═══ Spec Review ═══`,\r\n `Feature: \"${spec.title}\"`,\r\n `Requirements: ${spec.requirements.length}`,\r\n '',\r\n '**Specification:**',\r\n spec.overview,\r\n '',\r\n '**Requirements:**',\r\n reqSummary,\r\n '',\r\n '---',\r\n 'Approve this spec? The AI will then generate an implementation plan and tasks.',\r\n 'Say \"approve\" to proceed, or describe what needs to change.',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildImplementationPrompt(session: AISpecSession): string {\r\n const spec = session.spec;\r\n if (!spec) return 'No spec to implement.';\r\n\r\n const reqList = spec.requirements\r\n .map((r) => ` - [${r.priority}] ${r.description}`)\r\n .join('\\n');\r\n\r\n return [\r\n `═══ Implementation Planning ═══`,\r\n `Feature: \"${spec.title}\"`,\r\n `Requirements: ${spec.requirements.length}`,\r\n '',\r\n '**Requirements to implement:**',\r\n reqList,\r\n '',\r\n '**Instructions for AI:**',\r\n 'Generate a detailed implementation plan for this specification.',\r\n 'Include:',\r\n '1. Architecture decisions',\r\n '2. File structure changes',\r\n '3. Key implementation details',\r\n '4. Dependency requirements',\r\n '5. Testing strategy',\r\n '',\r\n '**IMPORTANT:** After the plan, you MUST generate executable tasks as a JSON array.',\r\n 'Each task should be a concrete, actionable step. Output the JSON inside a ```json code block:',\r\n '```json',\r\n '[',\r\n ' {',\r\n ' \"title\": \"Create auth middleware\",',\r\n ' \"description\": \"Implement JWT verification middleware for protected routes\",',\r\n ' \"type\": \"feature\",',\r\n ' \"priority\": \"critical\",',\r\n ' \"estimateHours\": 3,',\r\n ' \"tags\": [\"auth\", \"middleware\"]',\r\n ' },',\r\n ' {',\r\n ' \"title\": \"Write auth tests\",',\r\n ' \"description\": \"Unit and integration tests for authentication flow\",',\r\n ' \"type\": \"test\",',\r\n ' \"priority\": \"high\",',\r\n ' \"estimateHours\": 2,',\r\n ' \"tags\": [\"test\", \"auth\"]',\r\n ' }',\r\n ']',\r\n '```',\r\n '',\r\n 'Rules:',\r\n '- Each task must be independently executable',\r\n '- Order tasks by dependency (things that block others come first)',\r\n '- Use type: \"feature\" for code, \"test\" for tests, \"docs\" for documentation, \"chore\" for config',\r\n '- Use priority: \"critical\" for blockers, \"high\" for core features, \"medium\" for nice-to-haves, \"low\" for polish',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildTaskReviewPrompt(session: AISpecSession): string {\r\n return [\r\n `═══ Task Review ═══`,\r\n `Feature: \"${session.spec?.title ?? session.title}\"`,\r\n '',\r\n session.implementation ?? 'No implementation plan yet.',\r\n '',\r\n '---',\r\n 'Ready to execute these tasks? Say \"execute\" to begin, or describe changes needed.',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildExecutingPrompt(session: AISpecSession): string {\r\n return [\r\n `═══ Task Execution ═══`,\r\n `Feature: \"${session.spec?.title ?? session.title}\"`,\r\n '',\r\n '**Instructions for AI:**',\r\n 'Execute the tasks one by one in the order shown in the task list above.',\r\n '',\r\n 'For each task:',\r\n '1. Implement the code (create/modify files)',\r\n '2. Write tests if applicable',\r\n '3. After completing a task, tell the user to run: /sdd done <task number or title>',\r\n '4. Then move to the next task',\r\n '',\r\n '**Important:**',\r\n '- Focus on ONE task at a time',\r\n '- After completing each task, explicitly state what you did',\r\n '- Tell the user: \"Run /sdd done <N> to mark this task complete\"',\r\n '- Then proceed to the next task automatically',\r\n '- When ALL tasks are done, provide a summary of everything implemented',\r\n '',\r\n 'Start executing the first pending task now.',\r\n ].join('\\n');\r\n}\r\n\r\n// ─── Spec Builder Class ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * AI-driven specification builder. Instead of static questions, this builder\r\n * tracks conversation state and generates prompts that instruct the AI agent\r\n * to ask contextual questions and build specifications interactively.\r\n */\r\nexport class AISpecBuilder {\r\n private session: AISpecSession;\r\n private readonly store: SpecStore;\r\n private readonly minQuestions: number;\r\n private readonly maxQuestions: number;\r\n private readonly sessionPath?: string | undefined;\r\n\r\n constructor(opts: AISpecBuilderOptions) {\r\n this.store = opts.store;\r\n this.minQuestions = opts.minQuestions ?? 2;\r\n this.maxQuestions = opts.maxQuestions ?? 10;\r\n this.sessionPath = opts.sessionPath;\r\n this.session = {\r\n id: crypto.randomUUID(),\r\n phase: 'questioning',\r\n title: '',\r\n userIntent: '',\r\n projectContext: opts.projectContext ?? '',\r\n answers: [],\r\n questionCount: 0,\r\n approved: false,\r\n createdAt: Date.now(),\r\n updatedAt: Date.now(),\r\n };\r\n }\r\n\r\n // ── Session Persistence ──────────────────────────────────────────────────\r\n\r\n /** Save session state to disk. */\r\n async saveSession(): Promise<void> {\r\n if (!this.sessionPath) return;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n const path = await import('node:path');\r\n const { atomicWrite } = await import('../utils/atomic-write.js');\r\n await fsp.mkdir(path.dirname(this.sessionPath), { recursive: true });\r\n // atomicWrite: torn save would corrupt the SDD session JSON and the\r\n // next load would silently fall back to a fresh session.\r\n await atomicWrite(this.sessionPath, JSON.stringify(this.session, null, 2));\r\n } catch {\r\n // Best-effort persistence — don't crash if save fails\r\n }\r\n }\r\n\r\n /** Load session state from disk. Returns true if a session was loaded. */\r\n async loadSession(): Promise<boolean> {\r\n if (!this.sessionPath) return false;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n const raw = await fsp.readFile(this.sessionPath, 'utf8');\r\n const loaded = JSON.parse(raw) as AISpecSession;\r\n // Validate basic structure\r\n if (loaded?.id && loaded?.phase && loaded?.title) {\r\n this.session = loaded;\r\n return true;\r\n }\r\n } catch {\r\n // No saved session or invalid file\r\n }\r\n return false;\r\n }\r\n\r\n /** Delete saved session from disk. */\r\n async deleteSession(): Promise<void> {\r\n if (!this.sessionPath) return;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n await fsp.unlink(this.sessionPath);\r\n } catch {\r\n // File might not exist\r\n }\r\n }\r\n\r\n /** Auto-save helper — calls saveSession() but never throws.\r\n * Failures are surfaced via process.emitWarning so a persistent\r\n * ENOSPC / EACCES doesn't silently strand session edits in memory. */\r\n private autoSave(): void {\r\n this.saveSession().catch((err) => {\r\n const detail = toErrorMessage(err);\r\n process.emitWarning(\r\n `SpecBuilder autoSave failed: ${detail}`,\r\n 'SpecBuilderWarning',\r\n );\r\n });\r\n }\r\n\r\n // ── Session Lifecycle ─────────────────────────────────────────────────────\r\n\r\n /** Start a new session with a title and optional intent. */\r\n startSession(title: string, intent?: string): void {\r\n this.session.title = title;\r\n this.session.userIntent = intent ?? '';\r\n this.session.phase = 'questioning';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /** Get current session state (readonly). */\r\n getSession(): Readonly<AISpecSession> {\r\n return { ...this.session };\r\n }\r\n\r\n /** Get the current phase. */\r\n getPhase(): AISpecPhase {\r\n return this.session.phase;\r\n }\r\n\r\n // ── AI Prompt Generation ──────────────────────────────────────────────────\r\n\r\n /**\r\n * Get the AI prompt for the current phase.\r\n * This prompt is injected into the conversation so the AI agent knows\r\n * what to do next (ask a question, generate a spec, etc.).\r\n */\r\n getAIPrompt(): string {\r\n switch (this.session.phase) {\r\n case 'questioning':\r\n return buildQuestioningPrompt(this.session, this.minQuestions, this.maxQuestions);\r\n case 'spec_review':\r\n return buildSpecReviewPrompt(this.session);\r\n case 'implementation':\r\n return buildImplementationPrompt(this.session);\r\n case 'task_review':\r\n return buildTaskReviewPrompt(this.session);\r\n case 'executing':\r\n return buildExecutingPrompt(this.session);\r\n case 'done':\r\n return 'All tasks completed. Specification is fully implemented.';\r\n }\r\n }\r\n\r\n // ── Answer Processing ─────────────────────────────────────────────────────\r\n\r\n /**\r\n * Record a question/answer pair from the AI conversation.\r\n * Call this when the AI asks a question and the user responds.\r\n */\r\n addAnswer(question: string, answer: string): void {\r\n this.session.answers.push({ question, answer, timestamp: Date.now() });\r\n this.session.questionCount++;\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Check if more questions should be asked.\r\n * Returns false if max reached or if the AI has signaled it has enough info.\r\n */\r\n shouldContinueQuestioning(): boolean {\r\n return this.session.questionCount < this.maxQuestions;\r\n }\r\n\r\n /**\r\n * Check if minimum questions have been asked.\r\n */\r\n hasMetMinimumQuestions(): boolean {\r\n return this.session.questionCount >= this.minQuestions;\r\n }\r\n\r\n // ── Phase Transitions ─────────────────────────────────────────────────────\r\n\r\n /**\r\n * Set the generated specification and move to spec_review phase.\r\n */\r\n setSpec(spec: Specification): void {\r\n this.session.spec = spec;\r\n this.session.phase = 'spec_review';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Approve the current phase and advance to the next.\r\n * questioning → spec_review (requires spec to be set)\r\n * spec_review → implementation\r\n * implementation → task_review (requires implementation to be set)\r\n * task_review → executing\r\n * executing → done\r\n */\r\n approve(): AISpecPhase {\r\n switch (this.session.phase) {\r\n case 'questioning':\r\n if (!this.session.spec) {\r\n throw new SddError({\r\n message: 'Cannot approve: no spec generated yet.',\r\n code: ERROR_CODES.SDD_INVALID_STATE,\r\n context: { phase: 'questioning', sessionId: this.session.id },\r\n });\r\n }\r\n this.session.phase = 'spec_review';\r\n break;\r\n case 'spec_review':\r\n this.session.phase = 'implementation';\r\n break;\r\n case 'implementation':\r\n this.session.phase = 'task_review';\r\n break;\r\n case 'task_review':\r\n this.session.phase = 'executing';\r\n break;\r\n case 'executing':\r\n this.session.phase = 'done';\r\n break;\r\n case 'done':\r\n break;\r\n }\r\n this.session.approved = true;\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n return this.session.phase;\r\n }\r\n\r\n /**\r\n * Set the implementation plan text.\r\n */\r\n setImplementation(plan: string): void {\r\n this.session.implementation = plan;\r\n this.session.phase = 'task_review';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Mark session as done.\r\n */\r\n markDone(): void {\r\n this.session.phase = 'done';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Set the task graph ID for this session.\r\n */\r\n setTaskGraphId(graphId: string): void {\r\n this.session.taskGraphId = graphId;\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Get the task graph ID for this session.\r\n */\r\n getTaskGraphId(): string | undefined {\r\n return this.session.taskGraphId;\r\n }\r\n\r\n // ── Spec Persistence ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Save the current spec to the store.\r\n */\r\n async saveSpec(): Promise<Specification> {\r\n if (!this.session.spec) {\r\n throw new SddError({\r\n message: 'No spec to save.',\r\n code: ERROR_CODES.SDD_NOT_READY,\r\n context: { sessionId: this.session.id },\r\n });\r\n }\r\n await this.store.save(this.session.spec);\r\n return this.session.spec;\r\n }\r\n\r\n // ── Spec Generation Helpers ───────────────────────────────────────────────\r\n\r\n /**\r\n * Parse a spec from a JSON string (from AI output).\r\n * Validates and normalizes the structure.\r\n */\r\n parseSpecFromJSON(jsonStr: string): Specification {\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(jsonStr);\r\n } catch (e) {\r\n throw new SddError({\r\n message: 'Invalid JSON for spec',\r\n code: ERROR_CODES.SDD_PARSE_FAILED,\r\n cause: e,\r\n context: { detail: e instanceof Error ? e.message : 'parse error' },\r\n });\r\n }\r\n\r\n if (!parsed || typeof parsed !== 'object') {\r\n throw new SddError({\r\n message: 'Spec JSON must be an object',\r\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\r\n context: { actualType: typeof parsed },\r\n });\r\n }\r\n\r\n const raw = parsed as Record<string, unknown>;\r\n const now = Date.now();\r\n\r\n const title = String(raw.title ?? this.session.title ?? 'Untitled');\r\n const overview = String(raw.overview ?? '');\r\n\r\n // Validate overview is not empty\r\n if (!overview || overview === 'undefined') {\r\n throw new SddError({\r\n message: 'Spec must have an overview',\r\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\r\n context: { field: 'overview', title },\r\n });\r\n }\r\n\r\n const rawSections = Array.isArray(raw.sections) ? raw.sections : [];\r\n const sections: SpecSection[] = rawSections\r\n .filter((s: unknown) => s && typeof s === 'object')\r\n .map((s: Record<string, unknown>) => ({\r\n type: (['overview', 'requirements', 'architecture', 'api', 'data', 'security', 'acceptance']\r\n .includes(String(s.type)) ? String(s.type) : 'overview') as SpecSection['type'],\r\n title: String(s.title ?? ''),\r\n content: String(s.content ?? ''),\r\n level: Number(s.level) || 1,\r\n }));\r\n\r\n const rawReqs = Array.isArray(raw.requirements) ? raw.requirements : [];\r\n const requirements: SpecRequirement[] = rawReqs\r\n .filter((r: unknown) => r && typeof r === 'object')\r\n .map((r: Record<string, unknown>, i: number) => ({\r\n id: String(r.id ?? `REQ-${i + 1}`),\r\n type: (['functional', 'non-functional', 'security', 'performance', 'ux']\r\n .includes(String(r.type)) ? String(r.type) : 'functional') as SpecRequirement['type'],\r\n priority: (['critical', 'high', 'medium', 'low']\r\n .includes(String(r.priority)) ? String(r.priority) : 'medium') as SpecRequirement['priority'],\r\n description: String(r.description ?? ''),\r\n acceptanceCriteria: Array.isArray(r.acceptanceCriteria)\r\n ? r.acceptanceCriteria.map(String)\r\n : [],\r\n }));\r\n\r\n const spec: Specification = {\r\n id: crypto.randomUUID(),\r\n title,\r\n version: '0.1.0',\r\n status: 'draft',\r\n overview,\r\n sections,\r\n requirements,\r\n createdAt: now,\r\n updatedAt: now,\r\n metadata: {\r\n generatedBy: 'AISpecBuilder',\r\n sessionId: this.session.id,\r\n },\r\n };\r\n\r\n return spec;\r\n }\r\n\r\n /**\r\n * Extract JSON from AI output (handles ```json blocks and raw JSON).\r\n */\r\n extractJSON(text: string): string | null {\r\n // Try ```json ... ``` first\r\n const codeBlockMatch = text.match(/```json\\s*([\\s\\S]*?)```/);\r\n if (codeBlockMatch?.[1]) {\r\n return codeBlockMatch[1].trim();\r\n }\r\n\r\n // Try ``` ... ``` without language tag\r\n const genericBlockMatch = text.match(/```\\s*([\\s\\S]*?)```/);\r\n if (genericBlockMatch?.[1]) {\r\n const trimmed = genericBlockMatch[1].trim();\r\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\r\n return trimmed;\r\n }\r\n }\r\n\r\n // Try raw JSON object\r\n const jsonMatch = text.match(/(\\{[\\s\\S]*\\})/);\r\n if (jsonMatch?.[1]) {\r\n try {\r\n JSON.parse(jsonMatch[1]);\r\n return jsonMatch[1];\r\n } catch {\r\n // not valid JSON\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Detect if AI output contains a spec (JSON block).\r\n */\r\n hasSpecInOutput(text: string): boolean {\r\n return this.extractJSON(text) !== null;\r\n }\r\n\r\n /**\r\n * Try to parse a spec from AI output text.\r\n * Returns null if no valid spec found.\r\n */\r\n tryParseSpecFromOutput(text: string): Specification | null {\r\n const json = this.extractJSON(text);\r\n if (!json) return null;\r\n\r\n try {\r\n return this.parseSpecFromJSON(json);\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n // ── JSON Array Extraction (for tasks) ─────────────────────────────────────\r\n\r\n /**\r\n * Extract a JSON array from AI output (for task lists).\r\n */\r\n extractJSONArray(text: string): string | null {\r\n const codeBlockMatch = text.match(/```json\\s*([\\s\\S]*?)```/);\r\n if (codeBlockMatch?.[1]) {\r\n const trimmed = codeBlockMatch[1].trim();\r\n if (trimmed.startsWith('[')) return trimmed;\r\n }\r\n\r\n const arrayMatch = text.match(/(\\[[\\s\\S]*\\])/);\r\n if (arrayMatch?.[1]) {\r\n try {\r\n const parsed = JSON.parse(arrayMatch[1]);\r\n if (Array.isArray(parsed)) return arrayMatch[1];\r\n } catch {\r\n // not valid\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n}\r\n","import type { SpecTemplate } from '../types/spec.js';\n\n/**\n * Built-in spec templates for common development scenarios.\n */\nexport const SPEC_TEMPLATES: SpecTemplate[] = [\n {\n id: 'feature',\n name: 'New Feature',\n description: 'Template for new feature development',\n sections: [\n { type: 'overview', title: 'Overview', level: 2 },\n { type: 'requirements', title: 'Requirements', level: 2 },\n { type: 'architecture', title: 'Architecture', level: 2 },\n { type: 'api', title: 'API Design', level: 2 },\n { type: 'data', title: 'Data Model', level: 2 },\n { type: 'security', title: 'Security', level: 2 },\n { type: 'acceptance', title: 'Acceptance Criteria', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'non-functional', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'bugfix',\n name: 'Bug Fix',\n description: 'Template for bug fix specifications',\n sections: [\n { type: 'overview', title: 'Bug Description', level: 2 },\n { type: 'requirements', title: 'Root Cause Analysis', level: 2 },\n { type: 'acceptance', title: 'Fix Verification', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'critical', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'refactor',\n name: 'Refactor',\n description: 'Template for code refactoring',\n sections: [\n { type: 'overview', title: 'Current State', level: 2 },\n { type: 'requirements', title: 'Refactoring Goals', level: 2 },\n { type: 'architecture', title: 'Target Architecture', level: 2 },\n { type: 'acceptance', title: 'Verification', level: 2 },\n ],\n defaultRequirements: [\n { type: 'non-functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'infra',\n name: 'Infrastructure',\n description: 'Template for infrastructure/tooling changes',\n sections: [\n { type: 'overview', title: 'What and Why', level: 2 },\n { type: 'requirements', title: 'Requirements', level: 2 },\n { type: 'architecture', title: 'Design', level: 2 },\n { type: 'security', title: 'Security Impact', level: 2 },\n { type: 'acceptance', title: 'Rollout Plan', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'security', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'integration',\n name: 'Integration',\n description: 'Template for integrating external services or APIs',\n sections: [\n { type: 'overview', title: 'Integration Overview', level: 2 },\n { type: 'requirements', title: 'Integration Requirements', level: 2 },\n { type: 'api', title: 'API Contract', level: 2 },\n { type: 'architecture', title: 'Architecture', level: 2 },\n { type: 'security', title: 'Auth & Security', level: 2 },\n { type: 'acceptance', title: 'Testing Strategy', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'security', priority: 'critical', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'performance', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'cli-command',\n name: 'CLI Command',\n description: 'Template for new CLI commands/slash commands',\n sections: [\n { type: 'overview', title: 'Command Overview', level: 2 },\n { type: 'requirements', title: 'Command Requirements', level: 2 },\n { type: 'api', title: 'Command Interface', level: 2 },\n { type: 'acceptance', title: 'Usage Examples', level: 2 },\n ],\n defaultRequirements: [\n { type: 'ux', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n];\n\n/**\n * Get a template by ID.\n */\nexport function getTemplate(id: string): SpecTemplate | undefined {\n return SPEC_TEMPLATES.find((t) => t.id === id);\n}\n\n/**\n * List all available templates.\n */\nexport function listTemplates(): Array<{ id: string; name: string; description: string }> {\n return SPEC_TEMPLATES.map((t) => ({ id: t.id, name: t.name, description: t.description }));\n}\n\n/**\n * Generate a markdown skeleton from a template.\n */\nexport function templateToMarkdown(template: SpecTemplate, title?: string): string {\n const lines: string[] = [];\n lines.push(`# ${title ?? 'Untitled Specification'}`);\n lines.push('Version: 0.1.0');\n lines.push('');\n\n for (const section of template.sections) {\n lines.push(`${'#'.repeat(section.level + 1)} ${section.title}`);\n lines.push(`_<!-- ${section.type} section content -->_`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import type { TaskGraph, TaskNode, TaskProgress } from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nimport type { Specification } from '../types/spec.js';\nimport { truncate } from '../utils/string.js';\n\nconst STATUS_ICON: Record<TaskNode['status'], string> = {\n pending: '○',\n in_progress: '◐',\n blocked: '⊘',\n failed: '✗',\n review: '◑',\n completed: '●',\n};\n\nconst PRIORITY_ICON: Record<TaskNode['priority'], string> = {\n critical: '🔴',\n high: '🟠',\n medium: '🟡',\n low: '🟢',\n};\n\nconst TYPE_ICON: Record<TaskNode['type'], string> = {\n feature: '⚡',\n bugfix: '🐛',\n refactor: '♻️',\n docs: '📝',\n test: '🧪',\n chore: '🔧',\n};\n\n/**\n * Render a task graph as ASCII art for terminal display.\n */\nexport function renderTaskGraph(graph: TaskGraph, opts?: { compact?: boolean | undefined }): string {\n const lines: string[] = [];\n const compact = opts?.compact ?? false;\n\n // Header\n lines.push(`╭─ Task Graph: ${graph.title} ─╮`);\n lines.push(`│ Spec: ${graph.specId.slice(0, 8)}... │ Nodes: ${graph.nodes.size} │ Edges: ${graph.edges.length} │`);\n lines.push('╰' + '─'.repeat(Math.max(50, graph.title.length + 30)) + '╯');\n lines.push('');\n\n // Progress bar\n const progress = computeTaskProgress(graph);\n lines.push(renderProgress(progress));\n lines.push('');\n\n // Build adjacency for display\n const childrenMap = new Map<string, string[]>();\n for (const edge of graph.edges) {\n if (edge.type === 'depends_on') {\n // edge.from depends on edge.to → edge.to is a blocker\n const deps = childrenMap.get(edge.from) ?? [];\n deps.push(edge.to);\n childrenMap.set(edge.from, deps);\n }\n }\n\n // Render root nodes and their dependents\n const rendered = new Set<string>();\n const rootNodes = graph.rootNodes.filter((id) => graph.nodes.has(id));\n\n // If no root nodes, use all nodes\n const startNodes = rootNodes.length > 0\n ? rootNodes\n : Array.from(graph.nodes.keys()).filter((id) => {\n const deps = childrenMap.get(id);\n return !deps || deps.length === 0;\n });\n\n for (const rootId of startNodes) {\n renderNode(graph, rootId, lines, rendered, childrenMap, compact, '');\n }\n\n // Render any orphan nodes\n for (const [id] of graph.nodes) {\n if (!rendered.has(id)) {\n renderNode(graph, id, lines, rendered, childrenMap, compact, '');\n }\n }\n\n // Legend\n lines.push('');\n lines.push('Legend: ● done ◐ in-progress ○ pending ⊗ blocked ✗ failed ◒ review');\n\n return lines.join('\\n');\n}\n\nfunction renderNode(\n graph: TaskGraph,\n nodeId: string,\n lines: string[],\n rendered: Set<string>,\n childrenMap: Map<string, string[]>,\n compact: boolean,\n prefix: string,\n): void {\n if (rendered.has(nodeId)) return;\n rendered.add(nodeId);\n\n const node = graph.nodes.get(nodeId);\n if (!node) return;\n\n const icon = STATUS_ICON[node.status];\n const prioIcon = PRIORITY_ICON[node.priority];\n const typeIcon = TYPE_ICON[node.type];\n const title = compact ? truncate(node.title, 40) : node.title;\n\n const blockedBy = childrenMap.get(nodeId) ?? [];\n const depsStr = blockedBy.length > 0\n ? ` ← [${blockedBy.map((d) => graph.nodes.get(d)?.title?.slice(0, 12) ?? '?').join(', ')}]`\n : '';\n\n lines.push(`${prefix}${icon} ${typeIcon} ${prioIcon} ${title}${depsStr}`);\n\n if (!compact && node.description) {\n const descLines = node.description.split('\\n').slice(0, 3);\n for (const dl of descLines) {\n lines.push(`${prefix} └ ${truncate(dl, 60)}`);\n }\n }\n\n // Render nodes that depend on this one\n const dependents = graph.edges\n .filter((e) => e.type === 'depends_on' && e.to === nodeId)\n .map((e) => e.from)\n .filter((id) => graph.nodes.has(id));\n\n for (const depId of dependents) {\n renderNode(graph, depId, lines, rendered, childrenMap, compact, prefix + ' ');\n }\n}\n\n/**\n * Render a progress bar.\n */\nexport function renderProgress(progress: TaskProgress): string {\n const barWidth = 30;\n const filled = Math.round((progress.percentComplete / 100) * barWidth);\n const empty = barWidth - filled;\n const bar = '█'.repeat(filled) + '░'.repeat(empty);\n\n return [\n `Progress: [${bar}] ${progress.percentComplete}%`,\n ` ${progress.completed} done │ ${progress.inProgress} active │ ${progress.pending} pending │ ${progress.blocked} blocked │ ${progress.failed} failed`,\n ].join('\\n');\n}\n\n/**\n * Render a compact task list (for quick status checks).\n */\nexport function renderTaskList(graph: TaskGraph): string {\n const lines: string[] = [];\n const nodes = Array.from(graph.nodes.values());\n\n // Group by status\n const groups: Record<string, TaskNode[]> = {\n in_progress: [],\n pending: [],\n blocked: [],\n review: [],\n failed: [],\n completed: [],\n };\n\n for (const node of nodes) {\n groups[node.status]?.push(node);\n }\n\n for (const [status, group] of Object.entries(groups)) {\n if (group.length === 0) continue;\n const icon = STATUS_ICON[status as TaskNode['status']];\n lines.push(`${icon} ${status.toUpperCase()} (${group.length})`);\n for (const node of group) {\n const prio = PRIORITY_ICON[node.priority];\n const type = TYPE_ICON[node.type];\n lines.push(` ${type} ${prio} ${node.title}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render spec analysis summary.\n */\nexport function renderSpecAnalysis(\n spec: Specification,\n analysis: { completeness: number; gaps: string[]; risks: string[]; suggestions: string[] },\n): string {\n const lines: string[] = [];\n\n lines.push(`╭─ Spec Analysis: ${spec.title} ─╮`);\n lines.push('');\n\n // Completeness\n const barWidth = 20;\n const filled = Math.round((analysis.completeness / 100) * barWidth);\n const bar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);\n lines.push(`Completeness: [${bar}] ${analysis.completeness}%`);\n lines.push('');\n\n if (analysis.gaps.length > 0) {\n lines.push('⚠ Gaps:');\n for (const gap of analysis.gaps) {\n lines.push(` • ${gap}`);\n }\n lines.push('');\n }\n\n if (analysis.risks.length > 0) {\n lines.push('🔴 Risks:');\n for (const risk of analysis.risks) {\n lines.push(` • ${risk}`);\n }\n lines.push('');\n }\n\n if (analysis.suggestions.length > 0) {\n lines.push('💡 Suggestions:');\n for (const sug of analysis.suggestions) {\n lines.push(` • ${sug}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n","import { expectDefined } from '../utils/expect-defined.js';\nimport type { TaskGraph } from '../types/task-graph.js';\nimport { topologicalSort } from '../types/task-graph.js';\n/**\n * Enhanced critical path analysis with bottleneck detection,\n * parallel execution groups, and time estimation.\n */\nexport interface CriticalPathAnalysis {\n /** Ordered list of critical path task IDs. */\n criticalPath: string[];\n /** Total estimated hours for the critical path. */\n totalHours: number;\n /** Tasks that block the most downstream work. */\n bottlenecks: BottleneckTask[];\n /** Groups of tasks that can run in parallel. */\n parallelGroups: string[][];\n /** Recommended execution order respecting dependencies. */\n executionOrder: string[];\n /** Tasks with no blockers (can start immediately). */\n readyTasks: string[];\n /** Tasks that are blocked and cannot start. */\n blockedTasks: string[];\n}\n\nexport interface BottleneckTask {\n taskId: string;\n title: string;\n /** Number of tasks directly or transitively blocked by this task. */\n blockedCount: number;\n /** Total estimated hours of blocked downstream work. */\n blockedHours: number;\n /** Severity score (0-100). */\n severity: number;\n}\n\n/**\n * Analyze a task graph and return critical path analysis.\n */\nexport function analyzeCriticalPath(graph: TaskGraph): CriticalPathAnalysis {\n const nodes = Array.from(graph.nodes.values());\n const topoOrder = topologicalSort(graph);\n\n // Build adjacency: blocker → blocked tasks\n const blockedByMap = new Map<string, Set<string>>();\n const blocksMap = new Map<string, Set<string>>();\n\n for (const edge of graph.edges) {\n if (edge.type === 'depends_on') {\n // edge.from depends on edge.to\n if (!blockedByMap.has(edge.from)) blockedByMap.set(edge.from, new Set());\n blockedByMap.get(edge.from)?.add(edge.to);\n\n if (!blocksMap.has(edge.to)) blocksMap.set(edge.to, new Set());\n blocksMap.get(edge.to)?.add(edge.from);\n }\n }\n\n // Find ready tasks (no blockers or all blockers completed)\n const readyTasks: string[] = [];\n const blockedTasks: string[] = [];\n\n for (const node of nodes) {\n if (node.status === 'completed') continue;\n const blockers = blockedByMap.get(node.id);\n if (!blockers || blockers.size === 0) {\n readyTasks.push(node.id);\n } else {\n const allCompleted = Array.from(blockers).every((id) => {\n const n = graph.nodes.get(id);\n return n?.status === 'completed';\n });\n if (allCompleted) {\n readyTasks.push(node.id);\n } else {\n blockedTasks.push(node.id);\n }\n }\n }\n\n // Compute bottleneck scores\n const bottlenecks: BottleneckTask[] = [];\n for (const node of nodes) {\n if (node.status === 'completed') continue;\n const downstream = getTransitiveBlocked(graph, node.id, blocksMap);\n if (downstream.size > 0) {\n const blockedHours = Array.from(downstream).reduce((sum, id) => {\n const n = graph.nodes.get(id);\n return sum + (n?.estimateHours ?? 0);\n }, 0);\n bottlenecks.push({\n taskId: node.id,\n title: node.title,\n blockedCount: downstream.size,\n blockedHours,\n severity: Math.min(100, Math.round((downstream.size / nodes.length) * 100)),\n });\n }\n }\n\n bottlenecks.sort((a, b) => b.severity - a.severity);\n\n // Compute critical path (longest path by estimated hours)\n const criticalPath = computeCriticalPath(graph, topoOrder, blockedByMap);\n\n // Total hours on critical path\n const totalHours = criticalPath.reduce((sum, id) => {\n const n = graph.nodes.get(id);\n return sum + (n?.estimateHours ?? 0);\n }, 0);\n\n // Parallel execution groups\n const parallelGroups = computeParallelGroups(graph, blockedByMap);\n\n // Execution order: topo sort filtered to non-completed tasks\n const executionOrder = topoOrder.filter((id) => {\n const n = graph.nodes.get(id);\n return n && n.status !== 'completed';\n });\n\n return {\n criticalPath,\n totalHours,\n bottlenecks,\n parallelGroups,\n executionOrder,\n readyTasks,\n blockedTasks,\n };\n}\n\n/**\n * Get all tasks transitively blocked by a given task.\n */\nfunction getTransitiveBlocked(\n _graph: TaskGraph,\n taskId: string,\n blocksMap: Map<string, Set<string>>,\n): Set<string> {\n const visited = new Set<string>();\n const queue = [taskId];\n\n while (queue.length > 0) {\n const current = expectDefined(queue.shift());\n const blocked = blocksMap.get(current);\n if (!blocked) continue;\n for (const id of blocked) {\n if (!visited.has(id) && id !== taskId) {\n visited.add(id);\n queue.push(id);\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Compute the critical path (longest path by estimated hours).\n */\nfunction computeCriticalPath(\n graph: TaskGraph,\n _topoOrder: string[],\n blockedByMap: Map<string, Set<string>>,\n): string[] {\n // Use all nodes in the graph, not just topo-reachable ones\n const allIds = Array.from(graph.nodes.keys());\n if (allIds.length === 0) return [];\n\n const dist = new Map<string, number>();\n const prev = new Map<string, string | null>();\n\n // Initialize each node's distance to its own estimate\n for (const id of allIds) {\n dist.set(id, graph.nodes.get(id)?.estimateHours ?? 1);\n prev.set(id, null);\n }\n\n // Build reverse map: blocker → tasks it blocks\n const blocksMap = new Map<string, Set<string>>();\n for (const [taskId, blockers] of blockedByMap) {\n for (const blockerId of blockers) {\n if (!blocksMap.has(blockerId)) blocksMap.set(blockerId, new Set());\n blocksMap.get(blockerId)?.add(taskId);\n }\n }\n\n // Relax edges repeatedly (Bellman-Ford style) since topoOrder may be incomplete.\n // Run N-1 iterations to handle longest path in DAG.\n const n = allIds.length;\n for (let i = 0; i < n - 1; i++) {\n let changed = false;\n for (const id of allIds) {\n const blocked = blocksMap.get(id);\n if (!blocked) continue;\n for (const blockedId of blocked) {\n const candidateDist = (dist.get(id) ?? 0) + (graph.nodes.get(blockedId)?.estimateHours ?? 1);\n if (candidateDist > (dist.get(blockedId) ?? 0)) {\n dist.set(blockedId, candidateDist);\n prev.set(blockedId, id);\n changed = true;\n }\n }\n }\n if (!changed) break;\n }\n\n // Find the node with maximum distance (end of critical path)\n let maxDist = 0;\n let maxId = expectDefined(allIds[0]);\n for (const id of allIds) {\n const d = dist.get(id) ?? 0;\n if (d > maxDist) {\n maxDist = d;\n maxId = id;\n }\n }\n\n // Trace back the critical path\n const path: string[] = [];\n let current: string | null = maxId;\n const visited = new Set<string>();\n while (current && !visited.has(current)) {\n visited.add(current);\n path.unshift(current);\n current = prev.get(current) ?? null;\n }\n\n return path;\n}\n\n/**\n * Compute groups of tasks that can run in parallel.\n * Tasks in the same group have no dependencies on each other.\n */\nfunction computeParallelGroups(\n graph: TaskGraph,\n blockedByMap: Map<string, Set<string>>,\n): string[][] {\n const groups: string[][] = [];\n const assigned = new Set<string>();\n const nodes = Array.from(graph.nodes.values()).filter((n) => n.status !== 'completed');\n\n // Topological levels\n const remaining = new Set(nodes.map((n) => n.id));\n\n while (remaining.size > 0) {\n const group: string[] = [];\n for (const id of remaining) {\n const blockers = blockedByMap.get(id);\n if (!blockers || blockers.size === 0) {\n group.push(id);\n } else {\n const allAssigned = Array.from(blockers).every((b) => assigned.has(b));\n if (allAssigned) {\n group.push(id);\n }\n }\n }\n\n if (group.length === 0) {\n // Circular dependency or all remaining are blocked by non-completed\n // Just take the first remaining\n const first = Array.from(remaining)[0];\n if (first) group.push(first);\n }\n\n for (const id of group) {\n assigned.add(id);\n remaining.delete(id);\n }\n groups.push(group);\n }\n\n return groups;\n}\n","import type { Specification, SpecRequirement } from '../types/spec.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { assertNever } from '../utils/assert-never.js';\n\nexport interface SpecVersion {\n version: string;\n spec: Specification;\n timestamp: number;\n changeDescription?: string | undefined;\n}\n\nexport interface SpecDiff {\n added: SpecRequirement[];\n removed: SpecRequirement[];\n modified: Array<{\n requirement: SpecRequirement;\n previousVersion: SpecRequirement;\n changes: string[];\n }>;\n summary: string;\n}\n\n/**\n * Track spec versions and compute diffs between versions.\n */\nexport class SpecVersioning {\n private versions = new Map<string, SpecVersion[]>();\n\n /** Record a new version of a spec. */\n recordVersion(spec: Specification, changeDescription?: string): SpecVersion {\n const version: SpecVersion = {\n version: spec.version,\n spec: { ...spec },\n timestamp: Date.now(),\n changeDescription,\n };\n\n const history = this.versions.get(spec.id) ?? [];\n history.push(version);\n this.versions.set(spec.id, history);\n\n return version;\n }\n\n /** Get version history for a spec. */\n getHistory(specId: string): SpecVersion[] {\n return this.versions.get(specId) ?? [];\n }\n\n /** Get a specific version of a spec. */\n getVersion(specId: string, version: string): SpecVersion | undefined {\n const history = this.versions.get(specId) ?? [];\n return history.find((v) => v.version === version);\n }\n\n /** Get the latest version of a spec. */\n getLatest(specId: string): SpecVersion | undefined {\n const history = this.versions.get(specId) ?? [];\n return history[history.length - 1];\n }\n\n /** Compute diff between two versions of a spec. */\n diff(oldSpec: Specification, newSpec: Specification): SpecDiff {\n const oldReqs = new Map(oldSpec.requirements.map((r) => [r.id, r]));\n const newReqs = new Map(newSpec.requirements.map((r) => [r.id, r]));\n\n const added: SpecRequirement[] = [];\n const removed: SpecRequirement[] = [];\n const modified: SpecDiff['modified'] = [];\n\n // Find added and modified\n for (const [id, newReq] of newReqs) {\n const oldReq = oldReqs.get(id);\n if (!oldReq) {\n added.push(newReq);\n } else {\n const changes = this.compareRequirements(oldReq, newReq);\n if (changes.length > 0) {\n modified.push({\n requirement: newReq,\n previousVersion: oldReq,\n changes,\n });\n }\n }\n }\n\n // Find removed\n for (const [id, oldReq] of oldReqs) {\n if (!newReqs.has(id)) {\n removed.push(oldReq);\n }\n }\n\n const parts: string[] = [];\n if (added.length > 0) parts.push(`${added.length} added`);\n if (removed.length > 0) parts.push(`${removed.length} removed`);\n if (modified.length > 0) parts.push(`${modified.length} modified`);\n\n return {\n added,\n removed,\n modified,\n summary: parts.length > 0 ? parts.join(', ') : 'No changes',\n };\n }\n\n /**\n * Update a task graph incrementally based on spec changes.\n * - Added requirements → new tasks\n * - Removed requirements → remove tasks\n * - Modified requirements → update task descriptions\n * Returns the updated graph and list of changes made.\n */\n updateTaskGraph(\n graph: TaskGraph,\n oldSpec: Specification,\n newSpec: Specification,\n ): { graph: TaskGraph; changes: string[] } {\n const specDiff = this.diff(oldSpec, newSpec);\n const changes: string[] = [];\n\n // Map requirement IDs to task nodes\n const reqToTask = new Map<string, TaskNode>();\n for (const node of graph.nodes.values()) {\n if (node.specRequirementId) {\n reqToTask.set(node.specRequirementId, node);\n }\n }\n\n // Remove tasks for removed requirements\n for (const req of specDiff.removed) {\n const task = reqToTask.get(req.id);\n if (task) {\n graph.nodes.delete(task.id);\n graph.edges = graph.edges.filter((e) => e.from !== task.id && e.to !== task.id);\n changes.push(`Removed task: ${task.title}`);\n }\n }\n\n // Update tasks for modified requirements\n for (const mod of specDiff.modified) {\n const task = reqToTask.get(mod.requirement.id);\n if (task) {\n task.title = mod.requirement.description;\n task.description = this.buildTaskDescription(mod.requirement);\n task.priority = mod.requirement.priority;\n task.updatedAt = Date.now();\n changes.push(`Updated task: ${task.title} (${mod.changes.join(', ')})`);\n }\n }\n\n // Add tasks for new requirements\n for (const req of specDiff.added) {\n const now = Date.now();\n const newTask: TaskNode = {\n id: crypto.randomUUID(),\n title: req.description,\n description: this.buildTaskDescription(req),\n type: this.mapReqType(req.type),\n priority: req.priority,\n status: 'pending',\n specRequirementId: req.id,\n tags: [req.type, req.priority],\n createdAt: now,\n updatedAt: now,\n };\n graph.nodes.set(newTask.id, newTask);\n graph.rootNodes.push(newTask.id);\n changes.push(`Added task: ${newTask.title}`);\n }\n\n graph.updatedAt = Date.now();\n return { graph, changes };\n }\n\n private compareRequirements(old: SpecRequirement, current: SpecRequirement): string[] {\n const changes: string[] = [];\n if (old.description !== current.description) changes.push('description');\n if (old.priority !== current.priority) changes.push('priority');\n if (old.type !== current.type) changes.push('type');\n if (JSON.stringify(old.acceptanceCriteria) !== JSON.stringify(current.acceptanceCriteria)) {\n changes.push('acceptance criteria');\n }\n if (JSON.stringify(old.blockedBy) !== JSON.stringify(current.blockedBy)) {\n changes.push('dependencies');\n }\n return changes;\n }\n\n private buildTaskDescription(req: SpecRequirement): string {\n const lines = [req.description, '', `**Type:** ${req.type}`, `**Priority:** ${req.priority}`];\n if (req.acceptanceCriteria.length > 0) {\n lines.push('', '**Acceptance Criteria:**');\n for (const ac of req.acceptanceCriteria) {\n lines.push(`- ${ac}`);\n }\n }\n return lines.join('\\n');\n }\n\n private mapReqType(type: SpecRequirement['type']): TaskNode['type'] {\n switch (type) {\n case 'functional':\n return 'feature';\n case 'non-functional':\n return 'feature';\n case 'security':\n return 'feature';\n case 'performance':\n return 'feature';\n case 'ux':\n return 'feature';\n default:\n return assertNever(type);\n }\n }\n}\n","import type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport type { Specification } from '../types/spec.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport { analyzeCriticalPath } from './critical-path.js';\n\nexport interface AutoExecutorOptions {\n tracker: TaskTracker;\n events: EventBus;\n /** Maximum concurrent tasks. Defaults to 1 (sequential). */\n maxConcurrent?: number | undefined;\n /** Maximum retry attempts for failed tasks. */\n maxRetries?: number | undefined;\n /** Custom task executor function. */\n executeTask: (task: TaskNode, context: TaskExecutionContext) => Promise<TaskExecutionResult>;\n /** Called before each task starts. */\n onTaskStart?: (((task: TaskNode) => void)) | undefined;\n /** Called after each task completes. */\n onTaskComplete?: (task: TaskNode, result: TaskExecutionResult) => void;\n /** Called when a task fails. */\n onTaskFail?: (task: TaskNode, error: Error, retryCount: number) => void;\n /** Called when all tasks are done or no more can execute. */\n onDone?: (((summary: ExecutionSummary) => void)) | undefined;\n}\n\nexport interface TaskExecutionContext {\n /** The spec being implemented. */\n spec: Specification;\n /** The full task graph. */\n graph: TaskGraph;\n /** The current task being executed. */\n task: TaskNode;\n /** Tasks that this task depends on. */\n dependencies: TaskNode[];\n /** Tasks that depend on this task. */\n dependents: TaskNode[];\n /** Retry count for this task (0 = first attempt). */\n retryCount: number;\n}\n\nexport interface TaskExecutionResult {\n success: boolean;\n output?: string | undefined;\n error?: string | undefined;\n /** If true, the task will be retried. */\n retry?: boolean | undefined;\n}\n\nexport interface ExecutionSummary {\n total: number;\n completed: number;\n failed: number;\n skipped: number;\n retried: number;\n duration: number;\n criticalPath: string[];\n}\n\n/**\n * Auto-executor that drives task execution with dependency resolution,\n * retry logic, and critical path awareness.\n */\nexport class AutoExecutor {\n private readonly opts: AutoExecutorOptions;\n private stopped = false;\n private retryMap = new Map<string, number>();\n\n constructor(opts: AutoExecutorOptions) {\n this.opts = opts;\n }\n\n /**\n * Execute all tasks in the graph, respecting dependencies.\n */\n async execute(graph: TaskGraph, spec: Specification): Promise<ExecutionSummary> {\n this.stopped = false;\n this.retryMap.clear();\n const startTime = Date.now();\n\n const critical = analyzeCriticalPath(graph);\n let completed = 0;\n let failed = 0;\n const skipped = 0;\n let retried = 0;\n\n while (!this.stopped) {\n const readyTasks = this.getReadyTasks(graph);\n\n if (readyTasks.length === 0) {\n // Check if all tasks are done\n const allDone = Array.from(graph.nodes.values()).every(\n (n) => n.status === 'completed' || n.status === 'failed',\n );\n if (allDone) break;\n\n // Check for deadlock (all remaining tasks are blocked by failed tasks)\n const hasDeadlock = this.detectDeadlock(graph);\n if (hasDeadlock) break;\n\n break;\n }\n\n // Execute batch\n const batch = readyTasks.slice(0, this.opts.maxConcurrent ?? 1);\n\n const results = await Promise.allSettled(\n batch.map((task) => this.executeTaskWithRetry(task, graph, spec)),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const task = batch[i];\n if (!result || !task) continue;\n\n if (result.status === 'fulfilled') {\n const { result: execResult, retries } = result.value;\n if (execResult.success) {\n this.opts.tracker.updateNodeStatus(task.id, 'completed');\n completed++;\n if (retries > 0) retried++;\n this.opts.onTaskComplete?.(task, execResult);\n } else if (execResult.retry) {\n retried++;\n // Task will be retried on next iteration\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'failed', execResult.error);\n failed++;\n }\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'failed', String(result.reason));\n failed++;\n this.opts.onTaskFail?.(task, result.reason as Error, 0);\n }\n }\n }\n\n const duration = Date.now() - startTime;\n const summary: ExecutionSummary = {\n total: graph.nodes.size,\n completed,\n failed,\n skipped,\n retried,\n duration,\n criticalPath: critical.criticalPath,\n };\n\n this.opts.onDone?.(summary);\n return summary;\n }\n\n /** Stop execution. */\n stop(): void {\n this.stopped = true;\n }\n\n /** Get tasks that are ready to execute (all dependencies completed). */\n private getReadyTasks(graph: TaskGraph): TaskNode[] {\n const ready: TaskNode[] = [];\n\n for (const node of graph.nodes.values()) {\n if (node.status !== 'pending') continue;\n\n // Check if all blockers are completed\n const blockers = graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === node.id)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n\n const allBlockersDone = blockers.every((b) => b.status === 'completed');\n if (allBlockersDone) {\n ready.push(node);\n }\n }\n\n // Sort by priority\n const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n ready.sort((a, b) => (priorityOrder[a.priority] ?? 4) - (priorityOrder[b.priority] ?? 4));\n\n return ready;\n }\n\n /** Execute a single task with retry logic. */\n private async executeTaskWithRetry(\n task: TaskNode,\n graph: TaskGraph,\n spec: Specification,\n ): Promise<{ result: TaskExecutionResult; retries: number }> {\n const maxRetries = this.opts.maxRetries ?? 2;\n let retryCount = this.retryMap.get(task.id) ?? 0;\n\n while (retryCount <= maxRetries) {\n this.opts.tracker.updateNodeStatus(task.id, 'in_progress');\n this.opts.onTaskStart?.(task);\n\n const dependencies = this.getTaskDependencies(task.id, graph);\n const dependents = this.getTaskDependents(task.id, graph);\n\n const context: TaskExecutionContext = {\n spec,\n graph,\n task,\n dependencies,\n dependents,\n retryCount,\n };\n\n try {\n const result = await this.opts.executeTask(task, context);\n\n if (result.success) {\n const retriesForTask = this.retryMap.get(task.id) ?? 0;\n this.retryMap.delete(task.id);\n return { result, retries: retriesForTask };\n }\n\n if (result.retry && retryCount < maxRetries) {\n retryCount++;\n this.retryMap.set(task.id, retryCount);\n this.opts.tracker.updateNodeStatus(task.id, 'pending');\n continue;\n }\n\n return { result, retries: retryCount };\n } catch (error) {\n if (retryCount < maxRetries) {\n retryCount++;\n this.retryMap.set(task.id, retryCount);\n this.opts.tracker.updateNodeStatus(task.id, 'pending');\n this.opts.onTaskFail?.(task, error as Error, retryCount);\n continue;\n }\n\n return {\n result: {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n },\n retries: retryCount,\n };\n }\n }\n\n return { result: { success: false, error: 'Max retries exceeded' }, retries: retryCount };\n }\n\n /** Get tasks that this task depends on. */\n private getTaskDependencies(taskId: string, graph: TaskGraph): TaskNode[] {\n return graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === taskId)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n }\n\n /** Get tasks that depend on this task. */\n private getTaskDependents(taskId: string, graph: TaskGraph): TaskNode[] {\n return graph.edges\n .filter((e) => e.type === 'depends_on' && e.to === taskId)\n .map((e) => graph.nodes.get(e.from))\n .filter(Boolean) as TaskNode[];\n }\n\n /** Detect deadlock: all remaining tasks are blocked by failed tasks. */\n private detectDeadlock(graph: TaskGraph): boolean {\n const remaining = Array.from(graph.nodes.values()).filter(\n (n) => n.status === 'pending' || n.status === 'blocked',\n );\n\n if (remaining.length === 0) return false;\n\n return remaining.every((node) => {\n const blockers = graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === node.id)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n\n return blockers.some((b) => b.status === 'failed');\n });\n }\n}\n\n/**\n * Create an auto-executor that works with TaskFlow.\n */\nexport function createAutoExecutor(opts: {\n tracker: TaskTracker;\n events: EventBus;\n executeTask: AutoExecutorOptions['executeTask'];\n maxConcurrent?: number | undefined;\n maxRetries?: number | undefined;\n}): AutoExecutor {\n return new AutoExecutor({\n tracker: opts.tracker,\n events: opts.events,\n executeTask: opts.executeTask,\n maxConcurrent: opts.maxConcurrent,\n maxRetries: opts.maxRetries,\n });\n}\n","/**\n * SddTaskDecomposer\n *\n * Converts a TaskGraph (from SDD's TaskGenerator) into a dependency-aware\n * sequence of batches for ParallelEternalEngine.\n *\n * Key behaviour:\n * - Each `nextBatch()` call returns up to `parallelSlots` ready tasks\n * (all blockers completed, sorted by priority).\n * - Tasks that are blocked by an in-progress task are NOT included\n * in the batch — they wait for the blocker to complete.\n * - When `isDone()` returns true the whole graph is either completed\n * or deadlocked (all remaining tasks are blocked by failed tasks).\n *\n * Usage:\n * ```\n * const decomposer = new SddTaskDecomposer(tracker, graph, { parallelSlots: 4 });\n * while (!decomposer.isDone()) {\n * const batch = decomposer.nextBatch();\n * if (batch.length === 0) break; // deadlock\n * await fanOut(batch);\n * decomposer.acknowledgeBatch(batch.map(t => t.id));\n * }\n * ```\n */\n\nimport type { TaskNode, TaskGraph } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\n\nexport interface SddTaskDecomposerOptions {\n /** Max tasks per batch. Default: 4. Range 1–16. */\n parallelSlots?: number | undefined;\n}\n\nexport interface TaskBatch {\n /** Tasks ready to execute in this wave. */\n tasks: TaskNode[];\n /** 0-based wave number since the decomposer was constructed. */\n wave: number;\n /** True when every node in the graph is either completed or failed. */\n allDone: boolean;\n /** True when no batch was produced because remaining tasks are all blocked by failed nodes. */\n deadlocked: boolean;\n}\n\nexport class SddTaskDecomposer {\n private readonly slots: number;\n private wave = 0;\n\n constructor(\n private readonly tracker: TaskTracker,\n _graph: TaskGraph,\n opts: SddTaskDecomposerOptions = {},\n ) {\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n }\n\n // -------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------\n\n /**\n * Return the next batch of runnable tasks.\n * Returns `allDone: true` when every node is completed.\n * Returns `deadlocked: true` when no batch can be produced because\n * all remaining tasks are blocked by failed nodes.\n */\n nextBatch(): TaskBatch {\n if (this.isDone()) {\n return { tasks: [], wave: this.wave, allDone: true, deadlocked: false };\n }\n\n const pending = this.pendingReadyNodes();\n\n if (pending.length === 0) {\n // No runnable tasks — check for deadlock\n const hasBlockedTasks = this.hasAnyBlockedTasks();\n return { tasks: [], wave: this.wave, allDone: false, deadlocked: hasBlockedTasks };\n }\n\n const batch = pending.slice(0, this.slots);\n return { tasks: batch, wave: this.wave, allDone: false, deadlocked: false };\n }\n\n /**\n * Advance the wave counter after a batch completes.\n * Call this once per `nextBatch()` result that was fan-out.\n */\n acknowledgeBatch(_completedTaskIds: string[]): void {\n this.wave++;\n }\n\n /**\n * True when every node in the graph is completed.\n * Use this to exit the fan-out loop after `isDone() || deadlocked`.\n */\n isDone(): boolean {\n const progress = this.tracker.getProgress();\n return progress.total > 0 && progress.completed === progress.total;\n }\n\n /**\n * Total waves produced so far.\n */\n getWaveCount(): number {\n return this.wave;\n }\n\n // -------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------\n\n /**\n * Return pending nodes whose blockers are all completed.\n * Sorted by priority (critical first), then by creation time.\n */\n private pendingReadyNodes(): TaskNode[] {\n const allPending = this.tracker.getAllNodes({ status: ['pending'] });\n const ready: TaskNode[] = [];\n\n for (const node of allPending) {\n if (this.tracker.canStart(node.id)) {\n ready.push(node);\n }\n }\n\n // Sort by priority first, then by createdAt\n const priorityRank: Record<TaskNode['priority'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n };\n\n ready.sort((a, b) => {\n const pr = priorityRank[a.priority] - priorityRank[b.priority];\n if (pr !== 0) return pr;\n return a.createdAt - b.createdAt;\n });\n\n return ready;\n }\n\n /** True when at least one non-completed, non-failed task is blocked. */\n private hasAnyBlockedTasks(): boolean {\n const nodes = this.tracker.getAllNodes({\n status: ['pending', 'in_progress', 'blocked'],\n });\n return nodes.some((n) => n.status === 'blocked');\n }\n}","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\n/**\n * Fraction of the wall-clock `timeoutMs` window at which a PROACTIVE extension\n * is negotiated — BEFORE the deadline is actually crossed. The coordinator\n * watchdog (`executeWithTimeout`) arms at `timeoutMs * TIMEOUT_PREEMPT_FRACTION`\n * so a still-progressing subagent gets its ceiling raised while it is below the\n * limit, and never enters a \"timed out\" state. Reactive enforcement at the real\n * deadline still stands for the no-progress / denied case. Shared so the asking\n * side and any future caller agree on the same lead point.\n */\nexport const TIMEOUT_PREEMPT_FRACTION = 0.85;\n\n/**\n * Hard safety net for budget negotiation decisions. If no listener responds to\n * `budget.threshold_reached` within this window the negotiation defaults to\n * `'stop'`. Exported so the coordinator's watchdog can reuse the same ceiling\n * without hardcoding a second copy.\n */\nexport const DECISION_TIMEOUT_MS = 60_000;\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number | undefined;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number | undefined;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number | undefined;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n /**\n * Direct grant/deny hooks for SYNCHRONOUS policy or recording handlers that\n * decide in-process without a wired `budget.threshold_reached` listener\n * (e.g. the coordinator watchdog). `extend` patches the limits in place;\n * `deny` records the intent to stop. Production listener-driven handlers use\n * `requestDecision()` instead and can ignore these.\n */\n extend?: (extra: Partial<BudgetLimits>) => void;\n deny?: () => void;\n}) => 'throw' | 'continue' | 'stop' | { extend: Partial<BudgetLimits> } | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n\n /** Patch one or more budget limits in-place after construction.\n * Used by the coordinator watchdog when granting an extension.\n * All fields are optional — only provided fields are updated.\n * This is the single write path for limit mutations so that future\n * validation or side-effects live in one place (M1). */\n patchLimits(ext: Partial<BudgetLimits>): void {\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n }\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = DECISION_TIMEOUT_MS;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus | undefined;\n\n /**\n * Guard against dual-path races between the coordinator watchdog\n * (`executeWithTimeout`) and the budget's own `checkTimeout()`.\n * Both paths detect `elapsed >= timeoutMs` and can emit\n * `budget.threshold_reached` for kind `'timeout'` simultaneously.\n * Set to the current `timeoutMs` ceiling by the coordinator BEFORE\n * calling `onThreshold`, and cleared after the negotiation resolves.\n * `checkTimeout()` skips its wall-clock check while this is set so\n * the coordinator's watchdog is the sole source of wall-clock timeout\n * events — `checkTimeout()` focuses exclusively on `idle_timeout`.\n */\n private _watchdogActive: number | undefined;\n\n /** Returns the timeout ceiling currently being negotiated by the watchdog,\n * or `undefined` when no wall-clock negotiation is in flight.\n * Used by `executeWithTimeout` to detect a stale lock (M3). */\n get watchdogActive(): number | undefined { return this._watchdogActive; }\n\n /** Called by the coordinator watchdog BEFORE calling `onThreshold` so that\n * `checkTimeout()` skips its wall-clock check for this ceiling. Prevents\n * the budget's own `checkTimeout()` from emitting a second\n * `budget.threshold_reached` event while the watchdog is already\n * negotiating the same wall-clock deadline (C1). */\n setWatchdogNegotiation(timeoutMs: number): void { this._watchdogActive = timeoutMs; }\n\n /** Clears the watchdog guard after negotiation resolves. Called in the\n * `finally` block of both the pre-empt and deadline branches so it fires\n * on every exit path: grant, deny, throw, or error. */\n clearWatchdogNegotiation(): void { this._watchdogActive = undefined; }\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n // Skip the wall-clock 'timeout' kind while the coordinator watchdog is\n // negotiating this exact ceiling — it owns wall-clock; checkTimeout/here\n // own idle. Only suppress in the negotiation path (a handler is set); on\n // the no-handler hard-throw path the wall-clock must still trip. (Mirrors\n // the guard in checkTimeout, which previously was NOT applied here — so\n // an idle trip that called checkLimits re-added 'timeout' and defeated the\n // watchdog dedup.)\n const wallOwnedByWatchdog =\n this._onThreshold !== undefined && this._watchdogActive === this.limits.timeoutMs;\n if (\n this.limits.timeoutMs !== undefined &&\n elapsedMs > this.limits.timeoutMs &&\n !wallOwnedByWatchdog\n ) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus) {\n // No EventBus wired at all → nobody to negotiate with → hard stop.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n\n // LISTENER-DRIVEN PATH. A registered `budget.threshold_reached` listener\n // (director / collab / auto-extend) negotiates asynchronously. Start one\n // negotiation PER exceeded kind — each reports its OWN kind/used/limit and\n // emits a single event (no O(N^2) re-emission, no cross-kind first-wins\n // drop). Throw `BudgetThresholdSignal` for the first kind so the runner\n // awaits the decision and enforces extend/stop.\n if (bus.hasListenerFor('budget.threshold_reached')) {\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n this._pendingNegotiations.set(entry.kind, this._negotiateExtension(entry));\n }\n const decision = this._pendingNegotiations.get(first.kind);\n if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n // NO-LISTENER PATH. Invoke the handler synchronously to let an in-process\n // policy decide. Two outcomes:\n // • SYNC handler (returns a string/decision — e.g. the coordinator\n // watchdog / recording handlers) → its decision is honored in place\n // (an `extend` patches limits); no throw. This is the path the\n // watchdog drives while it owns wall-clock enforcement.\n // • ASYNC handler (returns a Promise via `requestDecision()`) → there is\n // no listener to resolve it and `requestDecision` resolves to 'stop',\n // so this is a definite hard stop: throw `BudgetExceededError`. This is\n // the documented \"auto mode + no listener → hard stop\" invariant that\n // protects a bare `/spawn` (no director) from a runaway subagent.\n let hardStop: BudgetExceededError | null = null;\n for (const entry of exceeded) {\n // Dedup per kind across back-to-back overruns in the same tick — a still\n // exceeded kind (e.g. iterations stays over after a grant) must not\n // re-invoke the handler on every record* call. The marker clears on a\n // microtask so a genuinely fresh overrun later can re-negotiate.\n if (this._pendingNegotiations.has(entry.kind)) continue;\n const marker = Promise.resolve<BudgetThresholdDecision>('stop');\n this._pendingNegotiations.set(entry.kind, marker);\n void marker.finally(() => this._pendingNegotiations.delete(entry.kind));\n const sync = this._invokeHandlerSync(entry);\n if (!sync) hardStop ??= new BudgetExceededError(entry.kind, entry.limit, entry.used);\n }\n if (hardStop) throw hardStop;\n return exceeded;\n }\n\n /**\n * Invoke `onThreshold` once for `entry` on the NO-LISTENER path and report\n * whether it decided synchronously. Returns `true` when the handler returned\n * a synchronous decision (already honored — an `extend` patched the limits),\n * or `false` when it returned a Promise (async; the caller hard-stops, since\n * there is no listener to resolve the negotiation). The handler is given the\n * full info shape (`requestDecision` plus direct `extend`/`deny`) so both\n * recording handlers and policy handlers work without a wired listener.\n */\n private _invokeHandlerSync(entry: { kind: BudgetKind; used: number; limit: number }): boolean {\n const handler = this._onThreshold;\n if (!handler) return false;\n let extendArg: Partial<BudgetLimits> | undefined;\n const result = handler({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n // Direct hooks for synchronous policy/recording handlers.\n extend: (extra: Partial<BudgetLimits>) => {\n extendArg = extra;\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n // A thenable means the handler deferred to async negotiation — but there is\n // no listener here, so it can never be granted → hard stop.\n if (result && typeof (result as { then?: unknown }).then === 'function') return false;\n if (result === 'throw') return false; // explicit hard stop\n // 'continue' / 'stop' / a returned { extend } decision — honor in place.\n if (result && typeof result === 'object' && 'extend' in result) {\n extendArg = (result as { extend: Partial<BudgetLimits> }).extend;\n }\n if (extendArg) this.patchLimits(extendArg);\n return true;\n }\n\n /**\n * Emit `budget.threshold_reached` and resolve to the listener's verdict.\n * Resolves to `'stop'` immediately when there is no listener (or no bus) so\n * no negotiation can hang and no fallback timer leaks. Mirrors the\n * coordinator watchdog's own request path so both agree on the no-listener\n * default.\n */\n private _busRequestDecision(entry: {\n kind: BudgetKind;\n used: number;\n limit: number;\n }): Promise<BudgetThresholdDecision> {\n const bus = this._events;\n if (!bus?.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n clearTimeout(fallback);\n resolve(d);\n };\n const fallback = setTimeout(() => respond('stop'), SubagentBudget.DECISION_TIMEOUT_MS);\n bus.emit('budget.threshold_reached', {\n kind: entry.kind as\n | 'iterations'\n | 'tool_calls'\n | 'tokens'\n | 'cost'\n | 'timeout'\n | 'idle_timeout',\n used: entry.used,\n limit: entry.limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n // deny() wins over a same-dispatch extend(): a listener that both grants\n // and denies (or two listeners disagreeing) is resolved as a stop. The\n // grant is deferred a microtask so a synchronous deny in the same emit\n // pre-empts it; async grants still resolve normally.\n extend: (extra: Partial<BudgetLimits>) => queueMicrotask(() => respond({ extend: extra })),\n deny: () => respond('stop'),\n });\n });\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n entry: { kind: BudgetKind; used: number; limit: number },\n ): Promise<BudgetThresholdDecision> {\n if (!this._onThreshold) {\n // Should never reach here — caller should have thrown already\n return 'stop';\n }\n try {\n const result = this._onThreshold({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n // One event for THIS kind only — each exceeded kind has its own\n // negotiation (and its own resolve), so there is no cross-kind\n // first-wins drop and no O(N^2) re-emission.\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n extend: (extra: Partial<BudgetLimits>) => {\n this.patchLimits(extra);\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving (single write path).\n this.patchLimits(decision.extend);\n return decision;\n } finally {\n this._pendingNegotiations.delete(entry.kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock / idle budget check. Delegates to `checkLimits(elapsed)`, so\n * `timeout` and `idle_timeout` follow the SAME negotiation path as the other\n * kinds — they are NOT a special-cased hard stop. This is deliberate: a\n * heartbeat-aware policy (see `attachAutoExtend` and `CollabSession`) grants\n * a timeout extension only while the agent is making progress and denies it\n * once the agent is genuinely stuck, which is safer than an unconditional\n * hard kill of a long-but-working agent. The runner translates the resulting\n * `BudgetThresholdSignal` decision (`extend` → patch limits in place,\n * `stop` → abort) just like every other kind.\n *\n * Decision table (same as `checkLimits`):\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` (negotiated;\n * a heartbeat-aware policy may extend the timeout)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n // Skip wall-clock timeout if the coordinator watchdog is already in the middle\n // of negotiating this exact ceiling — tool.progress is too frequent and creates\n // a race where both paths emit budget.threshold_reached for the same kind.\n // The watchdog owns wall-clock; checkTimeout focuses exclusively on idle.\n const wallSkipped =\n this._onThreshold !== undefined &&\n this._watchdogActive !== undefined &&\n timeoutMs !== undefined &&\n this._watchdogActive === timeoutMs;\n const wallTripped = wallSkipped ? false : timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\n/**\n * Wrap a factory to automatically filter out disabled tools from subagent\n * configurations. This provides mechanical enforcement of tool restrictions\n * (e.g., preventing delegation) in addition to the baseline prompt constraint.\n *\n * The wrapper reads `config.disabledTools` and removes those tools from the\n * agent's tool registry before returning.\n *\n * Usage:\n * const filteredFactory = withDisabledToolFiltering(originalFactory);\n * const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n */\nexport function withDisabledToolFiltering(factory: AgentFactory): AgentFactory {\n return async (config: SubagentConfig) => {\n const result = await factory(config);\n const disabled = config.disabledTools ?? [];\n if (disabled.length === 0) return result;\n\n // Agent.tools is a ToolRegistry with unregister() method\n const registry = result.agent.tools;\n if (registry && typeof registry.unregister === 'function') {\n for (const toolName of disabled) {\n registry.unregister(toolName);\n }\n }\n return result;\n };\n}\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: ((() => Promise<void> | void)) | undefined;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus | undefined;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const taskStartedAt = Date.now();\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Defer the stop/extend decision to the post-finally block below.\n // The coordinator's verdict may arrive after agent.run() returns;\n // awaiting it there (rather than in this fire-and-forget handler)\n // avoids a race where both this callback and the post-finally\n // block try to mutate `budgetError` concurrently.\n budgetError = err;\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~2000 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-2000);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n // Emit task_completed BEFORE the finally block unsubscribes the\n // FleetBus — this lets the WebUI see the subagent's final output.\n events.emit('subagent.task_completed', {\n subagentId: ctx.subagentId,\n taskId: task.id,\n status: result.status === 'done' ? 'success' : 'failed',\n iterations: result.iterations,\n toolCalls: ctx.budget.usage().toolCalls,\n durationMs: Date.now() - taskStartedAt,\n finalText: result.finalText?.trim() || undefined,\n });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n try {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n } catch {\n // Decision promise rejected — treat as hard stop.\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof AgentError\n ? result.error\n : new AgentError({\n message: result.error instanceof Error ? result.error.message : String(result.error ?? 'agent failed'),\n code: ERROR_CODES.AGENT_RUN_FAILED,\n cause: result.error,\n });\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new AgentError({\n message: 'agent aborted',\n code: ERROR_CODES.AGENT_ABORTED,\n });\n }\n if (result.status === 'max_iterations') {\n throw new AgentError({\n message: 'agent exhausted iteration limit',\n code: ERROR_CODES.AGENT_ITERATION_LIMIT,\n recoverable: true,\n });\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new AgentError({\n message: 'empty response — agent produced no text and no tool calls',\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { iterations: result.iterations },\n });\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new AgentError({\n message: `unrecovered tool failure: ${lastToolFailed} — agent ended turn without acknowledging the error`,\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { tool: lastToolFailed, iterations: result.iterations },\n });\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\nimport { truncate } from '../utils/string.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\nexport type CacheTtl = '5m' | '1h';\n\n/**\n * Provider-agnostic response-format directive.\n *\n * - `{ type: 'text' }` — free-form text (default).\n * - `{ type: 'json_object' }` — valid JSON without a schema constraint.\n * - `{ type: 'json_schema', jsonSchema: { name, schema, strict? } }` — JSON\n * constrained to the supplied JSON Schema. The `strict` flag is\n * OpenAI-specific; Gemini ignores it in favour of `responseMimeType`.\n *\n * Each provider adapter maps this into its own wire format:\n * OpenAI → `response_format`\n * Gemini → `responseMimeType` + `responseSchema`\n * Anthropic → (not yet supported; uses tools for structured output)\n */\nexport interface JsonSchemaSpec {\n name: string;\n /** OpenAI-specific: enable strict schema adherence. */\n strict?: boolean | undefined;\n /** The JSON Schema object describing the expected shape. */\n schema: Record<string, unknown>;\n /** Optional human-readable description (OpenAI). */\n description?: string | undefined;\n}\n\nexport type ResponseFormat =\n | { type: 'text' }\n | { type: 'json_object' }\n | { type: 'json_schema'; jsonSchema: JsonSchemaSpec };\n\n/**\n * Safety category threshold pair used by Google Gemini's `safetySettings`.\n *\n * Categories: `HARM_CATEGORY_HARASSMENT`, `HARM_CATEGORY_HATE_SPEECH`,\n * `HARM_CATEGORY_SEXUALLY_EXPLICIT`, `HARM_CATEGORY_DANGEROUS_CONTENT`.\n *\n * Thresholds: `BLOCK_NONE`, `BLOCK_ONLY_HIGH`, `BLOCK_MEDIUM_AND_ABOVE`,\n * `BLOCK_LOW_AND_ABOVE`.\n */\nexport interface SafetySetting {\n category: string;\n threshold: string;\n}\n\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number | undefined;\n /** Back-compat aggregate of all cache-write tokens. Prefer TTL-specific fields when present. */\n cacheWrite?: number | undefined;\n cacheWrite5m?: number | undefined;\n cacheWrite1h?: number | undefined;\n}\n\nexport interface ReasoningRequest {\n enabled?: boolean | undefined;\n effort?: ReasoningEffort | undefined;\n preserve?: boolean | undefined;\n display?: 'summarized' | 'omitted' | undefined;\n}\n\nexport interface RequestCacheControl {\n ttl?: CacheTtl | undefined;\n}\n\nexport interface ReasoningConfig {\n default: 'enabled' | 'disabled' | 'adaptive' | 'always_on';\n disableSupported: boolean;\n effortSupported: boolean;\n effortLevels: ReasoningEffort[];\n preserveThinking: 'unsupported' | 'optional' | 'always_on';\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n\n // ── Extended parameter support (optional; family defaults in CAPABILITIES_BY_FAMILY) ──\n\n /** Model accepts `top_k` / `topK` sampling parameter. */\n topK?: boolean | undefined;\n /** Model accepts `frequency_penalty` / `frequencyPenalty` parameter. */\n frequencyPenalty?: boolean | undefined;\n /** Model accepts `presence_penalty` / `presencePenalty` parameter. */\n presencePenalty?: boolean | undefined;\n /** Model accepts `seed` parameter for deterministic generation. */\n seed?: boolean | undefined;\n /**\n * Model accepts JSON Schema / structured-output constraints\n * (OpenAI `response_format.json_schema`, Gemini `responseMimeType`+`responseSchema`).\n * Distinct from `jsonMode` (which is just a system-prompt hint).\n */\n structuredOutput?: boolean | undefined;\n /** Model supports log-probability output (`logprobs`, `top_logprobs`). */\n logprobs?: boolean | undefined;\n /** Model supports audio input/output modality. */\n audio?: boolean | undefined;\n /** Model supports the `n` parameter for multiple completions. */\n multipleCompletions?: boolean | undefined;\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[] | undefined;\n messages: Message[];\n tools?: Tool[] | undefined;\n maxTokens: number;\n temperature?: number | undefined;\n topP?: number | undefined;\n topK?: number | undefined;\n frequencyPenalty?: number | undefined;\n presencePenalty?: number | undefined;\n seed?: number | undefined;\n /**\n * End-user identifier for abuse monitoring and per-user rate limiting.\n * - Anthropic → `metadata.user_id`\n * - OpenAI → `user`\n * - Gemini → (not supported)\n */\n user?: string | undefined;\n /**\n * Number of response candidates to generate. Google Gemini supports\n * this via `generationConfig.candidateCount`. OpenAI does not have\n * an equivalent (`n` is conceptually similar but distinct).\n */\n candidateCount?: number | undefined;\n /**\n * Whether to return log probabilities for output tokens.\n * - OpenAI → `logprobs: boolean` (+ `topLogprobs: number`)\n * - Gemini → `generationConfig.logprobs: number` (how many top candidates)\n * Default undefined = no logprobs requested.\n */\n logprobs?: boolean | undefined;\n /**\n * Number of most probable tokens to return log probabilities for\n * (OpenAI `top_logprobs`). Only meaningful when `logprobs` is true.\n * Range: 0-20. Gemini ignores this (uses `logprobs` as the count).\n */\n topLogprobs?: number | undefined;\n stopSequences?: string[] | undefined;\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool' | undefined; name: string };\n reasoning?: ReasoningRequest | undefined;\n cache?: RequestCacheControl | undefined;\n /**\n * Structured-output / response-format directive.\n * When set, the provider adapter maps this to its native response-format\n * parameter (OpenAI `response_format`, Gemini `responseMimeType`, etc.).\n * The model must advertise `capabilities.structuredOutput` for this to be\n * honoured; unsupported models will likely 400 or ignore it.\n */\n responseFormat?: ResponseFormat | undefined;\n /**\n * Safety category thresholds for filtering harmful content.\n * - Gemini → top-level `safetySettings` array with `{ category, threshold }`\n * - OpenAI → not supported (uses server-side moderation)\n * - Anthropic → not supported\n */\n safetySettings?: SafetySetting[] | undefined;\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string | undefined;\n name?: string | undefined;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string | undefined;\n /** Human-readable explanation from the provider. */\n message?: string | undefined;\n /** Provider request id, when present in the body or headers. */\n requestId?: string | undefined;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number | undefined;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string | undefined;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean | undefined;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number | undefined;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody | undefined;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody | undefined; cause?: unknown | undefined } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\n/**\n * Thrown when the provider stream stops delivering data mid-response.\n * This is distinct from a network error (TCP reset, DNS failure) — the\n * connection is established and the response started, but chunks stopped\n * arriving before the stream completed.\n *\n * Status 599 is used as a sentinel to distinguish stream hangs from\n * regular HTTP errors while still flowing through ProviderError-based\n * retry and fallback infrastructure.\n */\nexport class StreamHangError extends ProviderError {\n /** Name of the provider that hung, e.g. \"zai\", \"anthropic\". */\n public readonly hungProviderId: string;\n /** Model that was being called when the hang occurred. */\n public readonly hungModel: string;\n /** How long (ms) we waited for the next chunk before declaring a hang. */\n public readonly hangTimeoutMs: number;\n /** How many bytes were received before the hang. */\n public readonly bytesReceived: number;\n /** Elapsed time (ms) from the start of the stream until the hang. */\n public readonly elapsedMs: number;\n\n constructor(opts: {\n providerId: string;\n model: string;\n hangTimeoutMs: number;\n bytesReceived: number;\n elapsedMs: number;\n cause?: unknown | undefined;\n }) {\n super(\n `Stream hang: ${opts.providerId}/${opts.model} — no data for ${opts.hangTimeoutMs}ms after ${opts.bytesReceived} bytes (${opts.elapsedMs}ms elapsed)`,\n 599,\n true, // always retryable\n opts.providerId,\n {\n body: {\n message: `Stream stalled after ${opts.elapsedMs}ms, ${opts.bytesReceived} bytes received`,\n },\n cause: opts.cause,\n },\n );\n this.name = 'StreamHangError';\n this.hungProviderId = opts.providerId;\n this.hungModel = opts.model;\n this.hangTimeoutMs = opts.hangTimeoutMs;\n this.bytesReceived = opts.bytesReceived;\n this.elapsedMs = opts.elapsedMs;\n }\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { SubagentError, SubagentErrorKind } from '../../types/multi-agent.js';\nimport { ProviderError } from '../../types/provider.js';\nimport { AgentError } from '../../types/errors.js';\nimport { BudgetExceededError } from '../subagent-budget.js';\nimport { toErrorMessage } from '../../utils/error.js';\n\n/**\n * Map any raw exception thrown out of a subagent's runner into a\n * structured `SubagentError`. This is the single point where the\n * coordinator decides \"what kind of failure was that\" — so callers\n * (delegate tool output, /agents UI, retry policies) branch on\n * `kind` instead of substring-matching `error.message`.\n *\n * Exported because tests and CLI surfaces want to assert on the\n * classification without instantiating a coordinator.\n */\nexport function classifySubagentError(\n err: unknown,\n hints: { parentAborted?: boolean | undefined } = {},\n): SubagentError {\n // Unwrap AgentError wrappers — the runner wraps non-AgentError\n // throwables (ProviderError, TypeError, etc.) in AgentError so the\n // coordinator's try/catch catches a consistent type. Recurse into the\n // inner cause so classification sees the original error kind.\n if (err instanceof AgentError && err.cause) {\n return classifySubagentError(err.cause, hints);\n }\n\n const cause = err instanceof Error\n ? { name: err.name, message: err.message, stack: err.stack }\n : undefined;\n\n if (err instanceof ProviderError) {\n const baseMessage = err.describe();\n return providerErrorToSubagentError(err, baseMessage, cause);\n }\n\n const baseMessage = toErrorMessage(err);\n\n if (err instanceof BudgetExceededError) {\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\n iterations: 'budget_iterations',\n tool_calls: 'budget_tool_calls',\n tokens: 'budget_tokens',\n cost: 'budget_cost',\n timeout: 'budget_timeout',\n idle_timeout: 'budget_timeout',\n };\n return {\n kind: map[err.kind],\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n\n if (hints.parentAborted) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n\n const lower = baseMessage.toLowerCase();\n if (/agent aborted$/i.test(baseMessage)) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\n }\n if (/empty response/i.test(baseMessage)) {\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\n }\n if (/^tool failed: /i.test(baseMessage)) {\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\n }\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\n }\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\n }\n\n return { kind: 'unknown', message: baseMessage, retryable: false, cause };\n}\n\nfunction providerErrorToSubagentError(\n err: ProviderError,\n message: string,\n cause: SubagentError['cause'],\n): SubagentError {\n const status = err.status;\n if (status === 429 || err.body?.type === 'rate_limit_error') {\n return { kind: 'provider_rate_limit', message, retryable: true, backoffMs: 5_000, cause };\n }\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\n return { kind: 'provider_auth', message, retryable: false, cause };\n }\n if (status === 408 || status === 0) {\n return { kind: 'provider_timeout', message, retryable: true, cause };\n }\n if (status >= 500 && status < 600) {\n return { kind: 'provider_5xx', message, retryable: true, backoffMs: 3_000, cause };\n }\n return { kind: 'unknown', message, retryable: err.retryable, cause };\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number | undefined;\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n maxCostUsd?: number | undefined;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree', 'mailbox'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit', 'mailbox'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch', 'mailbox'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n 'mailbox',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json', 'mailbox'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document', 'mailbox'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch', 'mailbox'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n {\n config: {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n tools: [...PLAN_TOOLS, 'diff'],\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan with phases (Low Risk / Medium Risk / High Risk),\ndependency graph, rollback strategy, and exit criteria.\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Refactoring planner: analyzes code structure, maps dependencies, produces risk-scored phased plans with rollback strategy.',\n keywords: [\n 'refactor',\n 'refactoring',\n 'restructure',\n 'debt',\n 'technical debt',\n 'clean up',\n 'modularize',\n 'decouple',\n 'dependency graph',\n 'code structure',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [\n ...TOOLS.build,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Use Playwright browser tools (navigate, click, type, screenshot, evaluate)\n to automate web UI flows — open pages, interact with forms, capture evidence\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs, page HTML)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (screenshots, page HTML, logs) for reproduction\n- Keep scenarios independent so one failure doesn't cascade\n- For browser tests: playwright_navigate first, then interact, then playwright_screenshot as evidence\n- If playwright tools are unavailable, report it and fall back to API/CLI testing`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'browser',\n 'screenshot',\n 'web ui',\n 'headless',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n 'navigate',\n 'click',\n 'form fill',\n 'dom',\n 'page load',\n ],\n },\n },\n {\n config: {\n id: 'browser',\n name: 'Browser',\n role: 'browser',\n tools: [\n ...TOOLS.read,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the Browser agent. Your job is browser automation: open web pages,\ninteract with them, extract data, capture screenshots, and return structured\nresults. You are a read-focused agent — you drive the browser, not the filesystem.\n\nScope:\n- Navigate to URLs and wait for pages to load\n- Take full-page or element screenshots as evidence\n- Click buttons, fill forms, select options, type text — full user simulation\n- Extract page content: text, HTML, element attributes, data tables\n- Evaluate JavaScript in the page context to extract structured data\n- Verify visual state (element visibility, text content, attribute values)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"navigate | screenshot | extract | interact | verify\", \"url\": \"<url>\", \"steps\": [\"step1\", \"step2\"] }\n\nOutput: Structured markdown report:\n- ## Page (URL, title, load status)\n- ## Actions Taken (step-by-step with timestamps)\n- ## Results (extracted data, element states, verification results)\n- ## Screenshots (list attached screenshot references)\n- ## Errors (any failures with stack traces)\n\nWorking rules:\n- Always playwright_navigate first before any interaction\n- Always playwright_wait_for after navigation to ensure the page is ready\n- playwright_screenshot is your primary evidence — use it before and after interactions\n- Use playwright_evaluate for structured data extraction (JSON, text content)\n- If a selector fails, try alternative selectors before giving up\n- Report exact CSS selectors used — they're part of the evidence\n- If playwright tools are unavailable, report the error immediately — do not guess`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Browser automation: opens pages, clicks, types, screenshots, extracts data via Playwright headless Chromium.',\n keywords: [\n 'browser',\n 'screenshot',\n 'navigate',\n 'web page',\n 'scrape',\n 'crawl',\n 'headless',\n 'chrome',\n 'open url',\n 'capture',\n 'page title',\n 'extract data',\n 'fill form',\n 'click button',\n 'take screenshot',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n {\n config: {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n tools: [...TOOLS.inspect],\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report with severity-ranked findings, injection\nvectors, dependency issues, and a remediation checklist.\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Security scanner: detects hardcoded secrets, injection vectors, insecure patterns, and supply-chain risks with remediation.',\n keywords: [\n 'security',\n 'scan',\n 'vulnerability',\n 'secret',\n 'api key',\n 'hardcoded',\n 'injection',\n 'cve',\n 'audit dependencies',\n 'supply chain',\n 'xss',\n 'sqli',\n 'shell injection',\n 'sensitive data',\n 'credential',\n ],\n },\n },\n {\n config: {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n tools: [...TOOLS.inspect],\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report with critically/high/medium/low sections.\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Bug hunter: scans source code for bugs, anti-patterns, and code smells, producing a file:line-ranked hit list with fixes.',\n keywords: [\n 'bug',\n 'hunt',\n 'scan',\n 'code smell',\n 'anti-pattern',\n 'race condition',\n 'memory leak',\n 'null deref',\n 'type safety',\n 'unhandled error',\n 'find bugs',\n 'audit code',\n 'code quality',\n ],\n },\n },\n {\n config: {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n tools: [...TOOLS.inspect],\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with Summary, Top Errors, Tool Usage table,\nAnomalies, and Cost Trend sections.\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Audit log analyzer: parses session JSONL, detects failure patterns, tool anomalies, and cost trends with structured reports.',\n keywords: [\n 'audit',\n 'log',\n 'logs',\n 'session',\n 'trace',\n 'analyze logs',\n 'error patterns',\n 'cost analysis',\n 'tool usage',\n 'token usage',\n 'post-mortem',\n 'trend',\n 'anomaly',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [\n ...TOOLS.build,\n 'mcp__ssh__ssh_list_servers',\n 'mcp__ssh__ssh_connection_status',\n 'mcp__ssh__ssh_execute',\n 'mcp__ssh__ssh_execute_sudo',\n 'mcp__ssh__ssh_upload',\n 'mcp__ssh__ssh_download',\n 'mcp__ssh__ssh_sync',\n 'mcp__ssh__ssh_deploy',\n 'mcp__ssh__ssh_health_check',\n 'mcp__ssh__ssh_service_status',\n 'mcp__ssh__ssh_process_manager',\n 'mcp__ssh__ssh_tunnel',\n 'mcp__ssh__ssh_backup_create',\n 'mcp__ssh__ssh_backup_list',\n 'mcp__ssh__ssh_backup_restore',\n 'mcp__ssh__ssh_db_list',\n 'mcp__ssh__ssh_db_query',\n 'mcp__ssh__ssh_profile',\n ],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n- Use optional SSH MCP tools for remote hosts when the 'ssh' MCP server is enabled: list servers, run health checks, inspect services, transfer/deploy files, and open tunnels\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying\n- For remote SSH work, start with ssh_list_servers / ssh_connection_status, prefer read-only checks first, and do not run destructive commands without explicit user approval`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'ssh',\n 'remote ssh',\n 'remote server',\n 'sftp',\n 'tunnel',\n 'bastion',\n 'jump host',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n {\n config: {\n id: 'tech-stack',\n name: 'Tech Stack Validator',\n role: 'tech-stack',\n tools: ['search', 'fetch', 'read', 'grep', 'glob', 'outdated', 'audit', 'json', 'mailbox'],\n prompt: `You are the Tech Stack Validator — a single-shot validation agent that fires\nbefore any package, library, or framework choice is committed.\n\nYour ONLY job: verify that a technology choice is current, real, and not obsolete.\nYou are the \"this isn't code, this is 10-year-old technology\" agent. Intervene\nhard when the LLM hallucinates a version number or suggests dead tech.\n\n## Before you begin\n\nCheck the inter-agent mailbox for pending tasks. Other agents or the file-watcher\nmay have left assign messages with dependency files to audit:\n- mailbox action=check\n\nIf you find an assign message, use the specified file path and packages.\nWhen done, post results back:\n- mailbox action=send to=<sender> type=result subject=\"Tech stack audit results\" body=\"...\"\n\n## Critical rules\n\n1. **Verify existence.** Search npm registry (fetch https://registry.npmjs.org/<pkg>/latest)\n or web search. A package that doesn't exist = hallucination.\n\n2. **Check latest version.** Never trust any version number from the model. Always\n fetch the actual latest stable version from npm or the project's release page.\n\n3. **Reject dead packages.** No release in >2 years + unresolved critical issues =\n dead. Suggest a maintained replacement.\n\n4. **Reject prehistoric tech.** Any package/pattern superseded ≥5 years ago is\n REJECTED. Key blocklist:\n - axios / node-fetch / got / request → native fetch (Node 18+)\n - moment → date-fns / luxon / Temporal\n - jQuery (new projects) → vanilla DOM / React\n - Gulp / Grunt → tsup / esbuild / vite\n - CoffeeScript / Flow → TypeScript\n - Bluebird → native Promises\n - crypto-js → node:crypto / Web Crypto\n - Bower → npm/pnpm\n - underscore → lodash or native ES2020+\n\n5. **The intervention phrase.** When rejecting on age grounds, you MUST output\n exactly: \"This isn't code, this is X-year-old technology.\" where X =\n current year − the year the technology was made obsolete. Follow with\n what replaced it and a one-step migration path.\n\n6. **Prefer built-in over third-party.** Check Node 22+ native APIs first:\n node:test, node:sqlite, fetch, WebSocket, Web Crypto — all built-in.\n\n## Workflow (single-shot — do NOT loop)\n\n1. Receive the proposed package + version\n2. Search npm registry or web for the latest version\n3. Check age, maintenance status, deprecation\n4. Output verdict: APPROVED (with exact version) or REJECTED (with replacement)\n\n## Output format\n\n### Tech Stack Validation — <package>\n\n**Status**: APPROVED | REJECTED\n\n**Package**: <name>@<version>\n**Source**: <URL you checked — npm registry, GitHub, web search>\n**Age**: <first release> — <last release date>\n**Verdict**: 1–2 sentence explanation.\n\nWhen REJECTED on age:\n**\"This isn't code, this is X-year-old technology.\"**\n**Replaced by**: <modern alternative>\n**Migration**: <one concrete step>\n\nWhen APPROVED:\n**Install**: pnpm add <name>@^<major>.<minor>.0`,\n },\n budget: {\n timeoutMs: 120_000,\n maxIterations: 10,\n maxToolCalls: 40,\n maxTokens: 60_000,\n maxCostUsd: 0.25,\n },\n capability: {\n phase: 'meta',\n summary: 'Single-shot tech stack validator: checks npm for latest versions, rejects dead/obsolete packages, enforces modern alternatives.',\n keywords: [\n 'tech stack',\n 'version',\n 'package',\n 'library',\n 'framework',\n 'dependency',\n 'install',\n 'upgrade',\n 'latest',\n 'npm',\n 'pnpm add',\n 'outdated',\n 'obsolete',\n 'deprecated',\n 'what version',\n 'which package',\n 'check version',\n 'verify version',\n 'is this current',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Shadow Agent — background fleet monitoring and intervention.\r\n * Use for: silent observation, anomaly detection, on-demand intervention.\r\n */\r\nexport const SHADOW_AGENT: SubagentConfig = {\r\n id: 'shadow-agent',\r\n name: 'Shadow',\r\n role: 'shadow-agent',\r\n prompt: `You are the Shadow Agent — a silent background monitor for the WrongStack fleet.\r\n\r\nYour job is to observe, detect anomalies, and be ready to intervene — but only when commanded.\r\n\r\n## Core Responsibilities\r\n\r\n1. **Fleet Monitoring** (every 30s)\r\n - Call \\`fleet_status\\` + \\`fleet_health\\` on each heartbeat\r\n - Track what each agent is doing (task descriptions)\r\n - Detect stuck agents (>5min no events), idle agents, crashed agents\r\n\r\n2. **FleetBus Subscription**\r\n - Subscribe to \\`subagent.*\\` events to track lifecycle\r\n - Subscribe to \\`tool.executed\\` to monitor activity\r\n - Track agent joins (subagent.started) and leaves (subagent.stopped)\r\n\r\n3. **Mailbox Surveillance**\r\n - Monitor for \\`control\\` type messages starting with \"hoop\"\r\n - Detect orphan assigns (assign without result within 5min)\r\n - Cross-session awareness via shared project mailbox\r\n\r\n4. **Spike Detection**\r\n - Track task duration per agent\r\n - Flag agents that spawn and die within <5 seconds\r\n - Log spike events with reason (completed/error/killed/timeout)\r\n\r\n5. **Intervention Commands**\r\n Parse these from mailbox control messages:\r\n - \\`hoop <agentId>\\` — terminate specific agent\r\n - \\`hoop all\\` — terminate all running agents\r\n - \\`shadow status\\` — report current fleet snapshot\r\n - \\`shadow mute\\` — pause heartbeat monitoring\r\n - \\`shadow resume\\` — resume heartbeat monitoring\r\n - \\`shadow interval <ms>\\` — change heartbeat interval\r\n - \\`shadow model <model-id>\\` — change analysis model\r\n\r\n## Operating Rules\r\n\r\n- **Silent by default**: Use DEBUG level logging unless anomaly detected\r\n- **Deterministic**: Same state always produces same actions — no randomness\r\n- **Report on anomaly**: When anomaly detected, use \\`mail_send\\` to broadcast warning\r\n- **Never auto-intervene**: Always report unless explicitly commanded\r\n- **Minimal footprint**: Small state, efficient snapshots\r\n\r\n## Startup Sequence\r\n\r\n1. Send broadcast: \\`shadow:started { intervalMs, model, startTime }\\`\r\n2. Subscribe to FleetBus for all relevant events\r\n3. Schedule heartbeat cron job at configured interval\r\n4. Wait for commands or anomalies\r\n\r\n## Shutdown Sequence\r\n\r\n1. Cancel all cron jobs (\\`cron_cancel\\`)\r\n2. Send broadcast: \\`shadow:stopped { reason, finalState }\\`\r\n3. Clean up FleetBus subscriptions`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n 'shadow-agent': SHADOW_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number | undefined;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number | undefined;\r\n maxIterations?: number | undefined;\r\n maxToolCalls?: number | undefined;\r\n maxTokens?: number | undefined;\r\n maxCostUsd?: number | undefined;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n 'shadow-agent': { timeoutMs: 24 * 60 * 60 * 1000, maxIterations: 10000, maxToolCalls: 5000 }, // Long-running background monitor\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.entries(NICKNAME_POOL) as [NicknameKey, { name: string; domain: string }][];\n\n/** Reverse index: display name (e.g. \"Von Neumann\") → canonical pool key. */\nconst NAME_TO_KEY: Record<string, string> = Object.fromEntries(\n ALL_NICKNAMES.map(([key, entry]) => [entry.name, key]),\n);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/** Result of a nickname assignment. */\nexport interface NicknameAssignment {\n /**\n * Canonical pool key (e.g. `von-neumann`). This — NOT the display string — is\n * what callers must add to their `used` set and later remove on release.\n * Deriving the key by parsing the display string is unsafe: multi-word names\n * like \"Von Neumann\" would be truncated to \"von\" and never dedupe correctly.\n */\n key: string;\n /** Human display string, e.g. `Von Neumann (Backend)`. */\n display: string;\n}\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n *\n * Returns both the canonical pool `key` (for the `used` set) and the formatted\n * `display` string (`Name (Role)`, e.g. `Einstein (Bug Hunter)`).\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname KEYS already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): NicknameAssignment {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style.\n for (const [key, entry] of ALL_NICKNAMES) {\n if (!used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 4. Pool exhausted — synthesize a stable, unique key/display pair.\n const counter = used.size + 1;\n return { key: `scientist-${counter}`, display: `Scientist #${counter} (${formatRole(role)})` };\n}\n\n/**\n * Resolve a previously-assigned display string back to its canonical pool key,\n * for release paths that only retained the formatted name (e.g. a manifest\n * entry). Strips the trailing ` (Role)` suffix, then matches the base name\n * against the pool. Returns `undefined` when the name is not a known nickname.\n *\n * Use this instead of `name.split(' ')[0]` — the latter mangles multi-word\n * names like \"Von Neumann\" and \"Berners-Lee\".\n */\nexport function nicknameKeyFromDisplay(display: string): string | undefined {\n const base = display.replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const key = NAME_TO_KEY[base];\n if (key) return key;\n const synthesized = base.match(/^Scientist #(\\d+)$/);\n return synthesized ? `scientist-${synthesized[1]}` : undefined;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}\n","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport {\r\n BudgetExceededError,\r\n DECISION_TIMEOUT_MS,\r\n SubagentBudget,\r\n TIMEOUT_PREEMPT_FRACTION as _preemptFraction,\r\n} from './subagent-budget.js';\r\nimport { classifySubagentError } from './coordinator/error-classifier.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string | undefined;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget | undefined;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner | undefined;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner | undefined;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus | undefined;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n // awaitTasks() registers one short-lived 'task.completed' listener per\r\n // awaited id; a single call awaiting >10 ids (or several concurrent\r\n // callers) crosses Node's default 10-listener cap and prints a spurious\r\n // MaxListenersExceededWarning that also masks genuine leaks. These waiters\r\n // are bounded and self-removing, so lift the cap.\r\n this.setMaxListeners(0);\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const { key, display } = assignNickname(role, this.usedNicknames);\r\n this.usedNicknames.add(key);\r\n this.subagentNicknames.set(subagentId, key);\r\n return { ...subagent, name: display };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n const cfg = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...cfg, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...cfg, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i];\r\n if (!task) continue;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) this.emitPendingAborted(t, message);\r\n }\r\n\r\n /**\r\n * Emit a synthetic `stopped`/`aborted_by_parent` completion for a single\r\n * PENDING task — one that was never counted in `inFlight`. This MUST bypass\r\n * `recordCompletion`: that path does `inFlight--`, which for a pending task\r\n * steals a decrement from a genuinely in-flight task and trips the underflow\r\n * guard — suppressing that real task's `task.completed` and hanging its\r\n * `awaitTasks()` caller. Pushes the result and fires the event directly.\r\n */\r\n private emitPendingAborted(task: TaskSpec, message: string): void {\r\n const synthetic: TaskResult = {\r\n subagentId: task.subagentId ?? 'unassigned',\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task, result: synthetic });\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(\r\n this.runner,\r\n task,\r\n runCtx,\r\n budget,\r\n subagent.config.preemptFraction,\r\n );\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n preemptFraction: number = _preemptFraction,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n // Pre-empt arm state machine:\r\n // ACTIVE — pre-empt can fire for the current ceiling window\r\n // LOCKED — pre-empt is locked; cannot fire until ceiling changes\r\n enum PreemptState {\r\n ACTIVE = 'active',\r\n LOCKED = 'locked',\r\n }\r\n // The wall-clock ceiling value at the moment the state was locked.\r\n // Compared against the current wallLimit to detect stale locks caused by\r\n // external calls to budget.patchLimits().\r\n let preemptedCeiling: number | null = null;\r\n let preemptState: PreemptState = PreemptState.ACTIVE;\r\n // Heartbeat gate for the proactive pre-empt: the timestamp of the subagent's\r\n // last activity at the moment of the most recent grant. A later pre-empt is\r\n // only negotiated if there has been NEW activity since then — a stalled\r\n // agent (no progress since its last grant) gets no further extension and is\r\n // left to the real deadline. `-1` until the first grant so the first\r\n // pre-empt always fires. Activity time is derived from `budget.idleMs()`\r\n // (reset by tool calls / iterations / streamed progress), so it works even\r\n // for runners that don't increment the budget's usage counters directly.\r\n let lastGrantActivityTs = -1;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n // Terminate the subagent, classifying by whether a negotiation listener\r\n // is wired. A listener-observed stop (explicit deny at the deadline, or an\r\n // idle reap while observed) surfaces as 'stopped' — reject with a\r\n // non-budget error so the coordinator's catch falls to `signal.aborted →\r\n // 'stopped'`. With no listener it is an unattended budget breach →\r\n // BudgetExceededError → 'timeout'. This keeps a bare /spawn reporting\r\n // 'timeout' while a director/observer-driven stop reads as 'stopped'.\r\n const terminate = (kind: 'timeout' | 'idle_timeout', limit: number, used: number) => {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n budget._events?.hasListenerFor('budget.threshold_reached')\r\n ? new Error(`subagent stopped: budget ${kind} (limit=${limit}, used=${used})`)\r\n : new BudgetExceededError(kind, limit, used),\r\n );\r\n };\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity), the explicit wall-clock cap, or the PROACTIVE\r\n // pre-empt point (a fraction of the wall cap, see TIMEOUT_PREEMPT_FRACTION)\r\n // at which we negotiate an extension BEFORE the deadline is crossed. Any\r\n // being unset/already-asked drops out of the min, so single-limit configs\r\n // behave exactly as that limit alone.\r\n const scheduleNext = () => {\r\n const wallLimit = budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n const preemptRemaining =\r\n initialTimeoutMs === undefined || preemptedCeiling === wallLimit\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) * preemptFraction - (Date.now() - start);\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining, preemptRemaining)));\r\n };\r\n\r\n // Drive a timeout extension negotiation (used by BOTH the proactive\r\n // pre-empt and the at-deadline path). Resolves to the coordinator's\r\n // verdict: `{ extend: { timeoutMs } }` to grant, or a string to decline.\r\n // The budget's requestDecision falls back to 'stop' on no response, so\r\n // this never hangs.\r\n // Safety net: if no listener responds to the budget.threshold_reached event\r\n // within DECISION_TIMEOUT_MS (60 s), default to 'stop' so the watchdog\r\n // never hangs. Uses the exported DECISION_TIMEOUT_MS so both paths share\r\n // the same value — coordinator and budget agree on the ceiling.\r\n const negotiateTimeout = async (\r\n used: number,\r\n limit: number,\r\n ): Promise<'stop' | 'continue' | 'throw' | { extend: { timeoutMs?: number | undefined } }> => {\r\n const handler = budget.onThreshold;\r\n if (!handler) return 'stop';\r\n const result = handler({\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n requestDecision: () => {\r\n // No listener wired (bare /spawn, no director) → nobody can grant an\r\n // extension, so resolve to 'stop' immediately. Without this the emit\r\n // below goes unanswered and the run parks on the 60 s fallback timer\r\n // before stopping — the deadline must reap promptly instead. Mirrors\r\n // SubagentBudget._busRequestDecision so both agree on the default.\r\n if (!budget._events?.hasListenerFor('budget.threshold_reached')) {\r\n return Promise.resolve<'stop' | { extend: { timeoutMs?: number | undefined } }>('stop');\r\n }\r\n return new Promise<'stop' | { extend: { timeoutMs?: number | undefined } }>((resolveDecision) => {\r\n let settled = false;\r\n const resolve = (d: 'stop' | { extend: { timeoutMs?: number | undefined } }) => {\r\n if (settled) return;\r\n settled = true;\r\n resolveDecision(d);\r\n };\r\n const fallback = setTimeout(() => resolve('stop'), DECISION_TIMEOUT_MS);\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n // Informational: the budget's own decision deadline. Listeners may use\r\n // this to display a countdown. The coordinator does NOT enforce it —\r\n // it is the budget's own `setTimeout(fallback)` that races against\r\n // the listener's `extend()`/`deny()` call to guarantee progress.\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n // deny() wins over a same-dispatch extend(): defer the grant a\r\n // microtask so a synchronous deny in the same emit pre-empts it\r\n // (a listener that both grants and denies, or two listeners\r\n // disagreeing, resolves as a stop). Async grants still resolve.\r\n extend: (extra) => {\r\n clearTimeout(fallback);\r\n queueMicrotask(() => resolve({ extend: extra }));\r\n },\r\n deny: () => {\r\n clearTimeout(fallback);\r\n resolve('stop');\r\n },\r\n });\r\n });\r\n },\r\n });\r\n return typeof result === 'string' ? result : await result;\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is NOT\r\n // negotiable; the point of the default is to free a stuck slot. We still\r\n // emit the threshold event first so observers (director / monitor) can\r\n // record the reap, but any extension a listener offers is ignored.\r\n if (idleExceeded && !wallExceeded) {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'idle_timeout',\r\n used: budget.idleMs(),\r\n limit: idleLimit ?? 0,\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n extend: () => {},\r\n deny: () => {},\r\n });\r\n // An idle stall is a passive TIMEOUT (the agent hung), not an explicit\r\n // coordinator stop — surface it as 'timeout' regardless of any\r\n // listener. (Contrast the wall-clock deadline below, where an explicit\r\n // listener deny is a deliberate stop → 'stopped'.)\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('idle_timeout', idleLimit ?? 0, budget.idleMs()));\r\n return;\r\n }\r\n\r\n // PROACTIVE pre-empt: we've passed TIMEOUT_PREEMPT_FRACTION of the wall\r\n // window but NOT the deadline itself. Negotiate an extension now, while\r\n // the agent is still under its limit, so a progressing subagent gets its\r\n // ceiling raised and never enters a timed-out state. Heartbeat-gated on\r\n // the granting side (director / attachAutoExtend): no progress ⇒ decline,\r\n // and we fall through to the real-deadline behaviour below at the cap.\r\n // Asked at most once per window (preemptState === ACTIVE).\r\n if (\r\n wallLimit !== undefined &&\r\n !wallExceeded &&\r\n budget.onThreshold &&\r\n preemptState === PreemptState.ACTIVE &&\r\n elapsed >= wallLimit * preemptFraction\r\n ) {\r\n // Heartbeat gate: only negotiate a pre-empt extension if the agent has\r\n // made progress (a tool call / iteration / streamed output) SINCE the\r\n // last grant. A stalled agent — no new activity since its last\r\n // extension — gets no further pre-empt; we lock and let the real\r\n // deadline reap it. `activityTs` is the wall-clock time of the last\r\n // activity (now − idleMs). Without this gate an always-granting\r\n // listener would extend a wedged agent forever and the deadline would\r\n // never fire (T1).\r\n const activityTs = Date.now() - budget.idleMs();\r\n if (activityTs <= lastGrantActivityTs) {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n scheduleNext();\r\n return;\r\n }\r\n // C1 fix: register the watchdog as active BEFORE calling onThreshold so\r\n // that any concurrent tool.progress → checkTimeout() path sees the flag\r\n // and skips its own wall-clock emission. Cleared on every exit path so\r\n // checkTimeout() resumes normal operation after negotiation completes.\r\n budget.setWatchdogNegotiation(wallLimit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, wallLimit);\r\n if (typeof decision !== 'string' && decision.extend.timeoutMs !== undefined) {\r\n // Granted ahead of the deadline — raise the ceiling and open a\r\n // fresh window (a later pre-empt becomes eligible again, but only\r\n // if there is fresh activity by then — see the heartbeat gate).\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n } else {\r\n // Declined proactively (no progress / no listener). Don't re-ask\r\n // until the real deadline — the wallExceeded path below handles the\r\n // at-cap behaviour (warn+continue or hard stop).\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n }\r\n } catch {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n } finally {\r\n budget.clearWatchdogNegotiation();\r\n }\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out (or a pre-empt was just resolved).\r\n // Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit ?? 0;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // C1 fix: same guard as the pre-empt branch — register before onThreshold\r\n // so concurrent tool.progress → checkTimeout() skips its wall-clock emission.\r\n budget.setWatchdogNegotiation(limit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, limit);\r\n if (decision === 'throw') {\r\n // 'throw' is an explicit signal from the handler: end now rather\r\n // than silently keeping the subagent alive past its deadline.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n if (decision === 'continue') {\r\n // 'continue' — timeout denied but coordinator wants the agent to keep\r\n // running. Re-arm for a full wall window so we ask again later.\r\n // This makes wall-clock timeout a pure warning event: the subagent\r\n // keeps running until it naturally finishes, the next deadline fires,\r\n // or the user stops it.\r\n //\r\n // IMPORTANT: we must lock the pre-empt arm (set preemptState =\r\n // LOCKED) so it does NOT fire again until the ceiling changes.\r\n // The ceiling only changes if a future negotiation returns 'extend'\r\n // and patches budget.limits.timeoutMs. Without the lock, the\r\n // pre-empt would re-arm for ~1 s (Math.max(1_000, limit)) and\r\n // immediately fire again at elapsed > wallLimit × 0.85, creating\r\n // a ping-pong loop of spurious budget.threshold_reached events.\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n if (decision === 'stop') {\r\n // 'stop' — coordinator explicitly denied the extension and wants\r\n // the agent to end. This is a terminal decision: end now.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — nothing to grant → end.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n return;\r\n } finally {\r\n // Always clear the watchdog flag so checkTimeout() resumes wall-clock\r\n // checking on the next tool.progress event.\r\n budget.clearWatchdogNegotiation();\r\n }\r\n };\r\n // First arm: whichever of the idle window / pre-empt point / wall cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n result: result.result,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n // Inline-emit, NOT recordCompletion: these are PENDING tasks that were\r\n // never counted in inFlight. Routing them through recordCompletion would\r\n // decrement inFlight on behalf of a still-running task and suppress that\r\n // task's own completion via the underflow guard, hanging its awaiter.\r\n this.emitPendingAborted(\r\n t,\r\n `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n );\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. Delegates to the shared classifier.\r\n * Re-exported for backward compatibility.\r\n */\r\nexport { classifySubagentError } from './coordinator/error-classifier.js';\r\n","import { expectDefined } from '../utils/expect-defined.js';\n/**\n * SddParallelRun\n *\n * Drives a TaskGraph through ParallelEternalEngine's infrastructure\n * (DefaultMultiAgentCoordinator + AgentSubagentRunner) but powered by\n * SddTaskDecomposer — producing dependency-aware waves instead of\n * goal-driven iterations.\n *\n * One-shot: completes when all tasks are done OR a deadlock is detected.\n * Does NOT loop — each run() call is a discrete execution.\n *\n * Usage:\n * ```\n * const run = new SddParallelRun({ tracker, graph, agent, projectRoot });\n * await run.run({ onWave });\n * // or with progress callback:\n * await run.run({ onProgress: (p) => console.log(renderProgress(p)) });\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { SubagentConfig, TaskResult, TaskSpec } from '../types/multi-agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner, withDisabledToolFiltering } from '../coordination/agent-subagent-runner.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\nimport type { TaskGraph, TaskProgress } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { SddTaskDecomposer, type TaskBatch } from './sdd-task-decomposer.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nexport interface SddParallelRunOptions {\n /** Pre-constructed TaskTracker (must already hold the graph's initial state). */\n tracker: TaskTracker;\n /** The TaskGraph produced by TaskGenerator from an approved spec. */\n graph: TaskGraph;\n /** The main agent — used as the subagent factory. */\n agent: Agent;\n /** Project root (used for coordinator id). */\n projectRoot: string;\n /** Override default parallel slots (1–16). Default: 4. */\n parallelSlots?: number | undefined;\n /** Per-task timeout in ms. Default: 300_000 (5 min). */\n taskTimeoutMs?: number | undefined;\n /** Maximum retry attempts for failed tasks. Default: 2. */\n maxRetries?: number | undefined;\n /** Override the default agent factory. */\n subagentFactory?: AgentFactory | undefined;\n /** Called after each wave completes. */\n onWave?: ((wave: WaveResult) => void) | undefined;\n /** Called with progress stats every ~2s during execution. */\n onProgress?: ((progress: SddProgress) => void) | undefined;\n}\n\nexport interface SddProgress {\n wave: number;\n total: number;\n completed: number;\n inProgress: number;\n failed: number;\n blocked: number;\n pending: number;\n percent: number;\n deadlocked: boolean;\n}\n\nexport interface WaveResult {\n wave: number;\n batch: TaskBatch;\n results: TaskResult[];\n successCount: number;\n failCount: number;\n durationMs: number;\n stopRequested: boolean;\n}\n\nexport interface RunResult {\n totalWaves: number;\n totalCompleted: number;\n totalFailed: number;\n totalDurationMs: number;\n deadlocked: boolean;\n stopRequested: boolean;\n finalProgress: TaskProgress;\n}\n\nexport class SddParallelRun {\n private readonly slots: number;\n private readonly timeoutMs: number;\n private readonly maxRetries: number;\n private decomposer: SddTaskDecomposer;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private stopRequested = false;\n private retryMap = new Map<string, number>();\n\n constructor(private readonly opts: SddParallelRunOptions) {\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n this.timeoutMs = opts.taskTimeoutMs ?? 300_000;\n this.maxRetries = Math.max(0, opts.maxRetries ?? 2);\n this.decomposer = new SddTaskDecomposer(opts.tracker, opts.graph, { parallelSlots: this.slots });\n }\n\n // -------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------\n\n /** Trigger stop — causes run() to abort after the current wave. */\n stop(): void {\n this.stopRequested = true;\n this.coordinator?.stopAll();\n }\n\n /** Execute all waves until completion or deadlock. Returns final summary. */\n async run(): Promise<RunResult> {\n this.stopRequested = false;\n this.retryMap.clear();\n const startTime = Date.now();\n let totalCompleted = 0;\n let totalFailed = 0;\n let totalWaves = 0;\n\n this.buildCoordinator();\n\n while (!this.stopRequested && !this.decomposer.isDone()) {\n const batch = this.decomposer.nextBatch();\n\n if (batch.deadlocked) {\n // No runnable tasks and some are blocked — deadlock\n break;\n }\n\n if (batch.tasks.length === 0 && batch.allDone) {\n // Graph completed\n break;\n }\n\n const waveResult = await this.executeWave(batch);\n totalWaves++;\n totalCompleted += waveResult.successCount;\n totalFailed += waveResult.failCount;\n\n this.decomposer.acknowledgeBatch(batch.tasks.map(t => t.id));\n this.opts.onWave?.(waveResult);\n\n // Emit progress\n const progress = this.buildProgress();\n this.opts.onProgress?.(progress);\n\n if (this.stopRequested) break;\n }\n\n const finalProgress = this.opts.tracker.getProgress();\n\n return {\n totalWaves,\n totalCompleted,\n totalFailed,\n totalDurationMs: Date.now() - startTime,\n deadlocked: !this.decomposer.isDone() && this.stopRequested === false,\n stopRequested: this.stopRequested,\n finalProgress,\n };\n }\n\n // -------------------------------------------------------------------\n // Internal\n // -------------------------------------------------------------------\n\n private buildCoordinator(): void {\n const config: MultiAgentConfig = {\n coordinatorId: `sdd-parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const baseFactory = this.opts.subagentFactory ?? this.defaultFactory();\n const filteredFactory = withDisabledToolFiltering(baseFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n private defaultFactory(): AgentFactory {\n return async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n });\n }\n\n async executeWave(batch: TaskBatch): Promise<WaveResult> {\n const wave = batch.wave;\n const tasks = batch.tasks;\n const waveStart = Date.now();\n\n // Mark all tasks as in_progress\n for (const task of tasks) {\n this.opts.tracker.updateNodeStatus(task.id, 'in_progress');\n }\n\n const progress = computeTaskProgress(this.opts.graph);\n\n const taskIds: string[] = tasks.map(() => randomUUID());\n const subagentIds: string[] = tasks.map((_, i) => `sdd-wave${wave}-${i}`);\n\n // Build directive preamble\n const directivePreamble = [\n '═══ SDD PARALLEL EXECUTION ═══',\n '',\n `Wave ${wave + 1} of ~${Math.ceil(progress.total / this.slots)}`,\n `Graph: ${this.opts.graph.title}`,\n `Parallel slots: ${tasks.length}`,\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned SDD task end-to-end using multiple tool calls.',\n '• Mark the task [done] in the tracker when complete.',\n '• Do not ask before routine in-project tool use; if a permission gate appears, wait for that flow.',\n '• Keep output concise — summarize changes, do not transcribe files.',\n ].join('\\n');\n\n // Phase 1: spawn all subagents\n if (!this.coordinator) throw new SddError({\n message: 'SDD parallel runner requires a coordinator',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n const coordinator = this.coordinator;\n const spawns = subagentIds.map((subagentId) =>\n coordinator.spawn({\n id: subagentId,\n name: subagentId,\n role: 'executor',\n timeoutMs: this.timeoutMs,\n // Disable delegation — subagents are leaf workers, not orchestrators\n disabledTools: ['delegate'],\n }),\n );\n const spawnResults = await Promise.all(spawns);\n // All spawns succeeded or we bail entirely — no partial waves\n if (!spawnResults.every((r) => Boolean(r.subagentId))) {\n throw new SddError({\n message: 'One or more subagent spawns failed',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n }\n\n // Phase 2: assign task specs to spawned subagents\n const assignPromises = tasks.map((task, i) => {\n const spec: TaskSpec = {\n id: taskIds[i] ?? task.id,\n description: [\n directivePreamble,\n '',\n `── TASK ${i + 1}/${tasks.length} ──`,\n `[${task.priority.toUpperCase()}] ${task.title}`,\n '',\n task.description,\n ].join('\\n'),\n subagentId: subagentIds[i] ?? spawnResults[i]?.subagentId ?? task.id,\n timeoutMs: this.timeoutMs,\n };\n return this.coordinator?.assign(spec);\n });\n await Promise.all(assignPromises);\n\n // Phase 3: wait for all task results\n let results: TaskResult[];\n try {\n results = await coordinator.awaitTasks(taskIds);\n } catch (err) {\n // await threw — synthesize error results for all pending tasks\n results = taskIds.map((id) => ({\n subagentId: '',\n taskId: id,\n status: 'failed' as const,\n error: { kind: 'unknown' as const, message: String(err), retryable: false },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n }));\n }\n\n const successCount = results.filter((r) => r.status === 'success').length;\n const failCount = results.length - successCount;\n\n // Phase 4: update tracker status for each result, with retry support.\n // The tracker is keyed by the *graph node id* (`tasks[i].id`), not the\n // per-wave correlation id in `taskIds` (a fresh randomUUID each wave) —\n // results come back index-aligned with the dispatched `tasks`, so the\n // node id is recovered positionally. Using `taskIds[i]` here would throw\n // \"Node <uuid> not found\" and break retry accounting across waves.\n for (let i = 0; i < results.length; i++) {\n const result = expectDefined(results[i]);\n const taskId = expectDefined(tasks[i]).id;\n if (result.status === 'success') {\n this.opts.tracker.updateNodeStatus(taskId, 'completed');\n this.retryMap.delete(taskId);\n } else {\n const errMsg = result.error?.kind\n ? `${result.error.kind}: ${result.error.message}`\n : result.error?.message ?? 'unknown error';\n // Retry: re-mark as pending if retries remain\n const currentRetries = this.retryMap.get(taskId) ?? 0;\n if (currentRetries < this.maxRetries) {\n this.retryMap.set(taskId, currentRetries + 1);\n this.opts.tracker.updateNodeStatus(\n taskId,\n 'pending',\n `Retry ${currentRetries + 1}/${this.maxRetries}: ${errMsg}`,\n );\n } else {\n this.opts.tracker.updateNodeStatus(taskId, 'failed', errMsg);\n }\n }\n }\n\n return {\n wave,\n batch,\n results,\n successCount,\n failCount,\n durationMs: Date.now() - waveStart,\n stopRequested: this.stopRequested,\n };\n }\n\n private buildProgress(): SddProgress {\n const gp = this.opts.tracker.getProgress();\n const isDeadlocked = !this.decomposer.isDone() &&\n this.decomposer.nextBatch().deadlocked;\n return {\n wave: this.decomposer.getWaveCount(),\n total: gp.total,\n completed: gp.completed,\n inProgress: gp.inProgress,\n failed: gp.failed,\n blocked: gp.blocked,\n pending: gp.pending,\n percent: gp.percentComplete,\n deadlocked: isDeadlocked,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/atomic-write.ts","../../src/sdd/spec-parser.ts","../../src/sdd/task-generator.ts","../../src/types/task-graph.ts","../../src/utils/assert-never.ts","../../src/utils/child-env.ts","../../src/utils/error.ts","../../src/utils/expect-defined.ts","../../src/utils/string.ts","../../src/types/errors.ts","../../src/sdd/task-tracker.ts","../../src/sdd/task-flow.ts","../../src/sdd/spec-store.ts","../../src/sdd/task-graph-store.ts","../../src/sdd/board-types.ts","../../src/sdd/sdd-board-store.ts","../../src/sdd/sdd-board-projector.ts","../../src/sdd/sdd-run-registry.ts","../../src/sdd/spec-builder.ts","../../src/sdd/sdd-interview-driver.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/types/provider.ts","../../src/coordination/coordinator/error-classifier.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/sdd/sdd-task-decomposer.ts","../../src/sdd/sdd-parallel-run.ts","../../src/sdd/start-sdd-run.ts","../../src/worktree/worktree-manager.ts","../../src/sdd/sdd-lifecycle.ts","../../src/sdd/spec-templates.ts","../../src/sdd/task-visualizer.ts","../../src/sdd/critical-path.ts","../../src/sdd/spec-versioning.ts","../../src/sdd/auto-executor.ts","../../src/core/fallback-model.ts","../../src/sdd/sdd-supervisor.ts","../../src/sdd/verify-task.ts","../../src/sdd/decompose-task.ts","../../src/sdd/conflict-resolver.ts"],"names":["stat","resolve","path2","fsp","path3","fsp2","path4","fsp3","path","atomicWrite","first","baseMessage","randomUUID","PreemptState","join","mkdir","rm","fsp4","spawn","TASK_TYPES","readFile","writeFile"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,WAAA,EAAA,MAAA,WAAA;AAAA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ACA,MAAA,IAAI;AACF,QAAA,MAAMC,SAAAA,CAAU,GAAA,EAAK,QAAA,EAAU,MAAM,CAAA;AAAA,MACvC,CAAA,CAAA,MAAQ;AACN,QAAA,OAAO,KAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n const timeoutMs = opts.timeoutMs ?? 5_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`Timed out waiting for file lock: ${targetPath}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import type {\n SpecAnalysis,\n SpecRequirement,\n SpecSection,\n SpecValidationResult,\n Specification,\n} from '../types/spec.js';\n\nexport class SpecParser {\n parse(content: string): Specification {\n const lines = content.split('\\n');\n const sections = this.extractSections(lines);\n const requirements = this.extractRequirements(lines);\n const now = Date.now();\n\n return {\n id: crypto.randomUUID(),\n title: this.extractTitle(lines),\n version: this.extractVersion(lines),\n status: 'draft',\n overview: this.extractOverview(lines),\n sections,\n requirements,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n private extractTitle(lines: string[]): string {\n for (const line of lines) {\n const m = /^#\\s+(.+)/.exec(line.trim());\n if (m?.[1]) return m[1];\n }\n return 'Untitled Specification';\n }\n\n private extractVersion(lines: string[]): string {\n for (const line of lines) {\n const m = /version[:\\s]+(\\d+\\.\\d+\\.\\d+)/i.exec(line.trim());\n if (m?.[1]) return m[1];\n }\n return '0.0.1';\n }\n\n private extractOverview(lines: string[]): string {\n const overviewLines: string[] = [];\n let inOverview = false;\n let foundHeading = false;\n\n for (const line of lines) {\n if (/^##\\s+Overview/i.test(line.trim())) {\n inOverview = true;\n foundHeading = true;\n continue;\n }\n if (foundHeading && /^##\\s+/.test(line.trim())) break;\n if (inOverview) overviewLines.push(line);\n }\n\n return overviewLines.join('\\n').trim() || 'No overview provided';\n }\n\n private extractSections(lines: string[]): SpecSection[] {\n const sections: SpecSection[] = [];\n let currentSection: Partial<SpecSection> | null = null;\n let currentLines: string[] = [];\n let depth = 1;\n\n for (const line of lines) {\n const h2 = /^##\\s+(.+)/.exec(line.trim());\n const h3 = /^###\\s+(.+)/.exec(line.trim());\n\n if (h2) {\n if (currentSection && currentLines.length > 0) {\n sections.push({\n type: this.mapSectionType(currentSection.title ?? 'unknown'),\n title: currentSection.title ?? 'Unknown',\n level: depth,\n content: currentLines.join('\\n').trim(),\n });\n }\n currentSection = { title: h2[1] ?? 'Unknown' };\n currentLines = [];\n depth = 2;\n continue;\n }\n\n if (h3) {\n currentLines.push(line);\n continue;\n }\n\n if (currentSection) {\n currentLines.push(line);\n }\n }\n\n if (currentSection && currentLines.length > 0) {\n sections.push({\n type: this.mapSectionType(currentSection.title ?? 'unknown'),\n title: currentSection.title ?? 'Unknown',\n level: depth,\n content: currentLines.join('\\n').trim(),\n });\n }\n\n return sections;\n }\n\n private extractRequirements(lines: string[]): SpecRequirement[] {\n const requirements: SpecRequirement[] = [];\n let inRequirements = false;\n let idCounter = 0;\n\n for (const line of lines) {\n if (/^##\\s+Requirements/i.test(line.trim())) {\n inRequirements = true;\n continue;\n }\n if (inRequirements && /^##\\s+/.test(line.trim())) break;\n\n if (inRequirements) {\n const req = this.parseRequirementLine(line, `REQ-${++idCounter}`);\n if (req) requirements.push(req);\n }\n }\n\n return requirements;\n }\n\n private parseRequirementLine(line: string, id: string): SpecRequirement | null {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) return null;\n\n const lower = trimmed.toLowerCase();\n const types: SpecRequirement['type'][] = [\n 'functional',\n 'non-functional',\n 'security',\n 'performance',\n 'ux',\n ];\n let type: SpecRequirement['type'] = 'functional';\n for (const t of types) {\n if (lower.includes(`[${t}]`)) type = t;\n }\n\n let priority: SpecRequirement['priority'] = 'medium';\n if (trimmed.includes('[critical]') || trimmed.includes('[prio:high]')) {\n priority = 'critical';\n } else if (trimmed.includes('[high]')) {\n priority = 'high';\n } else if (trimmed.includes('[low]')) {\n priority = 'low';\n }\n\n return {\n id,\n type,\n priority,\n description: trimmed.replace(/\\[[^\\]]+\\]/g, '').trim(),\n acceptanceCriteria: [],\n };\n }\n\n private mapSectionType(title: string): SpecSection['type'] {\n const t = title.toLowerCase();\n if (t.includes('overview')) return 'overview';\n if (t.includes('requirement')) return 'requirements';\n if (t.includes('architect')) return 'architecture';\n if (t.includes('api')) return 'api';\n if (t.includes('data')) return 'data';\n if (t.includes('security')) return 'security';\n if (t.includes('acceptance')) return 'acceptance';\n return 'overview';\n }\n\n analyze(spec: Specification): SpecAnalysis {\n const gaps: string[] = [];\n const suggestions: string[] = [];\n const risks: SpecAnalysis['risks'] = [];\n\n // Check completeness\n const hasOverview = spec.sections.some((s) => s.type === 'overview');\n const hasRequirements = spec.sections.some((s) => s.type === 'requirements');\n const hasAcceptance = spec.sections.some((s) => s.type === 'acceptance');\n\n if (!hasOverview) gaps.push('Missing Overview section');\n if (!hasRequirements) gaps.push('Missing Requirements section');\n if (!hasAcceptance) gaps.push('Missing Acceptance Criteria section');\n\n if (spec.requirements.length === 0) {\n gaps.push('No requirements defined');\n suggestions.push('Add specific functional and non-functional requirements');\n }\n\n const unverifiedReqs = spec.requirements.filter((r) => r.acceptanceCriteria.length === 0);\n if (unverifiedReqs.length > 0) {\n gaps.push(`${unverifiedReqs.length} requirements without acceptance criteria`);\n suggestions.push('Define clear acceptance criteria for each requirement');\n }\n\n const criticalUnresolved = spec.requirements.filter(\n (r) => r.priority === 'critical' && r.blockedBy && r.blockedBy.length > 0,\n );\n for (const req of criticalUnresolved) {\n risks.push({\n requirement: req.id,\n risk: `Critical requirement blocked by ${req.blockedBy?.length} other requirements`,\n severity: 'high',\n });\n }\n\n const completeness = Math.round(\n (((hasOverview ? 1 : 0) +\n (hasRequirements ? 1 : 0) +\n (hasAcceptance ? 1 : 0) +\n (spec.requirements.length > 0 ? 1 : 0) +\n (spec.sections.length > 3 ? 1 : 0)) /\n 5) *\n 100,\n );\n\n return {\n specId: spec.id,\n completeness,\n coverage: {\n requirements: spec.requirements.length,\n apiEndpoints: spec.apiEndpoints?.length ?? 0,\n edgeCases: 0,\n errorHandling: 0,\n },\n gaps,\n risks,\n suggestions,\n };\n }\n\n validate(spec: Specification): SpecValidationResult {\n const errors: SpecValidationResult['errors'] = [];\n const warnings: SpecValidationResult['warnings'] = [];\n\n if (!spec.title.trim()) {\n errors.push({ path: 'title', message: 'Title is required' });\n }\n\n if (!spec.version.trim()) {\n errors.push({ path: 'version', message: 'Version is required' });\n }\n\n for (const req of spec.requirements) {\n if (!req.description.trim()) {\n errors.push({ path: `requirement.${req.id}`, message: 'Requirement description is empty' });\n }\n if (req.acceptanceCriteria.length === 0) {\n warnings.push({ path: `requirement.${req.id}`, message: 'No acceptance criteria defined' });\n }\n }\n\n const reqIds = new Set(spec.requirements.map((r) => r.id));\n const blockedByIds = new Set(spec.requirements.flatMap((r) => r.blockedBy ?? []));\n for (const id of blockedByIds) {\n if (!reqIds.has(id)) {\n errors.push({\n path: 'requirements',\n message: `BlockedBy references non-existent requirement: ${id}`,\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n }\n}\n","import type { SpecRequirement, Specification } from '../types/spec.js';\nimport type { TaskGraph, TaskNode, TaskPriority, TaskType } from '../types/task-graph.js';\nimport type { TaskStore, TaskTracker } from './task-tracker.js';\n\nexport interface TaskGeneratorOptions {\n taskTracker: TaskTracker;\n /**\n * Opt-in (default off): derive each task's completion-gate\n * `metadata.verificationCommand` from an acceptance criterion that carries a\n * runnable-command marker (`$ <cmd>`, or `run:`/`verify:`/`cmd:` prefix). Off\n * by default so the common case stays fast — auto-running a check per task is\n * exactly the slowness the robustness initiative set out to avoid; enable it\n * explicitly (the CLI gates it behind WRONGSTACK_SDD_VERIFY_FROM_ACCEPTANCE).\n */\n verificationFromAcceptance?: boolean | undefined;\n}\n\n/**\n * Pull a runnable verification command out of a requirement's acceptance\n * criteria. A criterion qualifies only when it carries an explicit marker —\n * `$ <cmd>` (shell-prompt style) or a `run:` / `verify:` / `cmd:` prefix — so\n * free-text criteria are never mistaken for commands. Returns the first match.\n */\nexport function extractVerificationCommand(criteria: readonly string[]): string | undefined {\n const marker = /^\\s*(?:\\$\\s+|(?:run|verify|cmd)\\s*:\\s*)(.+\\S)\\s*$/i;\n for (const c of criteria) {\n const m = marker.exec(c);\n if (m?.[1]) return m[1].trim();\n }\n return undefined;\n}\n\nexport interface GeneratedTask {\n specRequirementId?: string | undefined;\n title: string;\n description: string;\n type: TaskType;\n priority: TaskPriority;\n estimateHours?: number | undefined;\n tags?: string[] | undefined;\n}\n\nexport class TaskGenerator {\n constructor(private readonly opts: TaskGeneratorOptions) {}\n\n async generateFromSpec(spec: Specification): Promise<TaskGraph> {\n const graph = await this.opts.taskTracker.createGraph(spec.id, spec.title);\n\n // Track feature/implementation node ids so the deterministic fallback still\n // produces a real DAG: tests depend on the features they cover, docs depend\n // on everything. Without this the generated graph is edgeless and every task\n // looks independently runnable (the naive slot-filling the user rejected).\n const featureIds: string[] = [];\n\n const overview = spec.sections.find((s) => s.type === 'overview');\n if (overview) {\n featureIds.push(\n this.opts.taskTracker.addNode({\n title: `Implement ${spec.title}`,\n description: overview.content,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n }).id,\n );\n }\n\n // Group requirements by priority in a single pass, then emit in priority order.\n const byPriority: Record<TaskPriority, SpecRequirement[]> = {\n critical: [],\n high: [],\n medium: [],\n low: [],\n };\n for (const req of spec.requirements) {\n const bucket = byPriority[req.priority] ?? byPriority.medium;\n bucket.push(req);\n }\n\n const order: TaskPriority[] = ['critical', 'high', 'medium', 'low'];\n for (const p of order) {\n for (const req of byPriority[p]) {\n featureIds.push(this.opts.taskTracker.addNode(this.createTaskFromRequirement(req)).id);\n }\n }\n\n // API tasks\n if (spec.apiEndpoints && spec.apiEndpoints.length > 0) {\n const apiParent = this.opts.taskTracker.addNode({\n title: 'API Implementation',\n description: `Implement ${spec.apiEndpoints.length} API endpoints`,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n });\n featureIds.push(apiParent.id);\n\n for (const endpoint of spec.apiEndpoints) {\n const task = this.createTaskFromEndpoint(endpoint);\n featureIds.push(\n this.opts.taskTracker.addNode({\n ...task,\n parentId: apiParent.id,\n }).id,\n );\n }\n }\n\n // Test tasks — depend on every feature so they run after implementation.\n const testId = this.opts.taskTracker.addNode({\n title: 'Write Tests',\n description: 'Comprehensive test coverage for all features',\n type: 'test',\n priority: 'high',\n status: 'pending',\n }).id;\n for (const f of featureIds) this.opts.taskTracker.addDependency(f, testId);\n\n // Documentation tasks — depend on features + tests (last in the chain).\n const docsId = this.opts.taskTracker.addNode({\n title: 'Update Documentation',\n description: 'Update docs for new features',\n type: 'docs',\n priority: 'medium',\n status: 'pending',\n }).id;\n for (const f of [...featureIds, testId]) this.opts.taskTracker.addDependency(f, docsId);\n\n return graph;\n }\n\n private createTaskFromRequirement(\n req: SpecRequirement,\n ): Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'> {\n const verificationCommand = this.opts.verificationFromAcceptance\n ? extractVerificationCommand(req.acceptanceCriteria)\n : undefined;\n return {\n title: req.description,\n description: this.buildDescription(req),\n type: this.mapRequirementType(req.type),\n priority: req.priority,\n status: 'pending',\n specRequirementId: req.id,\n tags: [req.type, req.priority],\n estimateHours: this.estimateHours(req),\n ...(verificationCommand ? { metadata: { verificationCommand } } : {}),\n };\n }\n\n private createTaskFromEndpoint(\n endpoint: NonNullable<Specification['apiEndpoints']>[number],\n ): Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'> {\n return {\n title: `${endpoint.method} ${endpoint.path}`,\n description: endpoint.description,\n type: 'feature',\n priority: 'high',\n status: 'pending',\n tags: [endpoint.method],\n estimateHours: this.estimateForEndpoint(endpoint),\n };\n }\n\n private buildDescription(req: SpecRequirement): string {\n const lines = [req.description, '', '**Type:** ' + req.type, '**Priority:** ' + req.priority];\n\n if (req.acceptanceCriteria.length > 0) {\n lines.push('', '**Acceptance Criteria:**');\n for (const criterion of req.acceptanceCriteria) {\n lines.push(`- ${criterion}`);\n }\n }\n\n if (req.blockedBy && req.blockedBy.length > 0) {\n lines.push('', `**Blocked by:** ${req.blockedBy.join(', ')}`);\n }\n\n return lines.join('\\n');\n }\n\n private mapRequirementType(type: SpecRequirement['type']): TaskType {\n switch (type) {\n case 'functional':\n return 'feature';\n case 'non-functional':\n return 'feature';\n case 'security':\n return 'feature';\n case 'performance':\n return 'feature';\n case 'ux':\n return 'feature';\n default:\n return 'feature';\n }\n }\n\n private estimateHours(req: SpecRequirement): number {\n switch (req.priority) {\n case 'critical':\n return 8;\n case 'high':\n return 4;\n case 'medium':\n return 2;\n case 'low':\n return 1;\n default:\n return 2;\n }\n }\n\n private estimateForEndpoint(\n endpoint: NonNullable<Specification['apiEndpoints']>[number],\n ): number {\n let hours = 2;\n if (endpoint.auth) hours += 1;\n if (endpoint.request) hours += 1;\n return hours;\n }\n\n async generateSubtasks(parentTaskId: string, spec: Specification): Promise<void> {\n const reqId = this.opts.taskTracker.getNode(parentTaskId)?.specRequirementId;\n if (!reqId) return;\n\n const req = spec.requirements.find((r) => r.id === reqId);\n if (!req) return;\n\n if (req.acceptanceCriteria.length > 0) {\n for (const criterion of req.acceptanceCriteria) {\n this.opts.taskTracker.addNode({\n title: criterion,\n description: `Verify: ${criterion}`,\n type: 'test',\n priority: 'medium',\n status: 'pending',\n parentId: parentTaskId,\n });\n }\n }\n }\n}\n\nexport class DefaultTaskStore implements TaskStore {\n private graphs = new Map<string, TaskGraph>();\n\n async saveGraph(graph: TaskGraph): Promise<void> {\n this.graphs.set(graph.id, this.cloneGraph(graph));\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n const g = this.graphs.get(id);\n return g ? this.cloneGraph(g) : null;\n }\n\n async listGraphs(): Promise<{ id: string; title: string; updatedAt: number }[]> {\n return Array.from(this.graphs.values()).map((g) => ({\n id: g.id,\n title: g.title,\n updatedAt: g.updatedAt,\n }));\n }\n\n async deleteGraph(id: string): Promise<void> {\n this.graphs.delete(id);\n }\n\n private cloneGraph(g: TaskGraph): TaskGraph {\n return {\n ...g,\n nodes: new Map(g.nodes),\n edges: [...g.edges],\n rootNodes: [...g.rootNodes],\n };\n }\n}\n","export type TaskStatus = 'pending' | 'in_progress' | 'blocked' | 'failed' | 'review' | 'completed';\r\nexport type TaskPriority = 'critical' | 'high' | 'medium' | 'low';\r\nexport type TaskType = 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'chore';\r\n\r\nexport interface TaskNode {\r\n id: string;\r\n title: string;\r\n description: string;\r\n type: TaskType;\r\n priority: TaskPriority;\r\n status: TaskStatus;\r\n assignee?: string | undefined;\r\n estimateHours?: number | undefined;\r\n actualHours?: number | undefined;\r\n tags?: string[] | undefined;\r\n specRequirementId?: string | undefined;\r\n parentId?: string | undefined;\r\n children?: string[] | undefined;\r\n createdAt: number;\r\n updatedAt: number;\r\n startedAt?: number | undefined; // set when status → in_progress\r\n completedAt?: number | undefined;\r\n metadata?: Record<string, unknown>;\r\n}\r\n\r\nexport interface TaskEdge {\r\n id: string;\r\n from: string;\r\n to: string;\r\n type: 'blocks' | 'depends_on' | 'relates_to' | 'implements';\r\n weight?: number | undefined;\r\n}\r\n\r\nexport interface TaskGraph {\r\n id: string;\r\n specId: string;\r\n title: string;\r\n nodes: Map<string, TaskNode>;\r\n edges: TaskEdge[];\r\n rootNodes: string[];\r\n createdAt: number;\r\n updatedAt: number;\r\n}\r\n\r\nexport interface TaskDependency {\r\n taskId: string;\r\n blockedBy: string[];\r\n blocking: string[];\r\n}\r\n\r\nexport interface TaskAssignment {\r\n taskId: string;\r\n assignee: string;\r\n assignedAt: number;\r\n}\r\n\r\nexport interface TaskProgress {\r\n total: number;\r\n pending: number;\r\n inProgress: number;\r\n blocked: number;\r\n failed: number;\r\n review: number;\r\n completed: number;\r\n percentComplete: number;\r\n estimatedHours: number;\r\n actualHours: number;\r\n}\r\n\r\nexport interface TaskFilter {\r\n status?: TaskStatus[] | undefined;\r\n priority?: TaskPriority[] | undefined;\r\n type?: TaskType[] | undefined;\r\n assignee?: string[] | undefined;\r\n tags?: string[] | undefined;\r\n specRequirementId?: string | undefined;\r\n}\r\n\r\nexport interface TaskSort {\r\n field: 'priority' | 'createdAt' | 'updatedAt' | 'status';\r\n direction: 'asc' | 'desc';\r\n}\r\n\r\nexport interface CriticalPathResult {\r\n taskIds: string[];\r\n totalEstimateHours: number;\r\n bottleneckTasks: string[];\r\n}\r\n\r\nexport function computeTaskProgress(graph: TaskGraph): TaskProgress {\r\n let completed = 0;\r\n let pending = 0;\r\n let inProgress = 0;\r\n let blocked = 0;\r\n let failed = 0;\r\n let review = 0;\r\n let estimatedHours = 0;\r\n let actualHours = 0;\r\n for (const n of graph.nodes.values()) {\r\n switch (n.status) {\r\n case 'completed':\r\n completed++;\r\n break;\r\n case 'pending':\r\n pending++;\r\n break;\r\n case 'in_progress':\r\n inProgress++;\r\n break;\r\n case 'blocked':\r\n blocked++;\r\n break;\r\n case 'failed':\r\n failed++;\r\n break;\r\n case 'review':\r\n review++;\r\n break;\r\n }\r\n estimatedHours += n.estimateHours ?? 0;\r\n actualHours += n.actualHours ?? 0;\r\n }\r\n const total = graph.nodes.size;\r\n\r\n return {\r\n total,\r\n pending,\r\n inProgress,\r\n blocked,\r\n failed,\r\n review,\r\n completed,\r\n percentComplete: total > 0 ? Math.round((completed / total) * 100) : 0,\r\n estimatedHours,\r\n actualHours,\r\n };\r\n}\r\n\r\nexport function findCriticalPath(graph: TaskGraph): CriticalPathResult {\r\n const nodes = Array.from(graph.nodes.values());\r\n const criticalNodes = nodes.filter((n) => n.priority === 'critical');\r\n const bottleneckTasks = criticalNodes\r\n .filter((n) => graph.edges.some((e) => e.to === n.id && e.type === 'depends_on'))\r\n .map((n) => n.id);\r\n\r\n const totalEstimateHours = criticalNodes.reduce((sum, n) => sum + (n.estimateHours ?? 0), 0);\r\n\r\n return {\r\n taskIds: criticalNodes.map((n) => n.id),\r\n totalEstimateHours,\r\n bottleneckTasks,\r\n };\r\n}\r\n\r\nexport function topologicalSort(graph: TaskGraph): string[] {\r\n const visited = new Set<string>();\r\n const inStack = new Set<string>();\r\n const result: string[] = [];\r\n\r\n function visit(id: string): void {\r\n // Cycle: callers must detect cycles up-front if they care; we just stop recursing.\r\n if (inStack.has(id)) return;\r\n if (visited.has(id)) return;\r\n if (!graph.nodes.has(id)) return;\r\n\r\n visited.add(id);\r\n inStack.add(id);\r\n\r\n for (const edge of graph.edges) {\r\n if (edge.from === id) visit(edge.to);\r\n }\r\n\r\n inStack.delete(id);\r\n result.push(id);\r\n }\r\n\r\n for (const rootId of graph.rootNodes) {\r\n visit(rootId);\r\n }\r\n\r\n return result;\r\n}\r\n","/**\n * Exhaustiveness check for discriminated union switches.\n * Place in the `default` branch of a switch over a union type\n * to get a compile-time error when a new variant is added.\n *\n * @example\n * switch (block.type) {\n * case 'text': return renderText(block);\n * case 'tool_use': return renderToolUse(block);\n * default: return assertNever(block);\n * }\n */\nexport function assertNever(x: never, message?: string): never {\n const err = new Error(\n message ?? `Unhandled case: ${JSON.stringify(x)}`,\n );\n err.name = 'AssertNeverError';\n throw err;\n}\n","/**\n * Build a sanitized child-process environment.\n *\n * The bash/exec tools and MCP stdio transports execute LLM-generated or\n * configured commands. The parent process carries provider API keys\n * (ANTHROPIC_API_KEY, OPENAI_API_KEY, ...), VCS tokens (GITHUB_TOKEN),\n * and cloud credentials. Forwarding those to a child is an exfiltration\n * vector even with `permission: 'confirm'` — a compromised MCP server\n * or a cleverly composed shell pipeline can leak secrets.\n *\n * Strategy: copy a small, explicit allowlist of variables that real builds\n * need, then copy anything else that does NOT look secret-bearing. This\n * preserves user-friendly behavior (locale, terminal, npm config) while\n * blocking the obvious leak channels. Two value-side guards back up the\n * name-based filter:\n * - any value carrying an embedded URI credential (`scheme://user:pass@host`,\n * e.g. `DATABASE_URL`/`REDIS_URL`/`*_DSN`) is dropped (WS-01);\n * - `NODE_OPTIONS` is forwarded but with module-preload directives\n * (`--require`/`--import`/`--loader`) stripped so a parent-set value can't\n * inject code into node children (WS-02).\n *\n * Override with `WRONGSTACK_CHILD_ENV_PASSTHROUGH=1` to forward the full\n * parent environment unchanged (opt-in for advanced users who understand\n * the risk).\n */\n\nconst ALLOWED_KEYS = new Set<string>([\n 'PATH',\n 'HOME',\n 'USER',\n 'USERNAME',\n 'LOGNAME',\n 'SHELL',\n 'LANG',\n 'LC_ALL',\n 'LC_CTYPE',\n 'TERM',\n 'TZ',\n 'TMPDIR',\n 'TEMP',\n 'TMP',\n 'PWD',\n 'OLDPWD',\n 'COMSPEC',\n 'SYSTEMROOT',\n 'SYSTEMDRIVE',\n 'WINDIR',\n 'PROGRAMFILES',\n 'PROGRAMFILES(X86)',\n 'PROGRAMDATA',\n 'APPDATA',\n 'LOCALAPPDATA',\n 'USERPROFILE',\n 'PUBLIC',\n 'PATHEXT',\n]);\n\n// Substring match against env-var names (case-insensitive). Bias toward\n// false-positives — a missing var is recoverable, an exfiltrated key is not.\n// Only consulted for vars NOT on the curated allowlist; PWD/PASSWD-style\n// false positives there are avoided by checking allowlist first.\nconst SECRET_NAME_PARTS = [\n 'TOKEN',\n 'SECRET',\n 'PASSWORD',\n 'PASSWD',\n 'AUTH',\n 'CRED',\n 'BEARER',\n 'COOKIE',\n 'PRIVATE',\n];\n\nfunction looksSecret(name: string): boolean {\n const upper = name.toUpperCase();\n for (const p of SECRET_NAME_PARTS) {\n if (upper.includes(p)) return true;\n }\n // KEY is tricky — PUBLIC_KEY is fine to forward but most _KEY vars are\n // secrets. Require word boundary so KEYBOARD_LAYOUT etc. are not flagged.\n if (/(?:^|_)KEY(?:$|_|S$)/i.test(upper)) return true;\n if (/API[_-]?KEY/i.test(upper)) return true;\n if (/ACCESS[_-]?KEY/i.test(upper)) return true;\n if (/SESSION[_-]?ID/i.test(upper) === false && /SESSION/i.test(upper)) {\n // SESSION_ID is metadata (we set our own); other SESSION_* often holds\n // session cookies. Be conservative.\n return true;\n }\n return false;\n}\n\n/**\n * Value-side secret detection (WS-01). The name-based `looksSecret` filter\n * misses connection-string variables whose NAME is innocuous but whose VALUE\n * embeds a password — e.g. `DATABASE_URL=postgres://user:pass@host`,\n * `REDIS_URL=redis://:pass@host`, `MONGO_URI`, `AMQP_URL`, `*_DSN`. Forwarding\n * these to a child (bash/exec/MCP server) leaks the embedded credential.\n *\n * Matches a URI userinfo component that contains a password, i.e.\n * `scheme://[user]:<password>@host`. Deliberately precise: a credential-free\n * URL (`https://api.example.com`, `https://user@host` with no password) is NOT\n * matched, so non-secret `*_URL` knobs (registries, endpoints) still forward.\n */\nfunction valueHasEmbeddedCredential(value: string): boolean {\n // scheme:// then optional user, a ':' , a non-empty password, then '@'.\n // Userinfo chars stop at '/', whitespace, ':' (separator) and '@'.\n return /\\b[a-z][a-z0-9+.-]*:\\/\\/[^/\\s:@]*:[^/\\s@]+@/i.test(value);\n}\n\n/**\n * Code-injection directives that turn `NODE_OPTIONS` into an RCE channel by\n * preloading an arbitrary module into every node child process (WS-02).\n */\nconst NODE_OPTIONS_INJECTION_FLAG =\n /^(?:--require|-r|--import|--loader|--experimental-loader)$/;\nconst NODE_OPTIONS_INJECTION_FLAG_EQ =\n /^(?:--require|-r|--import|--loader|--experimental-loader)=/;\n\n/**\n * Strip module-preload directives from a `NODE_OPTIONS` value while preserving\n * benign flags (`--no-warnings`, `--max-old-space-size=…`, etc.). Handles both\n * the `--require=./x.js` and space-separated `--require ./x.js` forms. Returns\n * the sanitized string (possibly empty).\n */\nexport function sanitizeNodeOptions(value: string): string {\n const tokens = value.split(/\\s+/).filter(Boolean);\n const kept: string[] = [];\n for (let i = 0; i < tokens.length; i++) {\n const tok = tokens[i] as string;\n if (NODE_OPTIONS_INJECTION_FLAG_EQ.test(tok)) continue; // --require=./x\n if (NODE_OPTIONS_INJECTION_FLAG.test(tok)) {\n i++; // also drop the following path token (--require ./x)\n continue;\n }\n kept.push(tok);\n }\n return kept.join(' ');\n}\n\nexport interface BuildChildEnvOptions {\n /** Session ID to inject as WRONGSTACK_SESSION_ID. */\n sessionId?: string | undefined;\n /** Additional env vars to merge (takes priority over filtered parent env). */\n extra?: NodeJS.ProcessEnv | undefined;\n}\n\n/**\n * Build a filtered child-process environment suitable for bash, exec, and\n * MCP server subprocesses. Strips API keys, tokens, and other credentials\n * while preserving system/tooling variables.\n */\nexport function buildChildEnv(optsOrSessionId?: BuildChildEnvOptions | string): NodeJS.ProcessEnv {\n const opts: BuildChildEnvOptions =\n typeof optsOrSessionId === 'string'\n ? { sessionId: optsOrSessionId }\n : (optsOrSessionId ?? {});\n\n // WRONGSTACK_CHILD_ENV_PASSTHROUGH may NOT be set via config file.\n // It is a privileged override that opt-outs the entire credential filter\n // and must only be set by the operator's shell environment (real env var,\n // not something a config file injects into process.env). Config-file\n // sources do NOT go through process.env — only the actual shell environment\n // does — so checking Object.prototype.hasOwnProperty.call(process.env, ...)\n // is sufficient to exclude config-driven values.\n const hasOwn = Object.hasOwn(process.env, 'WRONGSTACK_CHILD_ENV_PASSTHROUGH');\n const legacyHasOwn = Object.hasOwn(process.env, 'WRONGSTACK_BASH_ENV_PASSTHROUGH');\n const passthrough = (hasOwn && process.env['WRONGSTACK_CHILD_ENV_PASSTHROUGH'] === '1')\n || (legacyHasOwn && process.env['WRONGSTACK_BASH_ENV_PASSTHROUGH'] === '1');\n if (passthrough && !process.env['CI']) {\n console.warn(\n '[agent] WARNING: WRONGSTACK_*_ENV_PASSTHROUGH=1 is active —\\n' +\n ' all parent env vars (including API keys) forwarded to child processes.\\n' +\n ' Do not use on shared or multi-tenant systems.'\n );\n }\n const out: NodeJS.ProcessEnv = {};\n\n // The CLI entry defaults NODE_ENV=production (so React/Ink resolve their\n // production builds — see cli-main) and marks the injection with this\n // flag. The injected value must NOT reach children: NODE_ENV=production\n // makes `pnpm install` skip devDependencies and flips test-runner\n // behavior. Strip both vars whenever the flag says wrongstack set them —\n // a NODE_ENV genuinely exported by the operator's shell (flag absent)\n // is forwarded unchanged. Applies in passthrough mode too: passthrough\n // means \"the operator's real environment\", which this value is not.\n const nodeEnvDefaulted = process.env['WRONGSTACK_NODE_ENV_DEFAULTED'] === '1';\n\n for (const [k, v] of Object.entries(process.env)) {\n if (v === undefined) continue;\n if (nodeEnvDefaulted && (k === 'NODE_ENV' || k === 'WRONGSTACK_NODE_ENV_DEFAULTED')) continue;\n if (passthrough) {\n out[k] = v;\n continue;\n }\n const upper = k.toUpperCase();\n // 0. Strip any value with an embedded URI credential (user:pass@host),\n // regardless of the variable name (WS-01). Applied before the allowlist\n // so even a \"system\" name carrying a connection string is caught.\n if (valueHasEmbeddedCredential(v)) continue;\n // 1. Forward names on the explicit allowlist — these are well-known\n // non-secret system variables (PATH, HOME, LANG, ...).\n if (ALLOWED_KEYS.has(upper)) {\n out[k] = v;\n continue;\n }\n // 2. Strip anything that looks like a secret.\n if (looksSecret(upper)) continue;\n // NODE_OPTIONS is forwarded (builds rely on flags like --no-warnings) but\n // module-preload directives (--require/--import/--loader) are stripped —\n // they would let a parent-set NODE_OPTIONS inject code into every node\n // child (WS-02 defense-in-depth).\n if (upper === 'NODE_OPTIONS') {\n const sanitized = sanitizeNodeOptions(v);\n if (sanitized) out[k] = sanitized;\n continue;\n }\n // 3. Forward tooling-prefixed vars that builds commonly need, unless\n // they already failed the secret check above.\n if (\n upper.startsWith('NODE_') ||\n upper.startsWith('NPM_') ||\n upper.startsWith('PNPM_') ||\n upper.startsWith('YARN_') ||\n upper.startsWith('GIT_') ||\n upper.startsWith('CI') ||\n upper.startsWith('XDG_') ||\n // Our own non-secret knobs (WRONGSTACK_HOME, WRONGSTACK_SESSION_ID, …).\n // Secrets never live in WRONGSTACK_* env vars (they're in the encrypted\n // vault). Forwarding keeps child wstack processes — e.g. ones spawned\n // by the test suite — inside the same redirected global root.\n upper.startsWith('WRONGSTACK_') ||\n upper === 'EDITOR' ||\n upper === 'VISUAL' ||\n upper === 'PAGER'\n ) {\n out[k] = v;\n }\n }\n\n // Merge explicit extras AFTER filtering. Callers MUST treat `opts.extra`\n // as a small, user-authored allowlist (e.g. MCP server tokens, LSP env\n // overrides from config). Do NOT pass `process.env` or any object derived\n // from it — that would defeat the parent-env scrub above. The secret\n // filter is intentionally skipped here so legitimate secret-bearing\n // tokens the user explicitly configured can still reach the child.\n if (opts.extra) {\n Object.assign(out, opts.extra);\n }\n\n if (opts.sessionId) out['WRONGSTACK_SESSION_ID'] = opts.sessionId;\n return out;\n}\n","/**\n * Converts an unknown error value to a human-readable string.\n * Used in 40+ files across the codebase to normalize error messaging.\n */\nexport function toErrorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/** Assert a value is neither null nor undefined. Throws if it is.\n * Useful after optional chaining and indexed access when the\n * control flow guarantees the value exists but TypeScript can't\n * prove it (e.g. after a check on a related field). */\nexport function expectDefined<T>(value: T | null | undefined, label?: string): T {\n if (value === null || value === undefined) {\n const err = new Error(label ? `Expected ${label} to be defined` : 'Expected value to be defined');\n err.name = 'ExpectDefinedError';\n throw err;\n }\n return value;\n}\n","/**\n * String utilities shared across the WrongStack codebase.\n */\n\n/**\n * Truncate a string to at most `max` characters, appending an ellipsis if it\n * was longer. Returns the original string unchanged when it fits.\n */\nexport function truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors — spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n","import type {\n TaskFilter,\n TaskGraph,\n TaskNode,\n TaskProgress,\n TaskSort,\n} from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { toErrorMessage } from '../utils/error.js';\n\nexport interface TaskStore {\n saveGraph(graph: TaskGraph): Promise<void>;\n loadGraph(id: string): Promise<TaskGraph | null>;\n listGraphs(): Promise<{ id: string; title: string; updatedAt: number }[]>;\n deleteGraph(id: string): Promise<void>;\n}\n\nexport interface TaskTrackerOptions {\n store: TaskStore;\n /**\n * Called when an in-the-background persistence (`saveGraph`) rejects.\n * The synchronous TaskTracker methods (addNode/addEdge/updateNodeStatus)\n * fire-and-forget their writes; without this, a failing store silently\n * loses graph mutations. Defaults to a console.warn.\n */\n onPersistError?: (((err: unknown) => void)) | undefined;\n}\n\nexport interface TaskTransition {\n from: TaskNode['status'];\n to: TaskNode['status'];\n timestamp: number;\n reason?: string | undefined;\n}\n\n/** A change notification emitted to `TaskTracker.subscribe` listeners. */\nexport interface TaskTrackerChange {\n type: 'node_added' | 'node_updated' | 'status_changed' | 'node_removed';\n nodeId: string;\n /** For `node_removed` this is the node as it was just before deletion. */\n node: TaskNode;\n transition?: TaskTransition | undefined;\n}\n\nexport type TaskTrackerListener = (change: TaskTrackerChange) => void;\n\nexport class TaskTracker {\n private graph: TaskGraph | null = null;\n private transitions: TaskTransition[] = [];\n private listeners: TaskTrackerListener[] = [];\n\n constructor(private readonly opts: TaskTrackerOptions) {}\n\n /**\n * Subscribe to live task mutations (add / update / status change). Returns an\n * unsubscribe fn. This is the hook the board projector uses to stream a live\n * snapshot — the tracker was previously fire-and-forget with no observability.\n */\n subscribe(listener: TaskTrackerListener): () => void {\n this.listeners.push(listener);\n return () => {\n const i = this.listeners.indexOf(listener);\n if (i >= 0) this.listeners.splice(i, 1);\n };\n }\n\n private notifyChange(change: TaskTrackerChange): void {\n for (const l of this.listeners) {\n try {\n l(change);\n } catch {\n // A faulty listener must never break a tracker mutation.\n }\n }\n }\n\n /**\n * Attach an existing graph (used by PhaseOrchestrator to associate a tracker\n * with a phase's pre-built task graph without re-creating it).\n */\n setGraph(graph: TaskGraph): void {\n this.graph = graph;\n }\n\n async createGraph(specId: string, title: string): Promise<TaskGraph> {\n this.graph = {\n id: crypto.randomUUID(),\n specId,\n title,\n nodes: new Map(),\n edges: [],\n rootNodes: [],\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n await this.opts.store.saveGraph(this.graph);\n return this.graph;\n }\n\n async loadGraph(id: string): Promise<TaskGraph | null> {\n this.graph = await this.opts.store.loadGraph(id);\n return this.graph;\n }\n\n addNode(node: Omit<TaskNode, 'id' | 'createdAt' | 'updatedAt'>): TaskNode {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const now = Date.now();\n const newNode: TaskNode = {\n ...node,\n id: crypto.randomUUID(),\n status: node.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n\n this.graph.nodes.set(newNode.id, newNode);\n\n if (!node.parentId) {\n this.graph.rootNodes.push(newNode.id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n this.notifyChange({ type: 'node_added', nodeId: newNode.id, node: newNode });\n\n return newNode;\n }\n\n addEdge(from: string, to: string, type: TaskGraph['edges'][0]['type'] = 'depends_on'): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n this.graph.edges.push({\n id: crypto.randomUUID(),\n from,\n to,\n type,\n });\n this.graph.updatedAt = Date.now();\n this.persist();\n }\n\n /**\n * Declare that `taskId` depends on `depId` (a `depends_on` edge `depId → taskId`),\n * guarding against self-loops, duplicates, missing nodes, and cycles. Returns\n * true if the dependency now holds (added or already present), false if it was\n * rejected (would create a cycle / unknown node). This is the safe entry point\n * for wiring agent-declared `dependsOn` references into the graph.\n */\n addDependency(depId: string, taskId: string): boolean {\n if (!this.graph) return false;\n if (depId === taskId) return false;\n if (!this.graph.nodes.has(depId) || !this.graph.nodes.has(taskId)) return false;\n // Already a blocker — idempotent success.\n if (this.getBlockers(taskId).includes(depId)) return true;\n // Cycle guard: if `depId` already (transitively) depends on `taskId`, adding\n // `taskId → depId` would close a loop. Reject rather than deadlock the run.\n if (this.dependsOnTransitively(depId, taskId, new Set())) return false;\n this.addEdge(depId, taskId, 'depends_on');\n return true;\n }\n\n /** True when `taskId` transitively depends on `targetId` (follows depends_on blockers). */\n private dependsOnTransitively(taskId: string, targetId: string, seen: Set<string>): boolean {\n if (taskId === targetId) return true;\n if (seen.has(taskId)) return false;\n seen.add(taskId);\n for (const blocker of this.getBlockers(taskId)) {\n if (this.dependsOnTransitively(blocker, targetId, seen)) return true;\n }\n return false;\n }\n\n /**\n * Merge `patch` into a node's `metadata` (used for per-task model/provider/\n * fallback assignment and the cancel marker). Persists + notifies as a node\n * update. No-op if the node is missing.\n */\n patchMetadata(id: string, patch: Record<string, unknown>): void {\n if (!this.graph) return;\n const node = this.graph.nodes.get(id);\n if (!node) return;\n node.metadata = { ...node.metadata, ...patch };\n node.updatedAt = Date.now();\n this.graph.updatedAt = node.updatedAt;\n this.persist();\n this.notifyChange({ type: 'node_updated', nodeId: id, node });\n }\n\n /**\n * Remove a node and every edge touching it. Intended for deleting a task that\n * has not started yet — callers must gate on status (do not remove a running\n * task). Dependents simply lose this blocker (re-evaluated by `canStart`).\n * Returns true if a node was removed.\n */\n removeNode(id: string): boolean {\n if (!this.graph) return false;\n const node = this.graph.nodes.get(id);\n if (!node) return false;\n this.graph.nodes.delete(id);\n this.graph.edges = this.graph.edges.filter((e) => e.from !== id && e.to !== id);\n this.graph.rootNodes = this.graph.rootNodes.filter((r) => r !== id);\n // Detach from any parent's children list.\n for (const n of this.graph.nodes.values()) {\n if (n.children?.includes(id)) n.children = n.children.filter((c) => c !== id);\n }\n this.graph.updatedAt = Date.now();\n this.persist();\n this.notifyChange({ type: 'node_removed', nodeId: id, node });\n return true;\n }\n\n updateNodeStatus(id: string, status: TaskNode['status'], reason?: string): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node) throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n const from = node.status;\n const now = Date.now();\n node.status = status;\n node.updatedAt = now;\n\n if (status === 'completed') {\n node.completedAt = now;\n node.startedAt = node.startedAt ?? now; // ensure startedAt is set\n }\n if (status === 'in_progress') {\n node.startedAt = now;\n }\n\n this.transitions.push({ from, to: status, timestamp: now, reason });\n\n // Auto-unblock dependents\n if (status === 'completed') {\n this.unblockDependents(id);\n }\n\n // Auto-block blockers\n if (status === 'in_progress') {\n this.checkAndBlockIfNeeded(id);\n }\n\n this.graph.updatedAt = now;\n this.persist();\n this.notifyChange({\n type: 'status_changed',\n nodeId: id,\n node,\n transition: { from, to: status, timestamp: now, reason },\n });\n }\n\n updateNode(id: string, patch: Partial<Pick<TaskNode, 'title' | 'description' | 'priority' | 'estimateHours' | 'tags' | 'assignee'>>): void {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n\n const node = this.graph.nodes.get(id);\n if (!node) throw new SddError({\n message: `Node ${id} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { nodeId: id },\n });\n\n if (patch.title !== undefined) node.title = patch.title;\n if (patch.description !== undefined) node.description = patch.description;\n if (patch.priority !== undefined) node.priority = patch.priority;\n if (patch.estimateHours !== undefined) node.estimateHours = patch.estimateHours;\n if (patch.tags !== undefined) node.tags = patch.tags;\n if (patch.assignee !== undefined) node.assignee = patch.assignee;\n node.updatedAt = Date.now();\n this.graph.updatedAt = node.updatedAt;\n this.persist();\n this.notifyChange({ type: 'node_updated', nodeId: id, node });\n }\n\n getNode(id: string): TaskNode | undefined {\n return this.graph?.nodes.get(id);\n }\n\n getAllNodes(filter?: TaskFilter, sort?: TaskSort): TaskNode[] {\n if (!this.graph) return [];\n\n let nodes = Array.from(this.graph.nodes.values());\n\n if (filter) {\n nodes = nodes.filter((n) => {\n if (filter.status?.length && !filter.status.includes(n.status)) return false;\n if (filter.priority?.length && !filter.priority.includes(n.priority)) return false;\n if (filter.type?.length && !filter.type.includes(n.type)) return false;\n if (filter.assignee?.length && n.assignee && !filter.assignee.includes(n.assignee))\n return false;\n if (filter.tags?.length && n.tags && !n.tags.some((t) => filter.tags?.includes(t)))\n return false;\n if (filter.specRequirementId && n.specRequirementId !== filter.specRequirementId)\n return false;\n return true;\n });\n }\n\n if (sort) {\n nodes.sort((a, b) => {\n const cmp = compareByField(a, b, sort.field);\n return sort.direction === 'asc' ? cmp : -cmp;\n });\n }\n\n return nodes;\n }\n\n getChildren(parentId: string): TaskNode[] {\n if (!this.graph) return [];\n return Array.from(this.graph.nodes.values()).filter((n) => n.parentId === parentId);\n }\n\n getDependents(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.from === taskId && e.type === 'depends_on')\n .map((e) => e.to);\n }\n\n getBlockers(taskId: string): string[] {\n if (!this.graph) return [];\n return this.graph.edges\n .filter((e) => e.to === taskId && e.type === 'depends_on')\n .map((e) => e.from);\n }\n\n canStart(taskId: string): boolean {\n const blockers = this.getBlockers(taskId);\n return blockers.every((id) => {\n const node = this.graph?.nodes.get(id);\n // A task can start when all blockers are either completed or failed.\n // Failed blockers should not permanently deadlock dependent tasks.\n return node?.status === 'completed' || node?.status === 'failed';\n });\n }\n\n getProgress(): TaskProgress {\n if (!this.graph) {\n return {\n total: 0,\n pending: 0,\n inProgress: 0,\n blocked: 0,\n failed: 0,\n review: 0,\n completed: 0,\n percentComplete: 0,\n estimatedHours: 0,\n actualHours: 0,\n };\n }\n return computeTaskProgress(this.graph);\n }\n\n getTransitions(_taskId?: string): TaskTransition[] {\n return [...this.transitions];\n }\n\n private unblockDependents(completedId: string): void {\n if (!this.graph) return;\n const dependents = this.getDependents(completedId);\n for (const depId of dependents) {\n const dep = this.graph.nodes.get(depId);\n if (dep?.status === 'blocked') {\n // Check if all blockers are now completed\n const remainingBlockers = this.getBlockers(depId);\n const allUnblocked = remainingBlockers.every((id) => {\n const blocker = this.graph?.nodes.get(id);\n return blocker?.status === 'completed' || blocker?.status === 'failed';\n });\n if (allUnblocked) {\n dep.status = 'pending';\n dep.updatedAt = Date.now();\n }\n }\n }\n }\n\n private checkAndBlockIfNeeded(taskId: string): void {\n if (!this.graph) return;\n const blockers = this.getBlockers(taskId);\n const someBlocked = blockers.some((id) => {\n const blocker = this.graph?.nodes.get(id);\n // A task is only blocked by incomplete blockers that haven't failed.\n // Failed tasks should not block their dependents.\n return blocker?.status !== 'completed' && blocker?.status !== 'failed';\n });\n if (someBlocked) {\n const node = this.graph.nodes.get(taskId);\n if (node) {\n node.status = 'blocked';\n node.updatedAt = Date.now();\n }\n }\n }\n\n /**\n * Fire-and-forget persistence with attached error handler.\n * Synchronous mutators (addNode/addEdge/updateNodeStatus) use this to\n * avoid forcing an async cascade through every caller; if the store\n * is missing or throwing, the error is surfaced via onPersistError.\n */\n private persist(): void {\n if (!this.graph) return;\n this.opts.store.saveGraph(this.graph).catch((err) => {\n this.opts.onPersistError\n ? this.opts.onPersistError(err)\n : console.warn(JSON.stringify({\n level: 'warn',\n event: 'task_tracker.save_graph_failed',\n message: toErrorMessage(err),\n timestamp: new Date().toISOString(),\n }));\n });\n }\n}\n\n// Sort comparison helpers\nconst PRIORITY_RANK: Record<TaskNode['priority'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n};\nconst STATUS_RANK: Record<TaskNode['status'], number> = {\n in_progress: 0,\n pending: 1,\n review: 2,\n blocked: 3,\n failed: 4,\n completed: 5,\n};\n\nfunction compareByField(a: TaskNode, b: TaskNode, field: TaskSort['field']): number {\n switch (field) {\n case 'priority': return PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority];\n case 'status': return STATUS_RANK[a.status] - STATUS_RANK[b.status];\n case 'createdAt': return a.createdAt - b.createdAt;\n case 'updatedAt': return a.updatedAt - b.updatedAt;\n }\n}\n","import type { EventBus } from '../kernel/events.js';\nimport type { DoneCondition } from '../types/multi-agent.js';\nimport type { SpecAnalysis, Specification } from '../types/spec.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { SpecParser } from './spec-parser.js';\nimport { DefaultTaskStore, TaskGenerator } from './task-generator.js';\nimport { TaskTracker } from './task-tracker.js';\n\n/**\n * Extended event map used internally by TaskFlow and multi-agent components.\n * These events are emitted on the injected EventBus and are a subset of\n * the full EventMap — they do not require a separate registration.\n */\nexport interface TaskFlowEventMap {\n 'phase.change': { from: TaskFlowPhase; to: TaskFlowPhase };\n 'task.started': { taskId: string };\n 'task.completed': { taskId: string; result?: unknown | undefined };\n 'task.failed': { taskId: string; error: string };\n 'task.review': { taskId: string };\n 'spec.analyzed': { analysis: SpecAnalysis };\n progress: { percent: number; message: string };\n done: { graph: TaskGraph };\n error: { phase: TaskFlowPhase; error: Error };\n}\n\nexport type TaskFlowPhase =\n | 'idle'\n | 'parsing'\n | 'analyzing'\n | 'generating'\n | 'executing'\n | 'reviewing'\n | 'completing'\n | 'done'\n | 'failed';\n\nexport type TaskFlowEventName = keyof TaskFlowEventMap;\n\nexport interface TaskFlowOptions {\n tracker: TaskTracker;\n events: EventBus;\n doneCondition?: DoneCondition | undefined;\n maxConcurrent?: number | undefined;\n}\n\nexport interface TaskFlowExecutionContext {\n executeTask: (task: TaskNode) => Promise<unknown>;\n onTaskComplete?: (task: TaskNode | undefined, result: unknown) => void;\n onTaskFail?: (task: TaskNode | undefined, error: Error) => void;\n}\n\nexport class TaskFlow {\n private phase: TaskFlowPhase = 'idle';\n private spec: Specification | null = null;\n private graph: TaskGraph | null = null;\n private stopped = false;\n\n constructor(private readonly opts: TaskFlowOptions) {\n this.setPhase('idle');\n }\n\n private emit<K extends TaskFlowEventName>(event: K, payload: TaskFlowEventMap[K]): void {\n (this.opts.events.emit as (event: string, payload: unknown) => void)(event, payload);\n }\n\n async fromSpec(specContent: string): Promise<TaskGraph> {\n this.setPhase('parsing');\n\n const parser = new SpecParser();\n this.spec = parser.parse(specContent);\n\n this.setPhase('analyzing');\n const analysis = parser.analyze(this.spec);\n this.emit('spec.analyzed', { analysis });\n\n if (analysis.completeness < 50) {\n const err = new SddError({\n message: `Spec completeness too low: ${analysis.completeness}%`,\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\n context: { completeness: analysis.completeness },\n });\n this.emit('error', { phase: 'analyzing', error: err });\n this.setPhase('failed');\n throw err;\n }\n\n this.setPhase('generating');\n const generator = new TaskGenerator({\n taskTracker: this.opts.tracker,\n verificationFromAcceptance: process.env['WRONGSTACK_SDD_VERIFY_FROM_ACCEPTANCE'] === '1',\n });\n this.graph = await generator.generateFromSpec(this.spec);\n\n return this.graph;\n }\n\n async execute(ctx: TaskFlowExecutionContext): Promise<TaskGraph> {\n if (!this.graph) throw new SddError({\n message: 'No graph loaded. Call fromSpec first.',\n code: ERROR_CODES.SDD_INVALID_STATE,\n context: { phase: this.phase },\n });\n\n this.setPhase('executing');\n this.stopped = false;\n\n const pendingTasks = this.getExecutableTasks();\n const maxConcurrent = this.opts.maxConcurrent ?? 2;\n\n while (pendingTasks.length > 0 && !this.stopped) {\n const batch = pendingTasks.splice(0, maxConcurrent);\n const results = await Promise.allSettled(\n batch.map((task) => this.executeSingleTask(task, ctx)),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const task = batch[i];\n\n if (!result || !task) continue;\n\n if (result.status === 'rejected') {\n const reason = result.reason as Error | undefined;\n this.opts.tracker.updateNodeStatus(task.id, 'failed', reason?.message);\n this.emit('task.failed', { taskId: task.id, error: reason?.message ?? 'unknown' });\n ctx.onTaskFail?.(task, reason as Error);\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'completed');\n this.emit('task.completed', { taskId: task.id, result: result.value });\n ctx.onTaskComplete?.(task, result.value);\n }\n\n this.emitProgress();\n }\n\n // Re-evaluate pending tasks (some may have become unblocked)\n const stillPending = this.getExecutableTasks();\n pendingTasks.length = 0;\n pendingTasks.push(...stillPending);\n\n // Check done condition\n if (this.checkDoneCondition()) {\n break;\n }\n }\n\n this.setPhase('completing');\n this.emit('done', { graph: this.graph });\n this.setPhase('done');\n\n return this.graph;\n }\n\n async reviewTask(taskId: string, approved: boolean, comment?: string): Promise<void> {\n const task = this.opts.tracker.getNode(taskId);\n if (!task) throw new SddError({\n message: `Task ${taskId} not found`,\n code: ERROR_CODES.SDD_NOT_READY,\n context: { taskId },\n });\n\n if (approved) {\n this.opts.tracker.updateNodeStatus(taskId, 'completed', comment);\n this.emit('task.completed', { taskId });\n } else {\n this.opts.tracker.updateNodeStatus(taskId, 'in_progress', comment ?? 'Needs revision');\n this.emit('task.review', { taskId });\n }\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n getPhase(): TaskFlowPhase {\n return this.phase;\n }\n\n getGraph(): TaskGraph | null {\n return this.graph;\n }\n\n getSpec(): Specification | null {\n return this.spec;\n }\n\n private setPhase(phase: TaskFlowPhase): void {\n const from = this.phase;\n this.phase = phase;\n this.emit('phase.change', { from, to: phase });\n }\n\n private getExecutableTasks(): TaskNode[] {\n return this.opts.tracker\n .getAllNodes({ status: ['pending', 'blocked'] })\n .filter((n) => n.status === 'pending' && this.opts.tracker.canStart(n.id))\n .sort((a, b) => {\n const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n return (priorityOrder[a.priority] ?? 4) - (priorityOrder[b.priority] ?? 4);\n });\n }\n\n private async executeSingleTask(task: TaskNode, ctx: TaskFlowExecutionContext): Promise<unknown> {\n this.opts.tracker.updateNodeStatus(task.id, 'in_progress');\n this.emit('task.started', { taskId: task.id });\n return ctx.executeTask(task);\n }\n\n private checkDoneCondition(): boolean {\n const condition = this.opts.doneCondition;\n if (!condition) {\n const progress = this.opts.tracker.getProgress();\n return progress.percentComplete === 100;\n }\n\n switch (condition.type) {\n case 'all_tasks_done': {\n const progress = this.opts.tracker.getProgress();\n return progress.pending === 0 && progress.inProgress === 0;\n }\n case 'iterations':\n return false; // Not tracked here\n case 'tool_calls':\n return false;\n default:\n return false;\n }\n }\n\n private emitProgress(): void {\n const progress = this.opts.tracker.getProgress();\n this.emit('progress', {\n percent: progress.percentComplete,\n message: `${progress.completed}/${progress.total} tasks completed`,\n });\n }\n}\n\nexport interface SpecDrivenDevOptions {\n workingDirectory: string;\n events: EventBus;\n doneCondition?: DoneCondition | undefined;\n}\n\nexport class SpecDrivenDev {\n private store: DefaultTaskStore;\n private tracker: TaskTracker;\n private readonly events: EventBus;\n private flows = new Map<string, TaskFlow>();\n\n constructor(opts: SpecDrivenDevOptions) {\n this.store = new DefaultTaskStore();\n this.tracker = new TaskTracker({ store: this.store });\n this.events = opts.events;\n }\n\n async createFlow(specContent: string, options?: Partial<TaskFlowOptions>): Promise<TaskFlow> {\n const flow = new TaskFlow({\n tracker: this.tracker,\n events: this.events,\n ...options,\n });\n\n const graph = await flow.fromSpec(specContent);\n this.flows.set(graph.id, flow);\n\n return flow;\n }\n\n getTracker(): TaskTracker {\n return this.tracker;\n }\n\n getFlow(graphId: string): TaskFlow | undefined {\n return this.flows.get(graphId);\n }\n\n listFlows(): { id: string; title: string; phase: TaskFlowPhase }[] {\n return Array.from(this.flows.entries()).map(([id, flow]) => ({\n id,\n title: flow.getGraph()?.title ?? 'Untitled',\n phase: flow.getPhase(),\n }));\n }\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { randomUUID } from 'node:crypto';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport type { Specification, SpecStatus } from '../types/spec.js';\n\nexport interface SpecStoreOptions {\n /** Directory where spec files are stored. Defaults to `.wrongstack/specs`. */\n baseDir: string;\n}\n\nexport interface SpecIndexEntry {\n id: string;\n title: string;\n version: string;\n status: SpecStatus;\n updatedAt: number;\n filePath: string;\n}\n\ninterface SpecIndex {\n version: 1;\n entries: SpecIndexEntry[];\n}\n\n/**\n * File-backed spec storage. Each spec is a JSON file under `baseDir/`.\n * An index file (`_index.json`) tracks all specs for fast listing.\n */\nexport class SpecStore {\n private readonly baseDir: string;\n private readonly indexPath: string;\n\n constructor(opts: SpecStoreOptions) {\n this.baseDir = opts.baseDir;\n this.indexPath = path.join(this.baseDir, '_index.json');\n }\n\n async save(spec: Specification): Promise<void> {\n await ensureDir(this.baseDir);\n const filePath = this.filePath(spec.id);\n await atomicWrite(filePath, JSON.stringify(spec, null, 2), { mode: 0o600 });\n await this.updateIndex(spec);\n }\n\n async load(id: string): Promise<Specification | null> {\n try {\n const raw = await fsp.readFile(this.filePath(id), 'utf8');\n return JSON.parse(raw) as Specification;\n } catch {\n return null;\n }\n }\n\n async list(): Promise<SpecIndexEntry[]> {\n const index = await this.readIndex();\n return index.entries.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n\n async delete(id: string): Promise<boolean> {\n try {\n await fsp.unlink(this.filePath(id));\n await this.removeFromIndex(id);\n return true;\n } catch {\n return false;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n try {\n await fsp.access(this.filePath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n /** Create a new spec with defaults, assign ID, and persist. */\n async createDraft(title: string, overview?: string): Promise<Specification> {\n const now = Date.now();\n const spec: Specification = {\n id: randomUUID(),\n title,\n version: '0.1.0',\n status: 'draft',\n overview: overview ?? '',\n sections: [],\n requirements: [],\n createdAt: now,\n updatedAt: now,\n };\n await this.save(spec);\n return spec;\n }\n\n /** Update spec fields and persist. */\n async update(id: string, patch: Partial<Omit<Specification, 'id' | 'createdAt'>>): Promise<Specification | null> {\n const spec = await this.load(id);\n if (!spec) return null;\n const updated: Specification = {\n ...spec,\n ...patch,\n id: spec.id,\n createdAt: spec.createdAt,\n updatedAt: Date.now(),\n };\n await this.save(updated);\n return updated;\n }\n\n private filePath(id: string): string {\n return path.join(this.baseDir, `${id}.json`);\n }\n\n private async readIndex(): Promise<SpecIndex> {\n try {\n const raw = await fsp.readFile(this.indexPath, 'utf8');\n const parsed = JSON.parse(raw) as SpecIndex;\n if (parsed?.version === 1) return parsed;\n } catch {\n /* no index yet */\n }\n return { version: 1, entries: [] };\n }\n\n private async updateIndex(spec: Specification): Promise<void> {\n const index = await this.readIndex();\n const entry: SpecIndexEntry = {\n id: spec.id,\n title: spec.title,\n version: spec.version,\n status: spec.status,\n updatedAt: spec.updatedAt,\n filePath: this.filePath(spec.id),\n };\n const idx = index.entries.findIndex((e) => e.id === spec.id);\n if (idx >= 0) {\n index.entries[idx] = entry;\n } else {\n index.entries.push(entry);\n }\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n\n private async removeFromIndex(id: string): Promise<void> {\n const index = await this.readIndex();\n index.entries = index.entries.filter((e) => e.id !== id);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\n\nexport interface TaskGraphStoreOptions {\n /** Directory where task graph files are stored. Defaults to `.wrongstack/task-graphs`. */\n baseDir: string;\n}\n\nexport interface TaskGraphIndexEntry {\n id: string;\n specId: string;\n title: string;\n nodeCount: number;\n completedCount: number;\n updatedAt: number;\n filePath: string;\n}\n\ninterface TaskGraphIndex {\n version: 1;\n entries: TaskGraphIndexEntry[];\n}\n\n/**\n * JSON serialisation helpers for TaskGraph (Map → Array round-trip).\n */\nfunction graphToJSON(graph: TaskGraph): string {\n const serialisable = {\n ...graph,\n nodes: Array.from(graph.nodes.entries()),\n };\n return JSON.stringify(serialisable, null, 2);\n}\n\nfunction graphFromJSON(raw: string): TaskGraph {\n const parsed = JSON.parse(raw) as Omit<TaskGraph, 'nodes'> & { nodes: [string, TaskNode][] };\n return {\n ...parsed,\n nodes: new Map(parsed.nodes),\n };\n}\n\n/**\n * File-backed task graph storage. Each graph is a JSON file under `baseDir/`.\n * An index file (`_index.json`) tracks all graphs for fast listing.\n */\nexport class TaskGraphStore {\n private readonly baseDir: string;\n private readonly indexPath: string;\n\n constructor(opts: TaskGraphStoreOptions) {\n this.baseDir = opts.baseDir;\n this.indexPath = path.join(this.baseDir, '_index.json');\n }\n\n async save(graph: TaskGraph): Promise<void> {\n await ensureDir(this.baseDir);\n const filePath = this.filePath(graph.id);\n await atomicWrite(filePath, graphToJSON(graph), { mode: 0o600 });\n await this.updateIndex(graph);\n }\n\n async load(id: string): Promise<TaskGraph | null> {\n try {\n const raw = await fsp.readFile(this.filePath(id), 'utf8');\n return graphFromJSON(raw);\n } catch {\n return null;\n }\n }\n\n async list(): Promise<TaskGraphIndexEntry[]> {\n const index = await this.readIndex();\n return index.entries.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n\n async delete(id: string): Promise<boolean> {\n try {\n await fsp.unlink(this.filePath(id));\n await this.removeFromIndex(id);\n return true;\n } catch {\n return false;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n try {\n await fsp.access(this.filePath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n private filePath(id: string): string {\n return path.join(this.baseDir, `${id}.json`);\n }\n\n private async readIndex(): Promise<TaskGraphIndex> {\n try {\n const raw = await fsp.readFile(this.indexPath, 'utf8');\n const parsed = JSON.parse(raw) as TaskGraphIndex;\n if (parsed?.version === 1) return parsed;\n } catch {\n /* no index yet */\n }\n return { version: 1, entries: [] };\n }\n\n private async updateIndex(graph: TaskGraph): Promise<void> {\n const index = await this.readIndex();\n const completedCount = Array.from(graph.nodes.values()).filter(\n (n) => n.status === 'completed',\n ).length;\n const entry: TaskGraphIndexEntry = {\n id: graph.id,\n specId: graph.specId,\n title: graph.title,\n nodeCount: graph.nodes.size,\n completedCount,\n updatedAt: graph.updatedAt,\n filePath: this.filePath(graph.id),\n };\n const idx = index.entries.findIndex((e) => e.id === graph.id);\n if (idx >= 0) {\n index.entries[idx] = entry;\n } else {\n index.entries.push(entry);\n }\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n\n private async removeFromIndex(id: string): Promise<void> {\n const index = await this.readIndex();\n index.entries = index.entries.filter((e) => e.id !== id);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n}\n","/**\n * SDD live board model.\n *\n * A board snapshot is the canonical, surface-agnostic projection of a running\n * (or persisted) SDD TaskGraph: tasks laid into topological dependency columns,\n * each carrying its short id, status, blockers and the agent currently on it.\n * The projector (sdd-board-projector.ts) emits these over the EventBus and\n * persists them (sdd-board-store.ts); every surface (WebUI/TUI) renders the\n * same shape.\n */\n\nimport type { TaskGraph, TaskNode, TaskProgress } from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\n\nexport type SddBoardStatus =\n | 'idle'\n | 'running'\n | 'paused'\n | 'completed'\n | 'failed'\n | 'deadlocked';\n\n/**\n * FORGE-style display status: `queued` = pending with all blockers done;\n * `cancelled` = a task the user stopped (stored as a terminal `failed` node\n * carrying `metadata.cancelled`, surfaced distinctly so it doesn't read as an\n * error). Display-only — not a core `TaskStatus`.\n */\nexport type SddTaskDisplayStatus = TaskNode['status'] | 'queued' | 'cancelled';\n\nexport interface SddBoardTask {\n id: string;\n /** Stable short id (t01, t02, …) in creation order. */\n shortId: string;\n title: string;\n description: string;\n status: TaskNode['status'];\n displayStatus: SddTaskDisplayStatus;\n priority: TaskNode['priority'];\n type: TaskNode['type'];\n /** Short ids of the tasks that block this one (depends_on edges). */\n deps: string[];\n /** Worker on the task right now (scientist nickname), if any. */\n agentName?: string | undefined;\n /** Git worktree branch this task runs in, when isolated. */\n worktreeBranch?: string | undefined;\n startedAt?: number | undefined;\n completedAt?: number | undefined;\n retries: number;\n /** Per-task model assignment (overrides the run default), if set. */\n model?: string | undefined;\n /** Per-task provider assignment (overrides the run default), if set. */\n provider?: string | undefined;\n /** Per-task fallback model chain (overrides the run default), if set. */\n fallbackModels?: string[] | undefined;\n /** Per-task completion-gate verification command, if set. */\n verificationCommand?: string | undefined;\n}\n\n/** A topological column: tasks whose deepest dependency chain is `depth`. */\nexport interface SddBoardColumn {\n label: string;\n /** Short ids of the tasks in this column (join against `tasks`). */\n taskIds: string[];\n}\n\nexport interface SddDeadlockChain {\n /** Short id of the blocked task. */\n blocked: string;\n /** Short ids of the failed/incomplete blockers holding it. */\n blockedBy: string[];\n}\n\n/** One entry in the live activity feed (the board's \"what just happened\" ticker). */\nexport interface SddBoardFeedEntry {\n ts: number;\n kind:\n | 'started'\n | 'completed'\n | 'failed'\n | 'retrying'\n | 'wave'\n | 'deadlock'\n | 'verification_failed'\n | 'conflict'\n | 'split'\n | 'supervisor';\n /** Short id of the task this entry concerns, when applicable. */\n taskShortId?: string | undefined;\n /** Worker involved, when applicable. */\n agentName?: string | undefined;\n /** Human-readable one-line summary. */\n text: string;\n}\n\nexport interface SddBoardSnapshot {\n runId: string;\n specId?: string | undefined;\n graphId: string;\n title: string;\n status: SddBoardStatus;\n startedAt: number;\n updatedAt: number;\n progress: TaskProgress;\n /** Current wave index (0-based) of the parallel run. */\n wave: number;\n tasks: SddBoardTask[];\n columns: SddBoardColumn[];\n diagnostics?: { deadlockChains?: SddDeadlockChain[] } | undefined;\n /** Live activity feed — most recent first (capped). */\n feed?: SddBoardFeedEntry[] | undefined;\n /** Run-level default worker model (task overrides take precedence). */\n defaultModel?: string | undefined;\n /** Run-level default worker provider. */\n defaultProvider?: string | undefined;\n /** Run-level default fallback model chain. */\n fallbackModels?: string[] | undefined;\n /** Base branch the run's squash commits land on (worktree runs only). */\n baseBranch?: string | undefined;\n /**\n * Squash commits the run landed on the base branch, in landing order. Lets a\n * post-run `/sdd rollback` revert them from disk after the live run is gone.\n */\n mergedCommits?: Array<{ taskId: string; sha: string; title: string }> | undefined;\n}\n\n/**\n * Lay a TaskGraph's nodes into topological dependency columns with stable short\n * ids and per-task blocker refs. Shared by the projector (live) and any static\n * board browser. Pure; no run state — `agentName`/`worktreeBranch`/`retries`\n * are read from the node's `assignee`/`metadata` so a reload reflects the last\n * persisted run.\n */\n/**\n * Stable short-id map (t01, t02, …) for a graph's nodes in creation order.\n * Shared by the board renderer and the projector (deadlock-chain labelling).\n */\nexport function shortIdMap(graph: TaskGraph): Map<string, string> {\n const nodes = Array.from(graph.nodes.values()).sort((a, b) => a.createdAt - b.createdAt);\n const m = new Map<string, string>();\n nodes.forEach((n, i) => {\n m.set(n.id, `t${String(i + 1).padStart(2, '0')}`);\n });\n return m;\n}\n\nexport function buildBoardTasks(graph: TaskGraph): {\n tasks: SddBoardTask[];\n columns: SddBoardColumn[];\n} {\n const nodes = Array.from(graph.nodes.values()).sort((a, b) => a.createdAt - b.createdAt);\n const shortId = shortIdMap(graph);\n\n // Blockers per node (depends_on edges pointing at the node).\n const blockers = new Map<string, string[]>();\n for (const n of nodes) blockers.set(n.id, []);\n for (const e of graph.edges) {\n if (e.type === 'depends_on') blockers.get(e.to)?.push(e.from);\n }\n\n const statusOf = (id: string) => graph.nodes.get(id)?.status;\n\n // Memoized topological depth (longest blocker chain), cycle-guarded.\n const depthCache = new Map<string, number>();\n const depthOf = (id: string, seen = new Set<string>()): number => {\n const cached = depthCache.get(id);\n if (cached !== undefined) return cached;\n if (seen.has(id)) return 0;\n seen.add(id);\n const deps = blockers.get(id) ?? [];\n const d = deps.length === 0 ? 0 : 1 + Math.max(...deps.map((b) => depthOf(b, seen)));\n depthCache.set(id, d);\n return d;\n };\n\n const toTask = (n: TaskNode): SddBoardTask => {\n const deps = blockers.get(n.id) ?? [];\n const allDepsDone = deps.every((b) => statusOf(b) === 'completed');\n const meta = (n.metadata ?? {}) as Record<string, unknown>;\n const cancelled = Boolean(meta['cancelled']);\n const displayStatus: SddTaskDisplayStatus = cancelled\n ? 'cancelled'\n : n.status === 'pending' && deps.length > 0 && allDepsDone\n ? 'queued'\n : n.status;\n return {\n id: n.id,\n shortId: shortId.get(n.id) ?? n.id.slice(0, 6),\n title: n.title,\n description: n.description,\n status: n.status,\n displayStatus,\n priority: n.priority,\n type: n.type,\n deps: deps.map((b) => shortId.get(b) ?? b.slice(0, 6)),\n agentName: n.assignee,\n worktreeBranch: typeof meta['worktreeBranch'] === 'string' ? (meta['worktreeBranch'] as string) : undefined,\n startedAt: n.startedAt,\n completedAt: n.completedAt,\n retries: typeof meta['retries'] === 'number' ? (meta['retries'] as number) : 0,\n model: typeof meta['model'] === 'string' ? (meta['model'] as string) : undefined,\n provider: typeof meta['provider'] === 'string' ? (meta['provider'] as string) : undefined,\n fallbackModels: Array.isArray(meta['fallbackModels']) ? (meta['fallbackModels'] as string[]) : undefined,\n verificationCommand:\n typeof meta['verificationCommand'] === 'string' ? (meta['verificationCommand'] as string) : undefined,\n };\n };\n\n const tasks = nodes.map(toTask);\n\n const byDepth = new Map<number, string[]>();\n for (const n of nodes) {\n const d = depthOf(n.id);\n if (!byDepth.has(d)) byDepth.set(d, []);\n byDepth.get(d)?.push(shortId.get(n.id) ?? n.id.slice(0, 6));\n }\n const columns: SddBoardColumn[] = [...byDepth.keys()]\n .sort((a, b) => a - b)\n .map((d) => ({ label: d === 0 ? 'Start' : `Phase ${d}`, taskIds: byDepth.get(d) ?? [] }));\n\n return { tasks, columns };\n}\n\n/**\n * Build a full board snapshot from a graph + run state. The projector calls\n * this on every (throttled) change.\n */\nexport function buildBoardSnapshot(\n graph: TaskGraph,\n run: {\n runId: string;\n specId?: string | undefined;\n status: SddBoardStatus;\n startedAt: number;\n wave: number;\n deadlockChains?: SddDeadlockChain[] | undefined;\n defaultModel?: string | undefined;\n defaultProvider?: string | undefined;\n fallbackModels?: string[] | undefined;\n baseBranch?: string | undefined;\n mergedCommits?: Array<{ taskId: string; sha: string; title: string }> | undefined;\n },\n now: number,\n): SddBoardSnapshot {\n const { tasks, columns } = buildBoardTasks(graph);\n return {\n runId: run.runId,\n specId: run.specId,\n graphId: graph.id,\n title: graph.title,\n status: run.status,\n startedAt: run.startedAt,\n updatedAt: now,\n progress: computeTaskProgress(graph),\n wave: run.wave,\n tasks,\n columns,\n diagnostics: run.deadlockChains?.length ? { deadlockChains: run.deadlockChains } : undefined,\n defaultModel: run.defaultModel,\n defaultProvider: run.defaultProvider,\n fallbackModels: run.fallbackModels,\n baseBranch: run.baseBranch,\n mergedCommits: run.mergedCommits?.length ? run.mergedCommits : undefined,\n };\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport type { SddBoardSnapshot } from './board-types.js';\n\nexport interface SddBoardStoreOptions {\n /** Directory for board snapshots + event logs (wpaths.projectSddBoards). */\n baseDir: string;\n}\n\nexport interface SddBoardIndexEntry {\n runId: string;\n specId?: string | undefined;\n title: string;\n status: string;\n total: number;\n completed: number;\n updatedAt: number;\n}\n\ninterface SddBoardIndex {\n version: 1;\n entries: SddBoardIndexEntry[];\n}\n\n/** One appended line in a board's JSONL event log. */\nexport interface SddBoardEvent {\n ts: number;\n type: string;\n payload?: unknown;\n}\n\n/**\n * File-backed SDD board storage. Each board (= one parallel run) has:\n * - `<runId>.json` — latest full snapshot (atomic; resume + standalone-webui mirror)\n * - `<runId>.events.jsonl`— append-only event log (audit / replay)\n * - `<runId>.control.jsonl` — append-only command queue (cross-process control, written by readers)\n * plus `_index.json` for fast listing. JSON for state, JSONL for streams.\n */\nexport class SddBoardStore {\n private readonly baseDir: string;\n private readonly indexPath: string;\n\n constructor(opts: SddBoardStoreOptions) {\n this.baseDir = opts.baseDir;\n this.indexPath = path.join(this.baseDir, '_index.json');\n }\n\n snapshotPath(runId: string): string {\n return path.join(this.baseDir, `${this.safe(runId)}.json`);\n }\n eventsPath(runId: string): string {\n return path.join(this.baseDir, `${this.safe(runId)}.events.jsonl`);\n }\n controlPath(runId: string): string {\n return path.join(this.baseDir, `${this.safe(runId)}.control.jsonl`);\n }\n\n async saveSnapshot(snapshot: SddBoardSnapshot): Promise<void> {\n await ensureDir(this.baseDir);\n await atomicWrite(this.snapshotPath(snapshot.runId), JSON.stringify(snapshot, null, 2), {\n mode: 0o600,\n });\n await this.updateIndex(snapshot);\n }\n\n async load(runId: string): Promise<SddBoardSnapshot | null> {\n try {\n const raw = await fsp.readFile(this.snapshotPath(runId), 'utf8');\n return JSON.parse(raw) as SddBoardSnapshot;\n } catch {\n return null;\n }\n }\n\n async list(): Promise<SddBoardIndexEntry[]> {\n const index = await this.readIndex();\n return index.entries.sort((a, b) => b.updatedAt - a.updatedAt);\n }\n\n async loadLatestForSpec(specId: string): Promise<SddBoardSnapshot | null> {\n const entry = (await this.list()).find((e) => e.specId === specId);\n return entry ? this.load(entry.runId) : null;\n }\n\n /** Append one line to the board's JSONL event log (best-effort, never throws). */\n async appendEvent(runId: string, event: SddBoardEvent): Promise<void> {\n try {\n await ensureDir(this.baseDir);\n await fsp.appendFile(this.eventsPath(runId), `${JSON.stringify(event)}\\n`, { mode: 0o600 });\n } catch {\n /* event log is best-effort */\n }\n }\n\n /** Append a control command (used by readers to steer a CLI-owned run). */\n async appendControl(runId: string, command: { ts: number; type: string; payload?: unknown }): Promise<void> {\n await ensureDir(this.baseDir);\n await fsp.appendFile(this.controlPath(runId), `${JSON.stringify(command)}\\n`, { mode: 0o600 });\n }\n\n /** Read + truncate the control queue (the run drains it). Returns parsed commands. */\n async drainControl(runId: string): Promise<Array<{ ts: number; type: string; payload?: unknown }>> {\n const p = this.controlPath(runId);\n let raw: string;\n try {\n raw = await fsp.readFile(p, 'utf8');\n } catch {\n return [];\n }\n try {\n await fsp.writeFile(p, '', { mode: 0o600 });\n } catch {\n /* ignore truncate failure */\n }\n return raw\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => {\n try {\n return JSON.parse(l) as { ts: number; type: string; payload?: unknown };\n } catch {\n return null;\n }\n })\n .filter((c): c is { ts: number; type: string; payload?: unknown } => c !== null);\n }\n\n async delete(runId: string): Promise<void> {\n await Promise.allSettled([\n fsp.unlink(this.snapshotPath(runId)),\n fsp.unlink(this.eventsPath(runId)),\n fsp.unlink(this.controlPath(runId)),\n ]);\n await this.removeFromIndex(runId);\n }\n\n // ── internal ────────────────────────────────────────────────────────────\n\n private safe(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9._-]/g, '_');\n }\n\n private async readIndex(): Promise<SddBoardIndex> {\n try {\n const raw = await fsp.readFile(this.indexPath, 'utf8');\n const parsed = JSON.parse(raw) as SddBoardIndex;\n if (parsed?.version === 1) return parsed;\n } catch {\n /* no index yet */\n }\n return { version: 1, entries: [] };\n }\n\n private async updateIndex(snapshot: SddBoardSnapshot): Promise<void> {\n const index = await this.readIndex();\n const entry: SddBoardIndexEntry = {\n runId: snapshot.runId,\n specId: snapshot.specId,\n title: snapshot.title,\n status: snapshot.status,\n total: snapshot.progress.total,\n completed: snapshot.progress.completed,\n updatedAt: snapshot.updatedAt,\n };\n const idx = index.entries.findIndex((e) => e.runId === snapshot.runId);\n if (idx >= 0) index.entries[idx] = entry;\n else index.entries.push(entry);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n\n private async removeFromIndex(runId: string): Promise<void> {\n const index = await this.readIndex();\n index.entries = index.entries.filter((e) => e.runId !== runId);\n await atomicWrite(this.indexPath, JSON.stringify(index, null, 2), { mode: 0o600 });\n }\n}\n","/**\n * SddBoardProjector\n *\n * Composes a live SDD board snapshot from a running graph and streams it to\n * every surface. It subscribes to `TaskTracker` mutations (the source of truth\n * for task state) plus the run's `sdd.*` lifecycle events (status / wave /\n * deadlock), and on each change — throttled — rebuilds a `SddBoardSnapshot`,\n * emits `sdd.board.snapshot` on the EventBus, persists it (JSON) and appends the\n * triggering event to the board's JSONL log.\n *\n * The graph is the single source of truth: task status/assignee/worktree live\n * on the nodes (the run mutates them through the tracker), so the projector\n * mostly re-derives the snapshot and only tracks run-level status/wave/deadlock.\n */\nimport type { EventBus, EventMap } from '../kernel/events.js';\nimport type { TaskGraph } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport {\n buildBoardSnapshot,\n shortIdMap,\n type SddBoardFeedEntry,\n type SddBoardStatus,\n type SddDeadlockChain,\n} from './board-types.js';\nimport type { SddBoardStore } from './sdd-board-store.js';\n\nexport interface SddBoardProjectorOptions {\n runId: string;\n graph: TaskGraph;\n tracker: TaskTracker;\n events: EventBus;\n /** Persist snapshots + JSONL events (optional — omit for in-memory only). */\n store?: SddBoardStore | undefined;\n specId?: string | undefined;\n /** Run-level default worker model/provider/fallbacks (shown in the board header). */\n defaultModel?: string | undefined;\n defaultProvider?: string | undefined;\n fallbackModels?: string[] | undefined;\n /** Base branch the run's squash commits land on (for the board + rollback). */\n baseBranch?: string | undefined;\n /** Snapshot coalescing window in ms (default 250). */\n throttleMs?: number | undefined;\n /** Clock injection for tests; defaults to Date.now. */\n now?: (() => number) | undefined;\n}\n\nexport class SddBoardProjector {\n private readonly o: SddBoardProjectorOptions;\n private readonly now: () => number;\n private readonly throttleMs: number;\n private readonly shortId: Map<string, string>;\n\n private status: SddBoardStatus = 'idle';\n private wave = 0;\n private startedAt: number;\n private deadlockChains: SddDeadlockChain[] = [];\n /** Live activity feed, most recent first (capped). */\n private feed: SddBoardFeedEntry[] = [];\n private static readonly FEED_CAP = 60;\n private finished = false;\n private runDeadlocked = false;\n private runStopped = false;\n /** Squash commits the run landed on the base branch (for post-run rollback). */\n private mergedCommits: Array<{ taskId: string; sha: string; title: string }> = [];\n /** Base branch reported by the run at start (overrides the constructor option). */\n private runBaseBranch: string | undefined;\n\n private dirty = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly unsubs: Array<() => void> = [];\n /** Tail of in-flight persistence, so callers can await a settled state. */\n private lastSave: Promise<void> = Promise.resolve();\n\n constructor(opts: SddBoardProjectorOptions) {\n this.o = opts;\n this.now = opts.now ?? Date.now;\n this.throttleMs = opts.throttleMs ?? 250;\n this.shortId = shortIdMap(opts.graph);\n this.startedAt = this.now();\n\n // Source of truth: any task mutation redraws the board.\n this.unsubs.push(opts.tracker.subscribe(() => this.markDirty()));\n\n // Run lifecycle → status/wave/deadlock + JSONL audit.\n this.onRun('sdd.run.started', (e) => {\n this.status = 'running';\n this.startedAt = this.now();\n if (e.baseBranch) this.runBaseBranch = e.baseBranch;\n this.markDirty();\n });\n this.onRun('sdd.run.finished', (e) => {\n this.finished = true;\n this.runDeadlocked = e.deadlocked;\n this.runStopped = e.stopped;\n this.flush(); // final snapshot persists synchronously\n });\n this.onRun('sdd.wave', (e) => {\n this.wave = e.wave;\n this.pushFeed({ ts: this.now(), kind: 'wave', text: `Wave ${e.wave + 1} started · ${e.batchSize} task(s) in parallel` });\n this.markDirty();\n });\n this.onRun('sdd.deadlock', (e) => {\n this.deadlockChains = e.chains.map((c) => ({\n blocked: this.shortId.get(c.blocked) ?? c.blocked.slice(0, 6),\n blockedBy: c.blockedBy.map((b) => this.shortId.get(b) ?? b.slice(0, 6)),\n }));\n this.pushFeed({ ts: this.now(), kind: 'deadlock', text: `Deadlock — ${e.chains.length} task(s) blocked by failed work` });\n this.markDirty();\n });\n // Task lifecycle → live activity feed (task STATE comes from the tracker,\n // which already triggers a redraw; here we narrate \"what just happened\").\n this.onRun('sdd.task.started', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'started',\n taskShortId: sid,\n agentName: e.agentName,\n text: `${e.agentName || 'a worker'} picked up ${sid ?? 'a task'}${this.titleOf(e.taskId)}`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.completed', (e) => {\n const sid = this.shortId.get(e.taskId);\n const agent = this.assigneeOf(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'completed',\n taskShortId: sid,\n agentName: agent,\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} completed${agent ? ` by ${agent}` : ''} · ${(e.durationMs / 1000).toFixed(1)}s`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.failed', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'failed',\n taskShortId: sid,\n agentName: this.assigneeOf(e.taskId),\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} failed — ${e.error}`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.retrying', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'retrying',\n taskShortId: sid,\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} retrying (${e.attempt}/${e.maxRetries})`,\n });\n this.markDirty();\n });\n // Robustness events (completion gate / merge / supervisor / split) — narrate\n // \"why a task didn't just sail to done\" so the board never silently hides a\n // gate rejection, conflict, or supervisor verdict.\n this.onRun('sdd.task.verification_failed', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'verification_failed',\n taskShortId: sid,\n agentName: this.assigneeOf(e.taskId),\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} failed verification — ${e.reason}`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.conflict', (e) => {\n const sid = this.shortId.get(e.taskId);\n const files = e.conflictFiles.length;\n this.pushFeed({\n ts: this.now(),\n kind: 'conflict',\n taskShortId: sid,\n agentName: this.assigneeOf(e.taskId),\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} merge conflict — ${files} file(s)${files ? `: ${e.conflictFiles.slice(0, 3).join(', ')}${files > 3 ? '…' : ''}` : ''}`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.merged', (e) => {\n // Persist the run commit so a post-run rollback can revert it off disk.\n const title = this.o.graph.nodes.get(e.taskId)?.title ?? '';\n this.mergedCommits.push({ taskId: e.taskId, sha: e.sha, title });\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'completed',\n taskShortId: sid,\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} merged → ${this.runBaseBranch ?? this.o.baseBranch ?? 'base'} (${e.sha.slice(0, 8)})`,\n });\n this.markDirty();\n });\n this.onRun('sdd.task.split', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'split',\n taskShortId: sid,\n text: `${sid ?? 'task'}${this.titleOf(e.taskId)} split into ${e.subtaskIds.length} sub-task(s)`,\n });\n this.markDirty();\n });\n this.onRun('sdd.supervisor.decision', (e) => {\n const sid = this.shortId.get(e.taskId);\n this.pushFeed({\n ts: this.now(),\n kind: 'supervisor',\n taskShortId: sid,\n text: `supervisor → ${e.action} for ${sid ?? 'task'}${this.titleOf(e.taskId)}${e.rationale ? ` (${e.rationale})` : ''}`,\n });\n this.markDirty();\n });\n }\n\n private pushFeed(entry: SddBoardFeedEntry): void {\n this.feed.unshift(entry);\n if (this.feed.length > SddBoardProjector.FEED_CAP) this.feed.length = SddBoardProjector.FEED_CAP;\n }\n\n /** ` (title…)` suffix for a feed line, or '' when the node/title is missing. */\n private titleOf(taskId: string): string {\n const t = this.o.graph.nodes.get(taskId)?.title;\n if (!t) return '';\n return ` (${t.length > 40 ? `${t.slice(0, 39)}…` : t})`;\n }\n\n private assigneeOf(taskId: string): string | undefined {\n return this.o.graph.nodes.get(taskId)?.assignee;\n }\n\n /** Latest snapshot, built on demand (e.g. for a late-joining client). */\n snapshot() {\n return this.build();\n }\n\n /** Resolve once all in-flight snapshot persistence has settled. */\n async drain(): Promise<void> {\n await this.lastSave;\n }\n\n /** Stop projecting and release subscriptions. */\n dispose(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n for (const u of this.unsubs) u();\n this.unsubs.length = 0;\n }\n\n // ── internal ────────────────────────────────────────────────────────────\n\n /** Subscribe to a run event scoped to this run id; also append to JSONL. */\n private onRun<K extends keyof EventMap>(event: K, handler: (e: EventMap[K]) => void): void {\n const wrapped = (e: EventMap[K]) => {\n if ((e as { runId?: string }).runId !== this.o.runId) return;\n void this.o.store?.appendEvent(this.o.runId, { ts: this.now(), type: event, payload: e });\n handler(e);\n };\n const off = this.o.events.on(event, wrapped as (p: EventMap[K]) => void);\n this.unsubs.push(off);\n }\n\n private resolveStatus(completed: number, total: number): SddBoardStatus {\n if (!this.finished) return this.status;\n if (this.runDeadlocked) return 'deadlocked';\n if (total > 0 && completed >= total) return 'completed';\n if (this.runStopped) return 'paused';\n return 'failed';\n }\n\n private build() {\n const snap = buildBoardSnapshot(\n this.o.graph,\n {\n runId: this.o.runId,\n specId: this.o.specId,\n status: 'running',\n startedAt: this.startedAt,\n wave: this.wave,\n deadlockChains: this.deadlockChains,\n defaultModel: this.o.defaultModel,\n defaultProvider: this.o.defaultProvider,\n fallbackModels: this.o.fallbackModels,\n baseBranch: this.runBaseBranch ?? this.o.baseBranch,\n mergedCommits: this.mergedCommits,\n },\n this.now(),\n );\n snap.status = this.resolveStatus(snap.progress.completed, snap.progress.total);\n snap.feed = this.feed.slice(0, SddBoardProjector.FEED_CAP);\n return snap;\n }\n\n private markDirty(): void {\n this.dirty = true;\n if (this.timer || this.finished) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n if (this.dirty) this.flush();\n }, this.throttleMs);\n }\n\n private flush(): void {\n this.dirty = false;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const snap = this.build();\n this.o.events.emit('sdd.board.snapshot', { runId: this.o.runId, snapshot: snap });\n if (this.o.store) {\n // Serialize writes (no two snapshots race on the same file) and swallow\n // persistence errors — a live stream must never crash on a disk hiccup.\n const store = this.o.store;\n this.lastSave = this.lastSave.then(() => store.saveSnapshot(snap)).catch(() => {});\n }\n }\n}\n","import type { SddBoardSnapshot } from './board-types.js';\nimport type { SddSubtaskSpec } from './sdd-parallel-run.js';\n\n/**\n * Control surface over a live SDD run, exposed to every steering surface\n * (TUI, CLI-hosted webui in-process; standalone webui via a control file the\n * run drains). The run itself stays CLI-owned — this is the only sanctioned\n * way to pause / retry / reassign from outside the run loop.\n */\nexport interface SddRunControl {\n runId: string;\n specId?: string | undefined;\n pause(): void;\n resume(): void;\n stop(): void;\n retryTask(taskId: string): boolean;\n /** Requeue every failed task to pending (board \"Retry all failed\"). Returns the count. */\n retryAllFailed(): number;\n reassignTask(taskId: string, agentName: string): boolean;\n /** Set/override a task's worker model (+ optional provider). Next dispatch. */\n setTaskModel(taskId: string, model: string | undefined, provider?: string | undefined): boolean;\n /** Set/override a task's fallback model chain. Next dispatch. */\n setTaskFallbacks(taskId: string, fallbackModels: string[] | undefined): boolean;\n /** Set/override a task's completion-gate verification command. Next dispatch. */\n setTaskVerification(taskId: string, verificationCommand: string | undefined): boolean;\n /** Cancel a task — abort it if running, else mark it cancelled. */\n cancelTask(taskId: string): Promise<boolean> | boolean;\n /** Delete a not-started task from the graph (refused while running). */\n deleteTask(taskId: string): boolean;\n /** Split a task into sub-tasks (refused while running). Returns the new leaf ids. */\n splitTask(taskId: string, subtasks: SddSubtaskSpec[]): string[];\n /**\n * Remove every git worktree + branch the run created (refused while running —\n * stop first). Returns the number removed.\n */\n cleanupWorktrees(): Promise<number>;\n /**\n * Undo the run's merged commits by reverting each on the base branch (refused\n * while running). History-preserving; refuses on a dirty tree / revert conflict.\n */\n rollback(): Promise<{ ok: boolean; reverted: number; reason?: string }>;\n /** Base branch the run's squash commits land on (worktree runs only). */\n getBaseBranch(): string | undefined;\n /** Squash commits the run landed on the base branch, in landing order. */\n getMergedCommits(): ReadonlyArray<{ taskId: string; sha: string; title: string }>;\n /** Latest board snapshot (built on demand). */\n snapshot(): SddBoardSnapshot;\n isRunning(): boolean;\n}\n\n/**\n * In-process registry of the active SDD run. One run is active at a time (a\n * single fleet drives it); a new run replaces the previous. Lives in the CLI\n * process where the fleet runs.\n */\nexport class SddRunRegistry {\n private current: SddRunControl | null = null;\n\n register(control: SddRunControl): void {\n this.current = control;\n }\n\n clear(runId: string): void {\n if (this.current?.runId === runId) this.current = null;\n }\n\n getActive(): SddRunControl | null {\n return this.current;\n }\n}\n","import { expectDefined } from '../utils/expect-defined.js';\r\nimport { toErrorMessage } from '../utils/error.js';\nimport type { Specification, SpecRequirement, SpecSection } from '../types/spec.js';\r\nimport type { SpecStore } from './spec-store.js';\r\nimport { SddError, ERROR_CODES } from '../types/errors.js';\r\n\r\n// ─── Session Types ────────────────────────────────────────────────────────────\r\n\r\nexport type AISpecPhase =\r\n | 'questioning' // AI is asking questions\r\n | 'spec_review' // Spec generated, waiting for user approval\r\n | 'implementation' // Implementation plan phase\r\n | 'task_review' // Tasks generated, waiting for execution\r\n | 'executing' // Running tasks\r\n | 'done'; // Everything complete\r\n\r\nexport interface CollectedAnswer {\r\n question: string;\r\n answer: string;\r\n timestamp: number;\r\n}\r\n\r\nexport interface AISpecSession {\r\n id: string;\r\n phase: AISpecPhase;\r\n title: string;\r\n userIntent: string;\r\n projectContext: string;\r\n answers: CollectedAnswer[];\r\n questionCount: number;\r\n spec?: Specification | undefined;\r\n implementation?: string | undefined;\r\n taskGraphId?: string | undefined;\r\n approved: boolean;\r\n createdAt: number;\r\n updatedAt: number;\r\n}\r\n\r\n// ─── Builder Options ──────────────────────────────────────────────────────────\r\n\r\nexport interface AISpecBuilderOptions {\r\n store: SpecStore;\r\n /** Minimum questions the AI should ask. Default: 2 */\r\n minQuestions?: number | undefined;\r\n /** Maximum questions before forcing spec generation. Default: 10 */\r\n maxQuestions?: number | undefined;\r\n /** Project context string (package.json, file structure, etc.) */\r\n projectContext?: string | undefined;\r\n /** Path to persist session state. If set, session survives process restarts. */\r\n sessionPath?: string | undefined;\r\n}\r\n\r\n// ─── AI Prompts ───────────────────────────────────────────────────────────────\r\n\r\nfunction buildQuestioningPrompt(session: AISpecSession, min: number, max: number): string {\r\n const answered = session.answers.length;\r\n const remaining = Math.max(0, min - answered);\r\n const budget = max - answered;\r\n\r\n const lines: string[] = [\r\n `═══ SDD Spec Builder ═══`,\r\n `Feature: \"${session.title}\"`,\r\n session.userIntent ? `Intent: ${session.userIntent}` : '',\r\n `Phase: Questioning (${answered} answered, ${budget} remaining budget)`,\r\n '',\r\n '**Instructions for AI:**',\r\n '',\r\n 'You are conducting a specification interview. Your job is to ask the user',\r\n 'intelligent, contextual questions to understand what they want to build.',\r\n '',\r\n `You have asked ${answered} questions so far.`,\r\n ];\r\n\r\n if (remaining > 0) {\r\n lines.push(`You MUST ask at least ${remaining} more question(s) before generating the spec.`);\r\n } else if (budget <= 0) {\r\n lines.push('You have reached the maximum question budget. Generate the spec NOW.');\r\n } else {\r\n lines.push(\r\n 'You may ask more questions if needed, or generate the spec if you have enough information.',\r\n 'Ask a question ONLY if it reveals something you genuinely need to know.',\r\n );\r\n }\r\n\r\n lines.push(\r\n '',\r\n '**Rules:**',\r\n '- Ask ONE question at a time',\r\n '- Questions must be specific and contextual — never generic',\r\n '- Adapt based on previous answers',\r\n '- Cover: scope, constraints, edge cases, integrations, security, performance as relevant',\r\n '- When you have enough info, respond with the full specification in JSON format',\r\n '',\r\n `**Question budget:** ${budget}/${max} remaining`,\r\n `**Minimum required:** ${remaining > 0 ? remaining : 'met'}`,\r\n );\r\n\r\n if (session.projectContext) {\r\n lines.push('', '**Project Context:**', '```', session.projectContext, '```');\r\n }\r\n\r\n if (answered > 0) {\r\n lines.push('', '**Conversation so far:**');\r\n for (let i = 0; i < answered; i++) {\r\n const a = expectDefined(session.answers[i]);\r\n lines.push(``, `Q${i + 1}: ${a.question}`, `A${i + 1}: ${a.answer}`);\r\n }\r\n }\r\n\r\n lines.push(\r\n '',\r\n '---',\r\n 'Now either:',\r\n `1. Ask your next question (if you need more info)`,\r\n `2. Generate the complete specification as JSON (if ready)`,\r\n '',\r\n 'If generating spec, output JSON inside ```json code block with this structure:',\r\n '```json',\r\n '{',\r\n ' \"title\": \"...\",',\r\n ' \"overview\": \"...\",',\r\n ' \"sections\": [{ \"type\": \"overview|requirements|architecture|api|data|security|acceptance\", \"title\": \"...\", \"content\": \"...\", \"level\": 1 }],',\r\n ' \"requirements\": [{ \"id\": \"REQ-1\", \"type\": \"functional|non-functional|security|performance|ux\", \"priority\": \"critical|high|medium|low\", \"description\": \"...\", \"acceptanceCriteria\": [\"...\"] }]',\r\n '}',\r\n '```',\r\n );\r\n\r\n return lines.filter(Boolean).join('\\n');\r\n}\r\n\r\nfunction buildSpecReviewPrompt(session: AISpecSession): string {\r\n const spec = session.spec;\r\n if (!spec) return 'No spec generated yet.';\r\n\r\n const reqSummary = spec.requirements\r\n .map((r) => ` [${r.priority}] ${r.description}`)\r\n .join('\\n');\r\n\r\n return [\r\n `═══ Spec Review ═══`,\r\n `Feature: \"${spec.title}\"`,\r\n `Requirements: ${spec.requirements.length}`,\r\n '',\r\n '**Specification:**',\r\n spec.overview,\r\n '',\r\n '**Requirements:**',\r\n reqSummary,\r\n '',\r\n '---',\r\n 'Approve this spec? The AI will then generate an implementation plan and tasks.',\r\n 'Say \"approve\" to proceed, or describe what needs to change.',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildImplementationPrompt(session: AISpecSession): string {\r\n const spec = session.spec;\r\n if (!spec) return 'No spec to implement.';\r\n\r\n const reqList = spec.requirements\r\n .map((r) => ` - [${r.priority}] ${r.description}`)\r\n .join('\\n');\r\n\r\n return [\r\n `═══ Implementation Planning ═══`,\r\n `Feature: \"${spec.title}\"`,\r\n `Requirements: ${spec.requirements.length}`,\r\n '',\r\n '**Requirements to implement:**',\r\n reqList,\r\n '',\r\n '**Instructions for AI:**',\r\n 'Generate a detailed implementation plan for this specification.',\r\n 'Include:',\r\n '1. Architecture decisions',\r\n '2. File structure changes',\r\n '3. Key implementation details',\r\n '4. Dependency requirements',\r\n '5. Testing strategy',\r\n '',\r\n '**IMPORTANT:** After the plan, you MUST generate executable tasks as a JSON array.',\r\n 'Each task should be a concrete, actionable step. Output the JSON inside a ```json code block:',\r\n '```json',\r\n '[',\r\n ' {',\r\n ' \"id\": \"t1\",',\n ' \"title\": \"Create auth middleware\",',\r\n ' \"description\": \"Implement JWT verification middleware for protected routes\",',\r\n ' \"type\": \"feature\",',\r\n ' \"priority\": \"critical\",',\r\n ' \"estimateHours\": 3,',\r\n ' \"dependsOn\": [],',\n ' \"tags\": [\"auth\", \"middleware\"]',\r\n ' },',\r\n ' {',\r\n ' \"id\": \"t2\",',\n ' \"title\": \"Write auth tests\",',\r\n ' \"description\": \"Unit and integration tests for authentication flow\",',\r\n ' \"type\": \"test\",',\r\n ' \"priority\": \"high\",',\r\n ' \"estimateHours\": 2,',\r\n ' \"dependsOn\": [\"t1\"],',\n ' \"tags\": [\"test\", \"auth\"]',\r\n ' }',\r\n ']',\r\n '```',\r\n '',\r\n 'Rules:',\r\n '- Give every task a short stable \"id\" (t1, t2, …). Reference prerequisites in \"dependsOn\"',\n ' as a list of those ids — this builds the real dependency graph that drives parallel vs',\n ' sequential execution.',\n '- \"dependsOn\": [] means the task is independent and may run in parallel with other roots.',\n '- A task with dependsOn runs ONLY after every listed task completes. Model true ordering:',\n ' tests depend on the feature they test, docs/integration depend on the parts they cover.',\n '- Do NOT create cycles (t1→t2→t1). Keep chains as shallow as correctness allows so',\n ' independent work runs concurrently.',\n '- Use type: \"feature\" for code, \"test\" for tests, \"docs\" for documentation, \"chore\" for config',\r\n '- Use priority: \"critical\" for blockers, \"high\" for core features, \"medium\" for nice-to-haves, \"low\" for polish',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildTaskReviewPrompt(session: AISpecSession): string {\r\n return [\r\n `═══ Task Review ═══`,\r\n `Feature: \"${session.spec?.title ?? session.title}\"`,\r\n '',\r\n session.implementation ?? 'No implementation plan yet.',\r\n '',\r\n '---',\r\n 'Ready to execute these tasks? Say \"execute\" to begin, or describe changes needed.',\r\n ].join('\\n');\r\n}\r\n\r\nfunction buildExecutingPrompt(session: AISpecSession): string {\r\n return [\r\n `═══ Task Execution ═══`,\r\n `Feature: \"${session.spec?.title ?? session.title}\"`,\r\n '',\r\n '**Instructions for AI:**',\r\n 'Execute the tasks one by one in the order shown in the task list above.',\r\n '',\r\n 'For each task:',\r\n '1. Implement the code (create/modify files)',\r\n '2. Write tests if applicable',\r\n '3. After completing a task, tell the user to run: /sdd done <task number or title>',\r\n '4. Then move to the next task',\r\n '',\r\n '**Important:**',\r\n '- Focus on ONE task at a time',\r\n '- After completing each task, explicitly state what you did',\r\n '- Tell the user: \"Run /sdd done <N> to mark this task complete\"',\r\n '- Then proceed to the next task automatically',\r\n '- When ALL tasks are done, provide a summary of everything implemented',\r\n '',\r\n 'Start executing the first pending task now.',\r\n ].join('\\n');\r\n}\r\n\r\n// ─── Spec Builder Class ───────────────────────────────────────────────────────\r\n\r\n/**\r\n * AI-driven specification builder. Instead of static questions, this builder\r\n * tracks conversation state and generates prompts that instruct the AI agent\r\n * to ask contextual questions and build specifications interactively.\r\n */\r\nexport class AISpecBuilder {\r\n private session: AISpecSession;\r\n private readonly store: SpecStore;\r\n private readonly minQuestions: number;\r\n private readonly maxQuestions: number;\r\n private readonly sessionPath?: string | undefined;\r\n\r\n constructor(opts: AISpecBuilderOptions) {\r\n this.store = opts.store;\r\n this.minQuestions = opts.minQuestions ?? 2;\r\n this.maxQuestions = opts.maxQuestions ?? 10;\r\n this.sessionPath = opts.sessionPath;\r\n this.session = {\r\n id: crypto.randomUUID(),\r\n phase: 'questioning',\r\n title: '',\r\n userIntent: '',\r\n projectContext: opts.projectContext ?? '',\r\n answers: [],\r\n questionCount: 0,\r\n approved: false,\r\n createdAt: Date.now(),\r\n updatedAt: Date.now(),\r\n };\r\n }\r\n\r\n // ── Session Persistence ──────────────────────────────────────────────────\r\n\r\n /** Save session state to disk. */\r\n async saveSession(): Promise<void> {\r\n if (!this.sessionPath) return;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n const path = await import('node:path');\r\n const { atomicWrite } = await import('../utils/atomic-write.js');\r\n await fsp.mkdir(path.dirname(this.sessionPath), { recursive: true });\r\n // atomicWrite: torn save would corrupt the SDD session JSON and the\r\n // next load would silently fall back to a fresh session.\r\n await atomicWrite(this.sessionPath, JSON.stringify(this.session, null, 2));\r\n } catch {\r\n // Best-effort persistence — don't crash if save fails\r\n }\r\n }\r\n\r\n /** Load session state from disk. Returns true if a session was loaded. */\r\n async loadSession(): Promise<boolean> {\r\n if (!this.sessionPath) return false;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n const raw = await fsp.readFile(this.sessionPath, 'utf8');\r\n const loaded = JSON.parse(raw) as AISpecSession;\r\n // Validate basic structure\r\n if (loaded?.id && loaded?.phase && loaded?.title) {\r\n this.session = loaded;\r\n return true;\r\n }\r\n } catch {\r\n // No saved session or invalid file\r\n }\r\n return false;\r\n }\r\n\r\n /** Delete saved session from disk. */\r\n async deleteSession(): Promise<void> {\r\n if (!this.sessionPath) return;\r\n try {\r\n const fsp = await import('node:fs/promises');\r\n await fsp.unlink(this.sessionPath);\r\n } catch {\r\n // File might not exist\r\n }\r\n }\r\n\r\n /** Auto-save helper — calls saveSession() but never throws.\r\n * Failures are surfaced via process.emitWarning so a persistent\r\n * ENOSPC / EACCES doesn't silently strand session edits in memory. */\r\n private autoSave(): void {\r\n this.saveSession().catch((err) => {\r\n const detail = toErrorMessage(err);\r\n process.emitWarning(\r\n `SpecBuilder autoSave failed: ${detail}`,\r\n 'SpecBuilderWarning',\r\n );\r\n });\r\n }\r\n\r\n // ── Session Lifecycle ─────────────────────────────────────────────────────\r\n\r\n /** Start a new session with a title and optional intent. */\r\n startSession(title: string, intent?: string): void {\r\n this.session.title = title;\r\n this.session.userIntent = intent ?? '';\r\n this.session.phase = 'questioning';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /** Get current session state (readonly). */\r\n getSession(): Readonly<AISpecSession> {\r\n return { ...this.session };\r\n }\r\n\r\n /** Get the current phase. */\r\n getPhase(): AISpecPhase {\r\n return this.session.phase;\r\n }\r\n\r\n // ── AI Prompt Generation ──────────────────────────────────────────────────\r\n\r\n /**\r\n * Get the AI prompt for the current phase.\r\n * This prompt is injected into the conversation so the AI agent knows\r\n * what to do next (ask a question, generate a spec, etc.).\r\n */\r\n getAIPrompt(): string {\r\n switch (this.session.phase) {\r\n case 'questioning':\r\n return buildQuestioningPrompt(this.session, this.minQuestions, this.maxQuestions);\r\n case 'spec_review':\r\n return buildSpecReviewPrompt(this.session);\r\n case 'implementation':\r\n return buildImplementationPrompt(this.session);\r\n case 'task_review':\r\n return buildTaskReviewPrompt(this.session);\r\n case 'executing':\r\n return buildExecutingPrompt(this.session);\r\n case 'done':\r\n return 'All tasks completed. Specification is fully implemented.';\r\n }\r\n }\r\n\r\n // ── Answer Processing ─────────────────────────────────────────────────────\r\n\r\n /**\r\n * Record a question/answer pair from the AI conversation.\r\n * Call this when the AI asks a question and the user responds.\r\n */\r\n addAnswer(question: string, answer: string): void {\r\n this.session.answers.push({ question, answer, timestamp: Date.now() });\r\n this.session.questionCount++;\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Check if more questions should be asked.\r\n * Returns false if max reached or if the AI has signaled it has enough info.\r\n */\r\n shouldContinueQuestioning(): boolean {\r\n return this.session.questionCount < this.maxQuestions;\r\n }\r\n\r\n /**\r\n * Check if minimum questions have been asked.\r\n */\r\n hasMetMinimumQuestions(): boolean {\r\n return this.session.questionCount >= this.minQuestions;\r\n }\r\n\r\n // ── Phase Transitions ─────────────────────────────────────────────────────\r\n\r\n /**\r\n * Set the generated specification and move to spec_review phase.\r\n */\r\n setSpec(spec: Specification): void {\r\n this.session.spec = spec;\r\n this.session.phase = 'spec_review';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Approve the current phase and advance to the next.\r\n * questioning → spec_review (requires spec to be set)\r\n * spec_review → implementation\r\n * implementation → task_review (requires implementation to be set)\r\n * task_review → executing\r\n * executing → done\r\n */\r\n approve(): AISpecPhase {\r\n switch (this.session.phase) {\r\n case 'questioning':\r\n if (!this.session.spec) {\r\n throw new SddError({\r\n message: 'Cannot approve: no spec generated yet.',\r\n code: ERROR_CODES.SDD_INVALID_STATE,\r\n context: { phase: 'questioning', sessionId: this.session.id },\r\n });\r\n }\r\n this.session.phase = 'spec_review';\r\n break;\r\n case 'spec_review':\r\n this.session.phase = 'implementation';\r\n break;\r\n case 'implementation':\r\n this.session.phase = 'task_review';\r\n break;\r\n case 'task_review':\r\n this.session.phase = 'executing';\r\n break;\r\n case 'executing':\r\n this.session.phase = 'done';\r\n break;\r\n case 'done':\r\n break;\r\n }\r\n this.session.approved = true;\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n return this.session.phase;\r\n }\r\n\r\n /**\r\n * Set the implementation plan text.\r\n */\r\n setImplementation(plan: string): void {\r\n this.session.implementation = plan;\r\n this.session.phase = 'task_review';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Mark session as done.\r\n */\r\n markDone(): void {\r\n this.session.phase = 'done';\r\n this.session.updatedAt = Date.now();\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Set the task graph ID for this session.\r\n */\r\n setTaskGraphId(graphId: string): void {\r\n this.session.taskGraphId = graphId;\r\n this.autoSave();\r\n }\r\n\r\n /**\r\n * Get the task graph ID for this session.\r\n */\r\n getTaskGraphId(): string | undefined {\r\n return this.session.taskGraphId;\r\n }\r\n\r\n // ── Spec Persistence ──────────────────────────────────────────────────────\r\n\r\n /**\r\n * Save the current spec to the store.\r\n */\r\n async saveSpec(): Promise<Specification> {\r\n if (!this.session.spec) {\r\n throw new SddError({\r\n message: 'No spec to save.',\r\n code: ERROR_CODES.SDD_NOT_READY,\r\n context: { sessionId: this.session.id },\r\n });\r\n }\r\n await this.store.save(this.session.spec);\r\n return this.session.spec;\r\n }\r\n\r\n // ── Spec Generation Helpers ───────────────────────────────────────────────\r\n\r\n /**\r\n * Parse a spec from a JSON string (from AI output).\r\n * Validates and normalizes the structure.\r\n */\r\n parseSpecFromJSON(jsonStr: string): Specification {\r\n let parsed: unknown;\r\n try {\r\n parsed = JSON.parse(jsonStr);\r\n } catch (e) {\r\n throw new SddError({\r\n message: 'Invalid JSON for spec',\r\n code: ERROR_CODES.SDD_PARSE_FAILED,\r\n cause: e,\r\n context: { detail: e instanceof Error ? e.message : 'parse error' },\r\n });\r\n }\r\n\r\n if (!parsed || typeof parsed !== 'object') {\r\n throw new SddError({\r\n message: 'Spec JSON must be an object',\r\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\r\n context: { actualType: typeof parsed },\r\n });\r\n }\r\n\r\n const raw = parsed as Record<string, unknown>;\r\n const now = Date.now();\r\n\r\n const title = String(raw.title ?? this.session.title ?? 'Untitled');\r\n const overview = String(raw.overview ?? '');\r\n\r\n // Validate overview is not empty\r\n if (!overview || overview === 'undefined') {\r\n throw new SddError({\r\n message: 'Spec must have an overview',\r\n code: ERROR_CODES.SDD_VALIDATION_FAILED,\r\n context: { field: 'overview', title },\r\n });\r\n }\r\n\r\n const rawSections = Array.isArray(raw.sections) ? raw.sections : [];\r\n const sections: SpecSection[] = rawSections\r\n .filter((s: unknown) => s && typeof s === 'object')\r\n .map((s: Record<string, unknown>) => ({\r\n type: (['overview', 'requirements', 'architecture', 'api', 'data', 'security', 'acceptance']\r\n .includes(String(s.type)) ? String(s.type) : 'overview') as SpecSection['type'],\r\n title: String(s.title ?? ''),\r\n content: String(s.content ?? ''),\r\n level: Number(s.level) || 1,\r\n }));\r\n\r\n const rawReqs = Array.isArray(raw.requirements) ? raw.requirements : [];\r\n const requirements: SpecRequirement[] = rawReqs\r\n .filter((r: unknown) => r && typeof r === 'object')\r\n .map((r: Record<string, unknown>, i: number) => ({\r\n id: String(r.id ?? `REQ-${i + 1}`),\r\n type: (['functional', 'non-functional', 'security', 'performance', 'ux']\r\n .includes(String(r.type)) ? String(r.type) : 'functional') as SpecRequirement['type'],\r\n priority: (['critical', 'high', 'medium', 'low']\r\n .includes(String(r.priority)) ? String(r.priority) : 'medium') as SpecRequirement['priority'],\r\n description: String(r.description ?? ''),\r\n acceptanceCriteria: Array.isArray(r.acceptanceCriteria)\r\n ? r.acceptanceCriteria.map(String)\r\n : [],\r\n }));\r\n\r\n const spec: Specification = {\r\n id: crypto.randomUUID(),\r\n title,\r\n version: '0.1.0',\r\n status: 'draft',\r\n overview,\r\n sections,\r\n requirements,\r\n createdAt: now,\r\n updatedAt: now,\r\n metadata: {\r\n generatedBy: 'AISpecBuilder',\r\n sessionId: this.session.id,\r\n },\r\n };\r\n\r\n return spec;\r\n }\r\n\r\n /**\r\n * Extract JSON from AI output (handles ```json blocks and raw JSON).\r\n */\r\n extractJSON(text: string): string | null {\r\n // Try ```json ... ``` first\r\n const codeBlockMatch = text.match(/```json\\s*([\\s\\S]*?)```/);\r\n if (codeBlockMatch?.[1]) {\r\n return codeBlockMatch[1].trim();\r\n }\r\n\r\n // Try ``` ... ``` without language tag\r\n const genericBlockMatch = text.match(/```\\s*([\\s\\S]*?)```/);\r\n if (genericBlockMatch?.[1]) {\r\n const trimmed = genericBlockMatch[1].trim();\r\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\r\n return trimmed;\r\n }\r\n }\r\n\r\n // Try raw JSON object\r\n const jsonMatch = text.match(/(\\{[\\s\\S]*\\})/);\r\n if (jsonMatch?.[1]) {\r\n try {\r\n JSON.parse(jsonMatch[1]);\r\n return jsonMatch[1];\r\n } catch {\r\n // not valid JSON\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Detect if AI output contains a spec (JSON block).\r\n */\r\n hasSpecInOutput(text: string): boolean {\r\n return this.extractJSON(text) !== null;\r\n }\r\n\r\n /**\r\n * Try to parse a spec from AI output text.\r\n * Returns null if no valid spec found.\r\n */\r\n tryParseSpecFromOutput(text: string): Specification | null {\r\n const json = this.extractJSON(text);\r\n if (!json) return null;\r\n\r\n try {\r\n return this.parseSpecFromJSON(json);\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n // ── JSON Array Extraction (for tasks) ─────────────────────────────────────\r\n\r\n /**\r\n * Extract a JSON array from AI output (for task lists).\r\n */\r\n extractJSONArray(text: string): string | null {\r\n const codeBlockMatch = text.match(/```json\\s*([\\s\\S]*?)```/);\r\n if (codeBlockMatch?.[1]) {\r\n const trimmed = codeBlockMatch[1].trim();\r\n if (trimmed.startsWith('[')) return trimmed;\r\n }\r\n\r\n const arrayMatch = text.match(/(\\[[\\s\\S]*\\])/);\r\n if (arrayMatch?.[1]) {\r\n try {\r\n const parsed = JSON.parse(arrayMatch[1]);\r\n if (Array.isArray(parsed)) return arrayMatch[1];\r\n } catch {\r\n // not valid\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n}\r\n","// SddInterviewDriver — a headless, REPL-free wrapper around AISpecBuilder that\n// drives the interactive Spec-Driven-Development interview (questioning → spec\n// → implementation plan → task graph) from any surface (WebUI, CLI, tests).\n//\n// The CLI `/sdd` slash command historically owned this loop via module-singleton\n// state (`sddState`) plus thin detection helpers in `packages/cli` — which the\n// WebUI cannot import (layer rule: webui ⇏ cli). This driver lifts the *pure*\n// logic into core so every surface shares one implementation: feed it the\n// agent's text output, it detects the spec / plan / task JSON, advances the\n// AISpecBuilder phases, and persists the resulting TaskGraph to disk so the run\n// machinery (SddParallelRun) can pick it up.\n//\n// The driver never runs the agent itself — the caller runs `agent.run(prompt)`\n// and feeds the output back via `ingestAgentOutput`. That keeps core free of any\n// agent-loop / provider coupling.\n\nimport type { Specification } from '../types/spec.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { AISpecBuilder, type AISpecPhase } from './spec-builder.js';\nimport type { SpecStore } from './spec-store.js';\nimport type { TaskGraphStore } from './task-graph-store.js';\nimport { TaskTracker } from './task-tracker.js';\nimport { DefaultTaskStore, TaskGenerator } from './task-generator.js';\nimport { buildBoardTasks, type SddBoardTask, type SddBoardColumn } from './board-types.js';\n\nexport interface SddInterviewDriverOptions {\n /** Disk-backed spec store (`wpaths.projectSpecs`). */\n specStore: SpecStore;\n /** Disk-backed task-graph store (`wpaths.projectTaskGraphs`). */\n graphStore: TaskGraphStore;\n /** Persist the interview session here so a reconnect can resume it. */\n sessionPath?: string | undefined;\n /** Project context string injected into the questioning prompt. */\n projectContext?: string | undefined;\n minQuestions?: number | undefined;\n maxQuestions?: number | undefined;\n}\n\n/** A serialisable view of the interview, streamed to observing surfaces. */\nexport interface SddInterviewSnapshot {\n sessionId: string;\n phase: AISpecPhase;\n title: string;\n questionCount: number;\n minQuestions: number;\n maxQuestions: number;\n answers: Array<{ question: string; answer: string }>;\n spec?:\n | {\n id: string;\n title: string;\n overview: string;\n requirements: Array<{ priority: string; description: string }>;\n }\n | undefined;\n graphId?: string | undefined;\n taskCount: number;\n /**\n * Topologically-laid-out task graph (once decomposed) — lets the wizard\n * render the same animated DAG as the live board (\"decomposition reveal\").\n */\n board?: { tasks: SddBoardTask[]; columns: SddBoardColumn[] } | undefined;\n /** The current AI prompt for this phase (what to send the agent next). */\n prompt: string;\n}\n\n/** What `ingestAgentOutput` detected and acted on. */\nexport interface SddIngestResult {\n specDetected: boolean;\n implementationDetected: boolean;\n tasksDetected: boolean;\n graphId?: string | undefined;\n}\n\nexport class SddInterviewDriver {\n readonly builder: AISpecBuilder;\n private readonly o: SddInterviewDriverOptions;\n private readonly minQuestions: number;\n private readonly maxQuestions: number;\n private tracker: TaskTracker | null = null;\n private graph: TaskGraph | null = null;\n\n constructor(opts: SddInterviewDriverOptions) {\n this.o = opts;\n this.minQuestions = opts.minQuestions ?? 2;\n this.maxQuestions = opts.maxQuestions ?? 10;\n this.builder = new AISpecBuilder({\n store: opts.specStore,\n sessionPath: opts.sessionPath,\n projectContext: opts.projectContext,\n minQuestions: this.minQuestions,\n maxQuestions: this.maxQuestions,\n });\n }\n\n /** Begin a fresh interview. Returns the first AI prompt (a question kickoff). */\n start(title: string, intent?: string): string {\n this.builder.startSession(title, intent);\n this.tracker = null;\n this.graph = null;\n return this.builder.getAIPrompt();\n }\n\n /**\n * Resume a previously-persisted interview from disk. Re-hydrates the task\n * graph too when one was already produced. Returns true if a session loaded.\n */\n async loadExisting(): Promise<boolean> {\n const loaded = await this.builder.loadSession();\n if (!loaded) return false;\n const graphId = this.builder.getTaskGraphId();\n if (graphId) {\n const graph = await this.o.graphStore.load(graphId);\n if (graph) {\n this.graph = graph;\n const tracker = new TaskTracker({ store: new DefaultTaskStore() });\n tracker.setGraph(graph);\n this.tracker = tracker;\n }\n }\n return true;\n }\n\n phase(): AISpecPhase {\n return this.builder.getPhase();\n }\n\n currentPrompt(): string {\n return this.builder.getAIPrompt();\n }\n\n getTracker(): TaskTracker | null {\n return this.tracker;\n }\n\n getGraph(): TaskGraph | null {\n return this.graph;\n }\n\n /** Record a Q/A pair (the agent asked `question`, the user replied `answer`). */\n submitAnswer(question: string, answer: string): void {\n this.builder.addAnswer(question, answer);\n }\n\n /**\n * Feed the agent's text output back into the interview. Detects, in order:\n * 1. a Specification JSON → setSpec (phase → spec_review) + persist to SpecStore\n * 2. an implementation plan (implementation phase) → setImplementation\n * 3. a task JSON array → build + persist a TaskGraph\n * Each step is independent and best-effort; a malformed payload is ignored\n * rather than thrown, so a chatty agent turn never breaks the interview.\n */\n async ingestAgentOutput(text: string): Promise<SddIngestResult> {\n const result: SddIngestResult = {\n specDetected: false,\n implementationDetected: false,\n tasksDetected: false,\n };\n\n // 1. Spec JSON → spec_review.\n if (!this.builder.getSession().spec) {\n const spec = this.builder.tryParseSpecFromOutput(text);\n if (spec) {\n this.builder.setSpec(spec);\n await this.persistSpec(spec);\n result.specDetected = true;\n }\n }\n\n // 2. Implementation plan (only meaningful in the implementation phase).\n if (this.builder.getPhase() === 'implementation') {\n if (this.trySaveImplementationPlan(text)) result.implementationDetected = true;\n }\n\n // 3. Task JSON array → TaskGraph (requires a spec to anchor the graph).\n const session = this.builder.getSession();\n if (session.spec) {\n const built = await this.tryBuildTasksFromOutput(text);\n if (built) {\n result.tasksDetected = true;\n result.graphId = built;\n }\n }\n\n return result;\n }\n\n /**\n * Advance to the next phase (mirrors `/sdd approve`). When moving into the\n * executing phase, guarantees a task graph exists — deterministically\n * generating one from the approved spec if the agent never emitted a valid\n * task array. Returns the new phase and its AI prompt.\n */\n async approve(): Promise<{ phase: AISpecPhase; prompt: string }> {\n const phase = this.builder.approve();\n if (phase === 'executing') {\n await this.ensureTaskGraph();\n }\n return { phase, prompt: this.builder.getAIPrompt() };\n }\n\n /**\n * Ensure a TaskGraph exists for the approved spec. If the agent already\n * produced one (via `ingestAgentOutput`), returns it; otherwise builds a\n * deterministic graph from the spec's requirements via TaskGenerator. This is\n * the robustness backstop: a run can always start, even if the model never\n * emitted a parseable task array.\n */\n async ensureTaskGraph(): Promise<TaskGraph | null> {\n if (this.graph) return this.graph;\n const spec = this.builder.getSession().spec;\n if (!spec) return null;\n\n const tracker = new TaskTracker({ store: new DefaultTaskStore() });\n const generator = new TaskGenerator({\n taskTracker: tracker,\n verificationFromAcceptance: process.env['WRONGSTACK_SDD_VERIFY_FROM_ACCEPTANCE'] === '1',\n });\n const graph = await generator.generateFromSpec(spec);\n this.tracker = tracker;\n this.graph = graph;\n await this.persistGraph(graph);\n this.builder.setTaskGraphId(graph.id);\n // Flush the session synchronously so a reconnect (loadExisting) sees the\n // graphId — setTaskGraphId's own auto-save is fire-and-forget.\n await this.builder.saveSession();\n return graph;\n }\n\n snapshot(): SddInterviewSnapshot {\n const s = this.builder.getSession();\n const spec = s.spec;\n return {\n sessionId: s.id,\n phase: s.phase,\n title: s.title,\n questionCount: s.questionCount,\n minQuestions: this.minQuestions,\n maxQuestions: this.maxQuestions,\n answers: s.answers.map((a) => ({ question: a.question, answer: a.answer })),\n spec: spec\n ? {\n id: spec.id,\n title: spec.title,\n overview: spec.overview,\n requirements: spec.requirements.map((r) => ({\n priority: r.priority,\n description: r.description,\n })),\n }\n : undefined,\n graphId: s.taskGraphId,\n taskCount: this.graph ? this.graph.nodes.size : 0,\n board: this.graph ? buildBoardTasks(this.graph) : undefined,\n prompt: this.builder.getAIPrompt(),\n };\n }\n\n // ── internals ────────────────────────────────────────────────────────────\n\n private async persistSpec(spec: Specification): Promise<void> {\n try {\n await this.o.specStore.save(spec);\n } catch {\n // best-effort — the in-memory session still has the spec\n }\n }\n\n private async persistGraph(graph: TaskGraph): Promise<void> {\n try {\n await this.o.graphStore.save(graph);\n } catch {\n // best-effort — the in-memory tracker still drives the run\n }\n }\n\n /**\n * Port of the CLI `trySaveImplementationPlan` operating on this driver's\n * builder. Captures the prose plan that precedes the task JSON block.\n */\n private trySaveImplementationPlan(text: string): boolean {\n const current = this.builder.getSession().implementation ?? '';\n const jsonStart = text.match(/```json\\s*\\[/);\n if (jsonStart?.index && jsonStart.index > 0) {\n const plan = text.substring(0, jsonStart.index).trim();\n if (plan.length > 50 && plan !== current && !isExplanatoryText(plan)) {\n this.builder.setImplementation(plan);\n return true;\n }\n }\n if (\n text.length > 100 &&\n !text.includes('```json') &&\n text.trim() !== current &&\n !isExplanatoryText(text)\n ) {\n this.builder.setImplementation(text.trim());\n return true;\n }\n return false;\n }\n\n /**\n * Port of the CLI `trySaveTasksFromAIOutput`: parse a task JSON array from the\n * agent output, build (or extend) the tracker + graph, persist to disk, and\n * link the graphId to the session. Returns the graphId on success.\n */\n private async tryBuildTasksFromOutput(text: string): Promise<string | undefined> {\n const json = this.builder.extractJSONArray(text);\n if (!json) return undefined;\n\n let tasks: Array<Record<string, unknown>>;\n try {\n tasks = JSON.parse(json) as Array<Record<string, unknown>>;\n } catch {\n return undefined;\n }\n const valid = tasks.filter(\n (t) => t && typeof t === 'object' && typeof t.title === 'string' && t.title.length > 0,\n );\n if (valid.length === 0) return undefined;\n\n const spec = this.builder.getSession().spec;\n if (!spec) return undefined;\n\n if (!this.tracker || !this.graph) {\n const tracker = new TaskTracker({ store: new DefaultTaskStore() });\n this.graph = await tracker.createGraph(spec.id, spec.title);\n this.tracker = tracker;\n }\n // Two passes: (1) create every node, recording every reference key by which\n // a `dependsOn` entry might name it (declared id, positional `t1`/`1`, title);\n // (2) resolve each task's `dependsOn` refs into real `depends_on` edges. This\n // is what turns a flat task list into a true dependency DAG — the scheduler\n // then runs independent tasks in parallel and dependent ones in order.\n const refMap = new Map<string, string>();\n const created: Array<{ nodeId: string; task: Record<string, unknown> }> = [];\n valid.forEach((task, i) => {\n const node = addTaskToTracker(this.tracker!, task);\n created.push({ nodeId: node.id, task });\n if (typeof task.id === 'string' && task.id.trim()) {\n refMap.set(task.id.trim().toLowerCase(), node.id);\n }\n refMap.set(`t${i + 1}`, node.id);\n refMap.set(String(i + 1), node.id);\n refMap.set(normalizeTaskRef(String(task.title)), node.id);\n });\n for (const { nodeId, task } of created) {\n const deps = Array.isArray(task.dependsOn) ? task.dependsOn : [];\n for (const ref of deps) {\n const depId = refMap.get(normalizeTaskRef(String(ref)));\n // addDependency self/duplicate/cycle-guards; a stale ref just no-ops.\n if (depId && depId !== nodeId) this.tracker!.addDependency(depId, nodeId);\n }\n }\n await this.persistGraph(this.graph);\n this.builder.setTaskGraphId(this.graph.id);\n // Flush so a reconnect resumes with the graph linked (see ensureTaskGraph).\n await this.builder.saveSession();\n return this.graph.id;\n }\n}\n\nconst TASK_TYPES = ['feature', 'bugfix', 'refactor', 'docs', 'test', 'chore'] as const;\nconst TASK_PRIORITIES = ['critical', 'high', 'medium', 'low'] as const;\n\n/** Normalize a dependsOn reference (id / positional / title) for map lookup. */\nfunction normalizeTaskRef(ref: string): string {\n return ref.trim().toLowerCase();\n}\n\nfunction addTaskToTracker(tracker: TaskTracker, task: Record<string, unknown>): TaskNode {\n return tracker.addNode({\n title: String(task.title),\n description: String(task.description ?? ''),\n type: (TASK_TYPES as readonly string[]).includes(String(task.type))\n ? (String(task.type) as (typeof TASK_TYPES)[number])\n : 'feature',\n priority: (TASK_PRIORITIES as readonly string[]).includes(String(task.priority))\n ? (String(task.priority) as (typeof TASK_PRIORITIES)[number])\n : 'medium',\n status: 'pending',\n estimateHours: Number(task.estimateHours) || 2,\n tags: Array.isArray(task.tags) ? task.tags.map(String) : [],\n });\n}\n\n/**\n * True when the text reads like conversational filler rather than a structured\n * implementation plan. Ported verbatim from the CLI detection so behaviour is\n * identical across surfaces.\n */\nexport function isExplanatoryText(text: string): boolean {\n const lower = text.toLowerCase();\n return (\n lower.startsWith(\"i'\") ||\n lower.startsWith('i will') ||\n lower.startsWith('let me') ||\n lower.startsWith(\"here's my\") ||\n lower.startsWith('here is my') ||\n lower.startsWith(\"i'm going to\") ||\n lower.startsWith('first, let me') ||\n lower.startsWith('sure') ||\n lower.startsWith('of course') ||\n lower.startsWith('okay') ||\n lower.startsWith('ok,') ||\n lower.startsWith('sounds good') ||\n lower.startsWith('no problem') ||\n (text.split('\\n').length < 3 && !text.includes('.'))\n );\n}\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\n/**\n * Fraction of the wall-clock `timeoutMs` window at which a PROACTIVE extension\n * is negotiated — BEFORE the deadline is actually crossed. The coordinator\n * watchdog (`executeWithTimeout`) arms at `timeoutMs * TIMEOUT_PREEMPT_FRACTION`\n * so a still-progressing subagent gets its ceiling raised while it is below the\n * limit, and never enters a \"timed out\" state. Reactive enforcement at the real\n * deadline still stands for the no-progress / denied case. Shared so the asking\n * side and any future caller agree on the same lead point.\n */\nexport const TIMEOUT_PREEMPT_FRACTION = 0.85;\n\n/**\n * Hard safety net for budget negotiation decisions. If no listener responds to\n * `budget.threshold_reached` within this window the negotiation defaults to\n * `'stop'`. Exported so the coordinator's watchdog can reuse the same ceiling\n * without hardcoding a second copy.\n */\nexport const DECISION_TIMEOUT_MS = 60_000;\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number | undefined;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number | undefined;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number | undefined;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n /**\n * Direct grant/deny hooks for SYNCHRONOUS policy or recording handlers that\n * decide in-process without a wired `budget.threshold_reached` listener\n * (e.g. the coordinator watchdog). `extend` patches the limits in place;\n * `deny` records the intent to stop. Production listener-driven handlers use\n * `requestDecision()` instead and can ignore these.\n */\n extend?: (extra: Partial<BudgetLimits>) => void;\n deny?: () => void;\n}) => 'throw' | 'continue' | 'stop' | { extend: Partial<BudgetLimits> } | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n\n /** Patch one or more budget limits in-place after construction.\n * Used by the coordinator watchdog when granting an extension.\n * All fields are optional — only provided fields are updated.\n * This is the single write path for limit mutations so that future\n * validation or side-effects live in one place (M1). */\n patchLimits(ext: Partial<BudgetLimits>): void {\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n }\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = DECISION_TIMEOUT_MS;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus | undefined;\n\n /**\n * Guard against dual-path races between the coordinator watchdog\n * (`executeWithTimeout`) and the budget's own `checkTimeout()`.\n * Both paths detect `elapsed >= timeoutMs` and can emit\n * `budget.threshold_reached` for kind `'timeout'` simultaneously.\n * Set to the current `timeoutMs` ceiling by the coordinator BEFORE\n * calling `onThreshold`, and cleared after the negotiation resolves.\n * `checkTimeout()` skips its wall-clock check while this is set so\n * the coordinator's watchdog is the sole source of wall-clock timeout\n * events — `checkTimeout()` focuses exclusively on `idle_timeout`.\n */\n private _watchdogActive: number | undefined;\n\n /** Returns the timeout ceiling currently being negotiated by the watchdog,\n * or `undefined` when no wall-clock negotiation is in flight.\n * Used by `executeWithTimeout` to detect a stale lock (M3). */\n get watchdogActive(): number | undefined { return this._watchdogActive; }\n\n /** Called by the coordinator watchdog BEFORE calling `onThreshold` so that\n * `checkTimeout()` skips its wall-clock check for this ceiling. Prevents\n * the budget's own `checkTimeout()` from emitting a second\n * `budget.threshold_reached` event while the watchdog is already\n * negotiating the same wall-clock deadline (C1). */\n setWatchdogNegotiation(timeoutMs: number): void { this._watchdogActive = timeoutMs; }\n\n /** Clears the watchdog guard after negotiation resolves. Called in the\n * `finally` block of both the pre-empt and deadline branches so it fires\n * on every exit path: grant, deny, throw, or error. */\n clearWatchdogNegotiation(): void { this._watchdogActive = undefined; }\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n // Skip the wall-clock 'timeout' kind while the coordinator watchdog is\n // negotiating this exact ceiling — it owns wall-clock; checkTimeout/here\n // own idle. Only suppress in the negotiation path (a handler is set); on\n // the no-handler hard-throw path the wall-clock must still trip. (Mirrors\n // the guard in checkTimeout, which previously was NOT applied here — so\n // an idle trip that called checkLimits re-added 'timeout' and defeated the\n // watchdog dedup.)\n const wallOwnedByWatchdog =\n this._onThreshold !== undefined && this._watchdogActive === this.limits.timeoutMs;\n if (\n this.limits.timeoutMs !== undefined &&\n elapsedMs > this.limits.timeoutMs &&\n !wallOwnedByWatchdog\n ) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus) {\n // No EventBus wired at all → nobody to negotiate with → hard stop.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n\n // LISTENER-DRIVEN PATH. A registered `budget.threshold_reached` listener\n // (director / collab / auto-extend) negotiates asynchronously. Start one\n // negotiation PER exceeded kind — each reports its OWN kind/used/limit and\n // emits a single event (no O(N^2) re-emission, no cross-kind first-wins\n // drop). Throw `BudgetThresholdSignal` for the first kind so the runner\n // awaits the decision and enforces extend/stop.\n if (bus.hasListenerFor('budget.threshold_reached')) {\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n this._pendingNegotiations.set(entry.kind, this._negotiateExtension(entry));\n }\n const decision = this._pendingNegotiations.get(first.kind);\n if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n // NO-LISTENER PATH. Invoke the handler synchronously to let an in-process\n // policy decide. Two outcomes:\n // • SYNC handler (returns a string/decision — e.g. the coordinator\n // watchdog / recording handlers) → its decision is honored in place\n // (an `extend` patches limits); no throw. This is the path the\n // watchdog drives while it owns wall-clock enforcement.\n // • ASYNC handler (returns a Promise via `requestDecision()`) → there is\n // no listener to resolve it and `requestDecision` resolves to 'stop',\n // so this is a definite hard stop: throw `BudgetExceededError`. This is\n // the documented \"auto mode + no listener → hard stop\" invariant that\n // protects a bare `/spawn` (no director) from a runaway subagent.\n let hardStop: BudgetExceededError | null = null;\n for (const entry of exceeded) {\n // Dedup per kind across back-to-back overruns in the same tick — a still\n // exceeded kind (e.g. iterations stays over after a grant) must not\n // re-invoke the handler on every record* call. The marker clears on a\n // microtask so a genuinely fresh overrun later can re-negotiate.\n if (this._pendingNegotiations.has(entry.kind)) continue;\n const marker = Promise.resolve<BudgetThresholdDecision>('stop');\n this._pendingNegotiations.set(entry.kind, marker);\n void marker.finally(() => this._pendingNegotiations.delete(entry.kind));\n const sync = this._invokeHandlerSync(entry);\n if (!sync) hardStop ??= new BudgetExceededError(entry.kind, entry.limit, entry.used);\n }\n if (hardStop) throw hardStop;\n return exceeded;\n }\n\n /**\n * Invoke `onThreshold` once for `entry` on the NO-LISTENER path and report\n * whether it decided synchronously. Returns `true` when the handler returned\n * a synchronous decision (already honored — an `extend` patched the limits),\n * or `false` when it returned a Promise (async; the caller hard-stops, since\n * there is no listener to resolve the negotiation). The handler is given the\n * full info shape (`requestDecision` plus direct `extend`/`deny`) so both\n * recording handlers and policy handlers work without a wired listener.\n */\n private _invokeHandlerSync(entry: { kind: BudgetKind; used: number; limit: number }): boolean {\n const handler = this._onThreshold;\n if (!handler) return false;\n let extendArg: Partial<BudgetLimits> | undefined;\n const result = handler({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n // Direct hooks for synchronous policy/recording handlers.\n extend: (extra: Partial<BudgetLimits>) => {\n extendArg = extra;\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n // A thenable means the handler deferred to async negotiation — but there is\n // no listener here, so it can never be granted → hard stop.\n if (result && typeof (result as { then?: unknown }).then === 'function') return false;\n if (result === 'throw') return false; // explicit hard stop\n // 'continue' / 'stop' / a returned { extend } decision — honor in place.\n if (result && typeof result === 'object' && 'extend' in result) {\n extendArg = (result as { extend: Partial<BudgetLimits> }).extend;\n }\n if (extendArg) this.patchLimits(extendArg);\n return true;\n }\n\n /**\n * Emit `budget.threshold_reached` and resolve to the listener's verdict.\n * Resolves to `'stop'` immediately when there is no listener (or no bus) so\n * no negotiation can hang and no fallback timer leaks. Mirrors the\n * coordinator watchdog's own request path so both agree on the no-listener\n * default.\n */\n private _busRequestDecision(entry: {\n kind: BudgetKind;\n used: number;\n limit: number;\n }): Promise<BudgetThresholdDecision> {\n const bus = this._events;\n if (!bus?.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n clearTimeout(fallback);\n resolve(d);\n };\n const fallback = setTimeout(() => respond('stop'), SubagentBudget.DECISION_TIMEOUT_MS);\n bus.emit('budget.threshold_reached', {\n kind: entry.kind as\n | 'iterations'\n | 'tool_calls'\n | 'tokens'\n | 'cost'\n | 'timeout'\n | 'idle_timeout',\n used: entry.used,\n limit: entry.limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n // deny() wins over a same-dispatch extend(): a listener that both grants\n // and denies (or two listeners disagreeing) is resolved as a stop. The\n // grant is deferred a microtask so a synchronous deny in the same emit\n // pre-empts it; async grants still resolve normally.\n extend: (extra: Partial<BudgetLimits>) => queueMicrotask(() => respond({ extend: extra })),\n deny: () => respond('stop'),\n });\n });\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n entry: { kind: BudgetKind; used: number; limit: number },\n ): Promise<BudgetThresholdDecision> {\n if (!this._onThreshold) {\n // Should never reach here — caller should have thrown already\n return 'stop';\n }\n try {\n const result = this._onThreshold({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n // One event for THIS kind only — each exceeded kind has its own\n // negotiation (and its own resolve), so there is no cross-kind\n // first-wins drop and no O(N^2) re-emission.\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n extend: (extra: Partial<BudgetLimits>) => {\n this.patchLimits(extra);\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving (single write path).\n this.patchLimits(decision.extend);\n return decision;\n } finally {\n this._pendingNegotiations.delete(entry.kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock / idle budget check. Delegates to `checkLimits(elapsed)`, so\n * `timeout` and `idle_timeout` follow the SAME negotiation path as the other\n * kinds — they are NOT a special-cased hard stop. This is deliberate: a\n * heartbeat-aware policy (see `attachAutoExtend` and `CollabSession`) grants\n * a timeout extension only while the agent is making progress and denies it\n * once the agent is genuinely stuck, which is safer than an unconditional\n * hard kill of a long-but-working agent. The runner translates the resulting\n * `BudgetThresholdSignal` decision (`extend` → patch limits in place,\n * `stop` → abort) just like every other kind.\n *\n * Decision table (same as `checkLimits`):\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` (negotiated;\n * a heartbeat-aware policy may extend the timeout)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n // Skip wall-clock timeout if the coordinator watchdog is already in the middle\n // of negotiating this exact ceiling — tool.progress is too frequent and creates\n // a race where both paths emit budget.threshold_reached for the same kind.\n // The watchdog owns wall-clock; checkTimeout focuses exclusively on idle.\n const wallSkipped =\n this._onThreshold !== undefined &&\n this._watchdogActive !== undefined &&\n timeoutMs !== undefined &&\n this._watchdogActive === timeoutMs;\n const wallTripped = wallSkipped ? false : timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\n/**\n * Wrap a factory to automatically filter out disabled tools from subagent\n * configurations. This provides mechanical enforcement of tool restrictions\n * (e.g., preventing delegation) in addition to the baseline prompt constraint.\n *\n * The wrapper reads `config.disabledTools` and removes those tools from the\n * agent's tool registry before returning.\n *\n * Usage:\n * const filteredFactory = withDisabledToolFiltering(originalFactory);\n * const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n */\nexport function withDisabledToolFiltering(factory: AgentFactory): AgentFactory {\n return async (config: SubagentConfig) => {\n const result = await factory(config);\n const disabled = config.disabledTools ?? [];\n if (disabled.length === 0) return result;\n\n // Agent.tools is a ToolRegistry with unregister() method\n const registry = result.agent.tools;\n if (registry && typeof registry.unregister === 'function') {\n for (const toolName of disabled) {\n registry.unregister(toolName);\n }\n }\n return result;\n };\n}\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: ((() => Promise<void> | void)) | undefined;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus | undefined;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const taskStartedAt = Date.now();\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Defer the stop/extend decision to the post-finally block below.\n // The coordinator's verdict may arrive after agent.run() returns;\n // awaiting it there (rather than in this fire-and-forget handler)\n // avoids a race where both this callback and the post-finally\n // block try to mutate `budgetError` concurrently.\n budgetError = err;\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~2000 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-2000);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n // Emit task_completed BEFORE the finally block unsubscribes the\n // FleetBus — this lets the WebUI see the subagent's final output.\n events.emit('subagent.task_completed', {\n subagentId: ctx.subagentId,\n taskId: task.id,\n status: result.status === 'done' ? 'success' : 'failed',\n iterations: result.iterations,\n toolCalls: ctx.budget.usage().toolCalls,\n durationMs: Date.now() - taskStartedAt,\n finalText: result.finalText?.trim() || undefined,\n });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n try {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n } catch {\n // Decision promise rejected — treat as hard stop.\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof AgentError\n ? result.error\n : new AgentError({\n message: result.error instanceof Error ? result.error.message : String(result.error ?? 'agent failed'),\n code: ERROR_CODES.AGENT_RUN_FAILED,\n cause: result.error,\n });\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new AgentError({\n message: 'agent aborted',\n code: ERROR_CODES.AGENT_ABORTED,\n });\n }\n if (result.status === 'max_iterations') {\n throw new AgentError({\n message: 'agent exhausted iteration limit',\n code: ERROR_CODES.AGENT_ITERATION_LIMIT,\n recoverable: true,\n });\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new AgentError({\n message: 'empty response — agent produced no text and no tool calls',\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { iterations: result.iterations },\n });\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new AgentError({\n message: `unrecovered tool failure: ${lastToolFailed} — agent ended turn without acknowledging the error`,\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { tool: lastToolFailed, iterations: result.iterations },\n });\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\nimport { truncate } from '../utils/string.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\nexport type CacheTtl = '5m' | '1h';\n\n/**\n * Provider-agnostic response-format directive.\n *\n * - `{ type: 'text' }` — free-form text (default).\n * - `{ type: 'json_object' }` — valid JSON without a schema constraint.\n * - `{ type: 'json_schema', jsonSchema: { name, schema, strict? } }` — JSON\n * constrained to the supplied JSON Schema. The `strict` flag is\n * OpenAI-specific; Gemini ignores it in favour of `responseMimeType`.\n *\n * Each provider adapter maps this into its own wire format:\n * OpenAI → `response_format`\n * Gemini → `responseMimeType` + `responseSchema`\n * Anthropic → (not yet supported; uses tools for structured output)\n */\nexport interface JsonSchemaSpec {\n name: string;\n /** OpenAI-specific: enable strict schema adherence. */\n strict?: boolean | undefined;\n /** The JSON Schema object describing the expected shape. */\n schema: Record<string, unknown>;\n /** Optional human-readable description (OpenAI). */\n description?: string | undefined;\n}\n\nexport type ResponseFormat =\n | { type: 'text' }\n | { type: 'json_object' }\n | { type: 'json_schema'; jsonSchema: JsonSchemaSpec };\n\n/**\n * Safety category threshold pair used by Google Gemini's `safetySettings`.\n *\n * Categories: `HARM_CATEGORY_HARASSMENT`, `HARM_CATEGORY_HATE_SPEECH`,\n * `HARM_CATEGORY_SEXUALLY_EXPLICIT`, `HARM_CATEGORY_DANGEROUS_CONTENT`.\n *\n * Thresholds: `BLOCK_NONE`, `BLOCK_ONLY_HIGH`, `BLOCK_MEDIUM_AND_ABOVE`,\n * `BLOCK_LOW_AND_ABOVE`.\n */\nexport interface SafetySetting {\n category: string;\n threshold: string;\n}\n\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number | undefined;\n /** Back-compat aggregate of all cache-write tokens. Prefer TTL-specific fields when present. */\n cacheWrite?: number | undefined;\n cacheWrite5m?: number | undefined;\n cacheWrite1h?: number | undefined;\n}\n\nexport interface ReasoningRequest {\n enabled?: boolean | undefined;\n effort?: ReasoningEffort | undefined;\n preserve?: boolean | undefined;\n display?: 'summarized' | 'omitted' | undefined;\n}\n\nexport interface RequestCacheControl {\n ttl?: CacheTtl | undefined;\n}\n\nexport interface ReasoningConfig {\n default: 'enabled' | 'disabled' | 'adaptive' | 'always_on';\n disableSupported: boolean;\n effortSupported: boolean;\n effortLevels: ReasoningEffort[];\n preserveThinking: 'unsupported' | 'optional' | 'always_on';\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n\n // ── Extended parameter support (optional; family defaults in CAPABILITIES_BY_FAMILY) ──\n\n /** Model accepts `top_k` / `topK` sampling parameter. */\n topK?: boolean | undefined;\n /** Model accepts `frequency_penalty` / `frequencyPenalty` parameter. */\n frequencyPenalty?: boolean | undefined;\n /** Model accepts `presence_penalty` / `presencePenalty` parameter. */\n presencePenalty?: boolean | undefined;\n /** Model accepts `seed` parameter for deterministic generation. */\n seed?: boolean | undefined;\n /**\n * Model accepts JSON Schema / structured-output constraints\n * (OpenAI `response_format.json_schema`, Gemini `responseMimeType`+`responseSchema`).\n * Distinct from `jsonMode` (which is just a system-prompt hint).\n */\n structuredOutput?: boolean | undefined;\n /** Model supports log-probability output (`logprobs`, `top_logprobs`). */\n logprobs?: boolean | undefined;\n /** Model supports audio input/output modality. */\n audio?: boolean | undefined;\n /** Model supports the `n` parameter for multiple completions. */\n multipleCompletions?: boolean | undefined;\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[] | undefined;\n messages: Message[];\n tools?: Tool[] | undefined;\n maxTokens: number;\n temperature?: number | undefined;\n topP?: number | undefined;\n topK?: number | undefined;\n frequencyPenalty?: number | undefined;\n presencePenalty?: number | undefined;\n seed?: number | undefined;\n /**\n * End-user identifier for abuse monitoring and per-user rate limiting.\n * - Anthropic → `metadata.user_id`\n * - OpenAI → `user`\n * - Gemini → (not supported)\n */\n user?: string | undefined;\n /**\n * Number of response candidates to generate. Google Gemini supports\n * this via `generationConfig.candidateCount`. OpenAI does not have\n * an equivalent (`n` is conceptually similar but distinct).\n */\n candidateCount?: number | undefined;\n /**\n * Whether to return log probabilities for output tokens.\n * - OpenAI → `logprobs: boolean` (+ `topLogprobs: number`)\n * - Gemini → `generationConfig.logprobs: number` (how many top candidates)\n * Default undefined = no logprobs requested.\n */\n logprobs?: boolean | undefined;\n /**\n * Number of most probable tokens to return log probabilities for\n * (OpenAI `top_logprobs`). Only meaningful when `logprobs` is true.\n * Range: 0-20. Gemini ignores this (uses `logprobs` as the count).\n */\n topLogprobs?: number | undefined;\n stopSequences?: string[] | undefined;\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool' | undefined; name: string };\n reasoning?: ReasoningRequest | undefined;\n cache?: RequestCacheControl | undefined;\n /**\n * Structured-output / response-format directive.\n * When set, the provider adapter maps this to its native response-format\n * parameter (OpenAI `response_format`, Gemini `responseMimeType`, etc.).\n * The model must advertise `capabilities.structuredOutput` for this to be\n * honoured; unsupported models will likely 400 or ignore it.\n */\n responseFormat?: ResponseFormat | undefined;\n /**\n * Safety category thresholds for filtering harmful content.\n * - Gemini → top-level `safetySettings` array with `{ category, threshold }`\n * - OpenAI → not supported (uses server-side moderation)\n * - Anthropic → not supported\n */\n safetySettings?: SafetySetting[] | undefined;\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string | undefined;\n name?: string | undefined;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string | undefined;\n /** Human-readable explanation from the provider. */\n message?: string | undefined;\n /** Provider request id, when present in the body or headers. */\n requestId?: string | undefined;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number | undefined;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string | undefined;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean | undefined;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number | undefined;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody | undefined;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody | undefined; cause?: unknown | undefined } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\n/**\n * Thrown when the provider stream stops delivering data mid-response.\n * This is distinct from a network error (TCP reset, DNS failure) — the\n * connection is established and the response started, but chunks stopped\n * arriving before the stream completed.\n *\n * Status 599 is used as a sentinel to distinguish stream hangs from\n * regular HTTP errors while still flowing through ProviderError-based\n * retry and fallback infrastructure.\n */\nexport class StreamHangError extends ProviderError {\n /** Name of the provider that hung, e.g. \"zai\", \"anthropic\". */\n public readonly hungProviderId: string;\n /** Model that was being called when the hang occurred. */\n public readonly hungModel: string;\n /** How long (ms) we waited for the next chunk before declaring a hang. */\n public readonly hangTimeoutMs: number;\n /** How many bytes were received before the hang. */\n public readonly bytesReceived: number;\n /** Elapsed time (ms) from the start of the stream until the hang. */\n public readonly elapsedMs: number;\n\n constructor(opts: {\n providerId: string;\n model: string;\n hangTimeoutMs: number;\n bytesReceived: number;\n elapsedMs: number;\n cause?: unknown | undefined;\n }) {\n super(\n `Stream hang: ${opts.providerId}/${opts.model} — no data for ${opts.hangTimeoutMs}ms after ${opts.bytesReceived} bytes (${opts.elapsedMs}ms elapsed)`,\n 599,\n true, // always retryable\n opts.providerId,\n {\n body: {\n message: `Stream stalled after ${opts.elapsedMs}ms, ${opts.bytesReceived} bytes received`,\n },\n cause: opts.cause,\n },\n );\n this.name = 'StreamHangError';\n this.hungProviderId = opts.providerId;\n this.hungModel = opts.model;\n this.hangTimeoutMs = opts.hangTimeoutMs;\n this.bytesReceived = opts.bytesReceived;\n this.elapsedMs = opts.elapsedMs;\n }\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { SubagentError, SubagentErrorKind } from '../../types/multi-agent.js';\nimport { ProviderError } from '../../types/provider.js';\nimport { AgentError } from '../../types/errors.js';\nimport { BudgetExceededError } from '../subagent-budget.js';\nimport { toErrorMessage } from '../../utils/error.js';\n\n/**\n * Map any raw exception thrown out of a subagent's runner into a\n * structured `SubagentError`. This is the single point where the\n * coordinator decides \"what kind of failure was that\" — so callers\n * (delegate tool output, /agents UI, retry policies) branch on\n * `kind` instead of substring-matching `error.message`.\n *\n * Exported because tests and CLI surfaces want to assert on the\n * classification without instantiating a coordinator.\n */\nexport function classifySubagentError(\n err: unknown,\n hints: { parentAborted?: boolean | undefined } = {},\n): SubagentError {\n // Unwrap AgentError wrappers — the runner wraps non-AgentError\n // throwables (ProviderError, TypeError, etc.) in AgentError so the\n // coordinator's try/catch catches a consistent type. Recurse into the\n // inner cause so classification sees the original error kind.\n if (err instanceof AgentError && err.cause) {\n return classifySubagentError(err.cause, hints);\n }\n\n const cause = err instanceof Error\n ? { name: err.name, message: err.message, stack: err.stack }\n : undefined;\n\n if (err instanceof ProviderError) {\n const baseMessage = err.describe();\n return providerErrorToSubagentError(err, baseMessage, cause);\n }\n\n const baseMessage = toErrorMessage(err);\n\n if (err instanceof BudgetExceededError) {\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\n iterations: 'budget_iterations',\n tool_calls: 'budget_tool_calls',\n tokens: 'budget_tokens',\n cost: 'budget_cost',\n timeout: 'budget_timeout',\n idle_timeout: 'budget_timeout',\n };\n return {\n kind: map[err.kind],\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n\n if (hints.parentAborted) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n\n const lower = baseMessage.toLowerCase();\n if (/agent aborted$/i.test(baseMessage)) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\n }\n if (/empty response/i.test(baseMessage)) {\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\n }\n if (/^tool failed: /i.test(baseMessage)) {\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\n }\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\n }\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\n }\n\n return { kind: 'unknown', message: baseMessage, retryable: false, cause };\n}\n\nfunction providerErrorToSubagentError(\n err: ProviderError,\n message: string,\n cause: SubagentError['cause'],\n): SubagentError {\n const status = err.status;\n if (status === 429 || err.body?.type === 'rate_limit_error') {\n return { kind: 'provider_rate_limit', message, retryable: true, backoffMs: 5_000, cause };\n }\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\n return { kind: 'provider_auth', message, retryable: false, cause };\n }\n if (status === 408 || status === 0) {\n return { kind: 'provider_timeout', message, retryable: true, cause };\n }\n if (status >= 500 && status < 600) {\n return { kind: 'provider_5xx', message, retryable: true, backoffMs: 3_000, cause };\n }\n return { kind: 'unknown', message, retryable: err.retryable, cause };\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number | undefined;\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n maxCostUsd?: number | undefined;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree', 'mailbox'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit', 'mailbox'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch', 'mailbox'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n 'mailbox',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json', 'mailbox'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document', 'mailbox'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch', 'mailbox'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n {\n config: {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n tools: [...PLAN_TOOLS, 'diff'],\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan with phases (Low Risk / Medium Risk / High Risk),\ndependency graph, rollback strategy, and exit criteria.\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Refactoring planner: analyzes code structure, maps dependencies, produces risk-scored phased plans with rollback strategy.',\n keywords: [\n 'refactor',\n 'refactoring',\n 'restructure',\n 'debt',\n 'technical debt',\n 'clean up',\n 'modularize',\n 'decouple',\n 'dependency graph',\n 'code structure',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [\n ...TOOLS.build,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Use Playwright browser tools (navigate, click, type, screenshot, evaluate)\n to automate web UI flows — open pages, interact with forms, capture evidence\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs, page HTML)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (screenshots, page HTML, logs) for reproduction\n- Keep scenarios independent so one failure doesn't cascade\n- For browser tests: playwright_navigate first, then interact, then playwright_screenshot as evidence\n- If playwright tools are unavailable, report it and fall back to API/CLI testing`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'browser',\n 'screenshot',\n 'web ui',\n 'headless',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n 'navigate',\n 'click',\n 'form fill',\n 'dom',\n 'page load',\n ],\n },\n },\n {\n config: {\n id: 'browser',\n name: 'Browser',\n role: 'browser',\n tools: [\n ...TOOLS.read,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the Browser agent. Your job is browser automation: open web pages,\ninteract with them, extract data, capture screenshots, and return structured\nresults. You are a read-focused agent — you drive the browser, not the filesystem.\n\nScope:\n- Navigate to URLs and wait for pages to load\n- Take full-page or element screenshots as evidence\n- Click buttons, fill forms, select options, type text — full user simulation\n- Extract page content: text, HTML, element attributes, data tables\n- Evaluate JavaScript in the page context to extract structured data\n- Verify visual state (element visibility, text content, attribute values)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"navigate | screenshot | extract | interact | verify\", \"url\": \"<url>\", \"steps\": [\"step1\", \"step2\"] }\n\nOutput: Structured markdown report:\n- ## Page (URL, title, load status)\n- ## Actions Taken (step-by-step with timestamps)\n- ## Results (extracted data, element states, verification results)\n- ## Screenshots (list attached screenshot references)\n- ## Errors (any failures with stack traces)\n\nWorking rules:\n- Always playwright_navigate first before any interaction\n- Always playwright_wait_for after navigation to ensure the page is ready\n- playwright_screenshot is your primary evidence — use it before and after interactions\n- Use playwright_evaluate for structured data extraction (JSON, text content)\n- If a selector fails, try alternative selectors before giving up\n- Report exact CSS selectors used — they're part of the evidence\n- If playwright tools are unavailable, report the error immediately — do not guess`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Browser automation: opens pages, clicks, types, screenshots, extracts data via Playwright headless Chromium.',\n keywords: [\n 'browser',\n 'screenshot',\n 'navigate',\n 'web page',\n 'scrape',\n 'crawl',\n 'headless',\n 'chrome',\n 'open url',\n 'capture',\n 'page title',\n 'extract data',\n 'fill form',\n 'click button',\n 'take screenshot',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n {\n config: {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n tools: [...TOOLS.inspect],\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report with severity-ranked findings, injection\nvectors, dependency issues, and a remediation checklist.\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Security scanner: detects hardcoded secrets, injection vectors, insecure patterns, and supply-chain risks with remediation.',\n keywords: [\n 'security',\n 'scan',\n 'vulnerability',\n 'secret',\n 'api key',\n 'hardcoded',\n 'injection',\n 'cve',\n 'audit dependencies',\n 'supply chain',\n 'xss',\n 'sqli',\n 'shell injection',\n 'sensitive data',\n 'credential',\n ],\n },\n },\n {\n config: {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n tools: [...TOOLS.inspect],\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report with critically/high/medium/low sections.\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Bug hunter: scans source code for bugs, anti-patterns, and code smells, producing a file:line-ranked hit list with fixes.',\n keywords: [\n 'bug',\n 'hunt',\n 'scan',\n 'code smell',\n 'anti-pattern',\n 'race condition',\n 'memory leak',\n 'null deref',\n 'type safety',\n 'unhandled error',\n 'find bugs',\n 'audit code',\n 'code quality',\n ],\n },\n },\n {\n config: {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n tools: [...TOOLS.inspect],\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with Summary, Top Errors, Tool Usage table,\nAnomalies, and Cost Trend sections.\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Audit log analyzer: parses session JSONL, detects failure patterns, tool anomalies, and cost trends with structured reports.',\n keywords: [\n 'audit',\n 'log',\n 'logs',\n 'session',\n 'trace',\n 'analyze logs',\n 'error patterns',\n 'cost analysis',\n 'tool usage',\n 'token usage',\n 'post-mortem',\n 'trend',\n 'anomaly',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [\n ...TOOLS.build,\n 'mcp__ssh__ssh_list_servers',\n 'mcp__ssh__ssh_connection_status',\n 'mcp__ssh__ssh_execute',\n 'mcp__ssh__ssh_execute_sudo',\n 'mcp__ssh__ssh_upload',\n 'mcp__ssh__ssh_download',\n 'mcp__ssh__ssh_sync',\n 'mcp__ssh__ssh_deploy',\n 'mcp__ssh__ssh_health_check',\n 'mcp__ssh__ssh_service_status',\n 'mcp__ssh__ssh_process_manager',\n 'mcp__ssh__ssh_tunnel',\n 'mcp__ssh__ssh_backup_create',\n 'mcp__ssh__ssh_backup_list',\n 'mcp__ssh__ssh_backup_restore',\n 'mcp__ssh__ssh_db_list',\n 'mcp__ssh__ssh_db_query',\n 'mcp__ssh__ssh_profile',\n ],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n- Use optional SSH MCP tools for remote hosts when the 'ssh' MCP server is enabled: list servers, run health checks, inspect services, transfer/deploy files, and open tunnels\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying\n- For remote SSH work, start with ssh_list_servers / ssh_connection_status, prefer read-only checks first, and do not run destructive commands without explicit user approval`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'ssh',\n 'remote ssh',\n 'remote server',\n 'sftp',\n 'tunnel',\n 'bastion',\n 'jump host',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n {\n config: {\n id: 'tech-stack',\n name: 'Tech Stack Validator',\n role: 'tech-stack',\n tools: ['search', 'fetch', 'read', 'grep', 'glob', 'outdated', 'audit', 'json', 'mailbox'],\n prompt: `You are the Tech Stack Validator — a single-shot validation agent that fires\nbefore any package, library, or framework choice is committed.\n\nYour ONLY job: verify that a technology choice is current, real, and not obsolete.\nYou are the \"this isn't code, this is 10-year-old technology\" agent. Intervene\nhard when the LLM hallucinates a version number or suggests dead tech.\n\n## Before you begin\n\nCheck the inter-agent mailbox for pending tasks. Other agents or the file-watcher\nmay have left assign messages with dependency files to audit:\n- mailbox action=check\n\nIf you find an assign message, use the specified file path and packages.\nWhen done, post results back:\n- mailbox action=send to=<sender> type=result subject=\"Tech stack audit results\" body=\"...\"\n\n## Critical rules\n\n1. **Verify existence.** Search npm registry (fetch https://registry.npmjs.org/<pkg>/latest)\n or web search. A package that doesn't exist = hallucination.\n\n2. **Check latest version.** Never trust any version number from the model. Always\n fetch the actual latest stable version from npm or the project's release page.\n\n3. **Reject dead packages.** No release in >2 years + unresolved critical issues =\n dead. Suggest a maintained replacement.\n\n4. **Reject prehistoric tech.** Any package/pattern superseded ≥5 years ago is\n REJECTED. Key blocklist:\n - axios / node-fetch / got / request → native fetch (Node 18+)\n - moment → date-fns / luxon / Temporal\n - jQuery (new projects) → vanilla DOM / React\n - Gulp / Grunt → tsup / esbuild / vite\n - CoffeeScript / Flow → TypeScript\n - Bluebird → native Promises\n - crypto-js → node:crypto / Web Crypto\n - Bower → npm/pnpm\n - underscore → lodash or native ES2020+\n\n5. **The intervention phrase.** When rejecting on age grounds, you MUST output\n exactly: \"This isn't code, this is X-year-old technology.\" where X =\n current year − the year the technology was made obsolete. Follow with\n what replaced it and a one-step migration path.\n\n6. **Prefer built-in over third-party.** Check Node 22+ native APIs first:\n node:test, node:sqlite, fetch, WebSocket, Web Crypto — all built-in.\n\n## Workflow (single-shot — do NOT loop)\n\n1. Receive the proposed package + version\n2. Search npm registry or web for the latest version\n3. Check age, maintenance status, deprecation\n4. Output verdict: APPROVED (with exact version) or REJECTED (with replacement)\n\n## Output format\n\n### Tech Stack Validation — <package>\n\n**Status**: APPROVED | REJECTED\n\n**Package**: <name>@<version>\n**Source**: <URL you checked — npm registry, GitHub, web search>\n**Age**: <first release> — <last release date>\n**Verdict**: 1–2 sentence explanation.\n\nWhen REJECTED on age:\n**\"This isn't code, this is X-year-old technology.\"**\n**Replaced by**: <modern alternative>\n**Migration**: <one concrete step>\n\nWhen APPROVED:\n**Install**: pnpm add <name>@^<major>.<minor>.0`,\n },\n budget: {\n timeoutMs: 120_000,\n maxIterations: 10,\n maxToolCalls: 40,\n maxTokens: 60_000,\n maxCostUsd: 0.25,\n },\n capability: {\n phase: 'meta',\n summary: 'Single-shot tech stack validator: checks npm for latest versions, rejects dead/obsolete packages, enforces modern alternatives.',\n keywords: [\n 'tech stack',\n 'version',\n 'package',\n 'library',\n 'framework',\n 'dependency',\n 'install',\n 'upgrade',\n 'latest',\n 'npm',\n 'pnpm add',\n 'outdated',\n 'obsolete',\n 'deprecated',\n 'what version',\n 'which package',\n 'check version',\n 'verify version',\n 'is this current',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Shadow Agent — one-shot fleet monitoring and intervention.\n * Use for: quiet anomaly checks and on-demand intervention.\n */\r\nexport const SHADOW_AGENT: SubagentConfig = {\n id: 'shadow-agent',\n name: 'Shadow',\n role: 'shadow-agent',\n prompt: `You are the Shadow Agent — a quiet, one-shot monitor for the WrongStack fleet.\n\nYour job is to inspect the fleet when the host explicitly assigns a Shadow pass, detect anomalies, and be ready to intervene — but only when commanded.\n\r\n## Core Responsibilities\r\n\r\n1. **Fleet Monitoring** (host-assigned one-shot checks)\n - The host assigns one-shot check tasks; it does not expect routine heartbeats\n - On each assigned check, call \\`fleet_status\\` + \\`fleet_health\\`\n - Track what each agent is doing (task descriptions)\n - Detect stuck agents (>5min no events), idle agents, crashed agents\n\r\n2. **FleetBus Subscription**\r\n - Subscribe to \\`subagent.*\\` events to track lifecycle\r\n - Subscribe to \\`tool.executed\\` to monitor activity\r\n - Track agent joins (subagent.started) and leaves (subagent.stopped)\r\n\r\n3. **Mailbox Surveillance**\r\n - Monitor for \\`control\\` type messages starting with \"hoop\"\r\n - Detect orphan assigns (assign without result within 5min)\r\n - Cross-session awareness via shared project mailbox\r\n\r\n4. **Spike Detection**\r\n - Track task duration per agent\r\n - Flag agents that spawn and die within <5 seconds\r\n - Log spike events with reason (completed/error/killed/timeout)\r\n\r\n5. **Intervention Commands**\r\n Parse these from mailbox control messages:\r\n - \\`hoop <agentId>\\` — terminate specific agent\r\n - \\`hoop all\\` — terminate all running agents\r\n - \\`shadow status\\` — report current fleet snapshot\r\n - \\`shadow mute\\` — pause anomaly reporting\n - \\`shadow resume\\` — resume anomaly reporting\n - \\`shadow interval <ms>\\` — update the legacy interval setting\n - \\`shadow model <model-id>\\` — change analysis model\r\n\r\n## Operating Rules\n\n- **Silent by default**: Do not send mail or status reports for healthy checks\n- **Deterministic**: Same state always produces same actions — no randomness\n- **Report only when needed**: Use \\`mail_send\\` only for high/critical anomalies or explicit control replies\n- **Never auto-intervene**: Always report unless explicitly commanded\n- **Minimal footprint**: Small state, efficient snapshots\n- **One-shot lifecycle**: Finish the assigned check and stop; do not schedule follow-up work\n\n## Startup Sequence\n\n1. Run one fleet snapshot with \\`fleet_status\\` + \\`fleet_health\\`\n2. Check \\`mail_inbox\\` for explicit control messages\n3. If healthy, do not send mail; final answer may be exactly \\`shadow: quiet\\`\n\n## Shutdown Sequence\n\n1. Return only anomalies, command results, or \\`shadow: quiet\\`\n2. The host stops this Shadow Agent after the assigned pass`,\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n 'shadow-agent': SHADOW_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number | undefined;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number | undefined;\r\n maxIterations?: number | undefined;\r\n maxToolCalls?: number | undefined;\r\n maxTokens?: number | undefined;\r\n maxCostUsd?: number | undefined;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\n 'shadow-agent': {\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\n maxIterations: 2000,\n maxToolCalls: 5000,\n maxTokens: 60_000,\n maxCostUsd: 1,\n },\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.entries(NICKNAME_POOL) as [NicknameKey, { name: string; domain: string }][];\n\n/** Reverse index: display name (e.g. \"Von Neumann\") → canonical pool key. */\nconst NAME_TO_KEY: Record<string, string> = Object.fromEntries(\n ALL_NICKNAMES.map(([key, entry]) => [entry.name, key]),\n);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/** Result of a nickname assignment. */\nexport interface NicknameAssignment {\n /**\n * Canonical pool key (e.g. `von-neumann`). This — NOT the display string — is\n * what callers must add to their `used` set and later remove on release.\n * Deriving the key by parsing the display string is unsafe: multi-word names\n * like \"Von Neumann\" would be truncated to \"von\" and never dedupe correctly.\n */\n key: string;\n /** Human display string, e.g. `Von Neumann (Backend)`. */\n display: string;\n}\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n *\n * Returns both the canonical pool `key` (for the `used` set) and the formatted\n * `display` string (`Name (Role)`, e.g. `Einstein (Bug Hunter)`).\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname KEYS already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): NicknameAssignment {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style.\n for (const [key, entry] of ALL_NICKNAMES) {\n if (!used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 4. Pool exhausted — synthesize a stable, unique key/display pair.\n const counter = used.size + 1;\n return { key: `scientist-${counter}`, display: `Scientist #${counter} (${formatRole(role)})` };\n}\n\n/**\n * Resolve a previously-assigned display string back to its canonical pool key,\n * for release paths that only retained the formatted name (e.g. a manifest\n * entry). Strips the trailing ` (Role)` suffix, then matches the base name\n * against the pool. Returns `undefined` when the name is not a known nickname.\n *\n * Use this instead of `name.split(' ')[0]` — the latter mangles multi-word\n * names like \"Von Neumann\" and \"Berners-Lee\".\n */\nexport function nicknameKeyFromDisplay(display: string): string | undefined {\n const base = display.replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const key = NAME_TO_KEY[base];\n if (key) return key;\n const synthesized = base.match(/^Scientist #(\\d+)$/);\n return synthesized ? `scientist-${synthesized[1]}` : undefined;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}\n","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport {\r\n BudgetExceededError,\r\n DECISION_TIMEOUT_MS,\r\n SubagentBudget,\r\n TIMEOUT_PREEMPT_FRACTION as _preemptFraction,\r\n} from './subagent-budget.js';\r\nimport { classifySubagentError } from './coordinator/error-classifier.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string | undefined;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget | undefined;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner | undefined;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner | undefined;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus | undefined;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n // awaitTasks() registers one short-lived 'task.completed' listener per\r\n // awaited id; a single call awaiting >10 ids (or several concurrent\r\n // callers) crosses Node's default 10-listener cap and prints a spurious\r\n // MaxListenersExceededWarning that also masks genuine leaks. These waiters\r\n // are bounded and self-removing, so lift the cap.\r\n this.setMaxListeners(0);\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const { key, display } = assignNickname(role, this.usedNicknames);\r\n this.usedNicknames.add(key);\r\n this.subagentNicknames.set(subagentId, key);\r\n return { ...subagent, name: display };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n const cfg = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...cfg, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...cfg, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i];\r\n if (!task) continue;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) this.emitPendingAborted(t, message);\r\n }\r\n\r\n /**\r\n * Emit a synthetic `stopped`/`aborted_by_parent` completion for a single\r\n * PENDING task — one that was never counted in `inFlight`. This MUST bypass\r\n * `recordCompletion`: that path does `inFlight--`, which for a pending task\r\n * steals a decrement from a genuinely in-flight task and trips the underflow\r\n * guard — suppressing that real task's `task.completed` and hanging its\r\n * `awaitTasks()` caller. Pushes the result and fires the event directly.\r\n */\r\n private emitPendingAborted(task: TaskSpec, message: string): void {\r\n const synthetic: TaskResult = {\r\n subagentId: task.subagentId ?? 'unassigned',\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task, result: synthetic });\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(\r\n this.runner,\r\n task,\r\n runCtx,\r\n budget,\r\n subagent.config.preemptFraction,\r\n );\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n preemptFraction: number = _preemptFraction,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n // Pre-empt arm state machine:\r\n // ACTIVE — pre-empt can fire for the current ceiling window\r\n // LOCKED — pre-empt is locked; cannot fire until ceiling changes\r\n enum PreemptState {\r\n ACTIVE = 'active',\r\n LOCKED = 'locked',\r\n }\r\n // The wall-clock ceiling value at the moment the state was locked.\r\n // Compared against the current wallLimit to detect stale locks caused by\r\n // external calls to budget.patchLimits().\r\n let preemptedCeiling: number | null = null;\r\n let preemptState: PreemptState = PreemptState.ACTIVE;\r\n // Heartbeat gate for the proactive pre-empt: the timestamp of the subagent's\r\n // last activity at the moment of the most recent grant. A later pre-empt is\r\n // only negotiated if there has been NEW activity since then — a stalled\r\n // agent (no progress since its last grant) gets no further extension and is\r\n // left to the real deadline. `-1` until the first grant so the first\r\n // pre-empt always fires. Activity time is derived from `budget.idleMs()`\r\n // (reset by tool calls / iterations / streamed progress), so it works even\r\n // for runners that don't increment the budget's usage counters directly.\r\n let lastGrantActivityTs = -1;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n // Terminate the subagent, classifying by whether a negotiation listener\r\n // is wired. A listener-observed stop (explicit deny at the deadline, or an\r\n // idle reap while observed) surfaces as 'stopped' — reject with a\r\n // non-budget error so the coordinator's catch falls to `signal.aborted →\r\n // 'stopped'`. With no listener it is an unattended budget breach →\r\n // BudgetExceededError → 'timeout'. This keeps a bare /spawn reporting\r\n // 'timeout' while a director/observer-driven stop reads as 'stopped'.\r\n const terminate = (kind: 'timeout' | 'idle_timeout', limit: number, used: number) => {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n budget._events?.hasListenerFor('budget.threshold_reached')\r\n ? new Error(`subagent stopped: budget ${kind} (limit=${limit}, used=${used})`)\r\n : new BudgetExceededError(kind, limit, used),\r\n );\r\n };\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity), the explicit wall-clock cap, or the PROACTIVE\r\n // pre-empt point (a fraction of the wall cap, see TIMEOUT_PREEMPT_FRACTION)\r\n // at which we negotiate an extension BEFORE the deadline is crossed. Any\r\n // being unset/already-asked drops out of the min, so single-limit configs\r\n // behave exactly as that limit alone.\r\n const scheduleNext = () => {\r\n const wallLimit = budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n const preemptRemaining =\r\n initialTimeoutMs === undefined || preemptedCeiling === wallLimit\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) * preemptFraction - (Date.now() - start);\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining, preemptRemaining)));\r\n };\r\n\r\n // Drive a timeout extension negotiation (used by BOTH the proactive\r\n // pre-empt and the at-deadline path). Resolves to the coordinator's\r\n // verdict: `{ extend: { timeoutMs } }` to grant, or a string to decline.\r\n // The budget's requestDecision falls back to 'stop' on no response, so\r\n // this never hangs.\r\n // Safety net: if no listener responds to the budget.threshold_reached event\r\n // within DECISION_TIMEOUT_MS (60 s), default to 'stop' so the watchdog\r\n // never hangs. Uses the exported DECISION_TIMEOUT_MS so both paths share\r\n // the same value — coordinator and budget agree on the ceiling.\r\n const negotiateTimeout = async (\r\n used: number,\r\n limit: number,\r\n ): Promise<'stop' | 'continue' | 'throw' | { extend: { timeoutMs?: number | undefined } }> => {\r\n const handler = budget.onThreshold;\r\n if (!handler) return 'stop';\r\n const result = handler({\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n requestDecision: () => {\r\n // No listener wired (bare /spawn, no director) → nobody can grant an\r\n // extension, so resolve to 'stop' immediately. Without this the emit\r\n // below goes unanswered and the run parks on the 60 s fallback timer\r\n // before stopping — the deadline must reap promptly instead. Mirrors\r\n // SubagentBudget._busRequestDecision so both agree on the default.\r\n if (!budget._events?.hasListenerFor('budget.threshold_reached')) {\r\n return Promise.resolve<'stop' | { extend: { timeoutMs?: number | undefined } }>('stop');\r\n }\r\n return new Promise<'stop' | { extend: { timeoutMs?: number | undefined } }>((resolveDecision) => {\r\n let settled = false;\r\n const resolve = (d: 'stop' | { extend: { timeoutMs?: number | undefined } }) => {\r\n if (settled) return;\r\n settled = true;\r\n resolveDecision(d);\r\n };\r\n const fallback = setTimeout(() => resolve('stop'), DECISION_TIMEOUT_MS);\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n // Informational: the budget's own decision deadline. Listeners may use\r\n // this to display a countdown. The coordinator does NOT enforce it —\r\n // it is the budget's own `setTimeout(fallback)` that races against\r\n // the listener's `extend()`/`deny()` call to guarantee progress.\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n // deny() wins over a same-dispatch extend(): defer the grant a\r\n // microtask so a synchronous deny in the same emit pre-empts it\r\n // (a listener that both grants and denies, or two listeners\r\n // disagreeing, resolves as a stop). Async grants still resolve.\r\n extend: (extra) => {\r\n clearTimeout(fallback);\r\n queueMicrotask(() => resolve({ extend: extra }));\r\n },\r\n deny: () => {\r\n clearTimeout(fallback);\r\n resolve('stop');\r\n },\r\n });\r\n });\r\n },\r\n });\r\n return typeof result === 'string' ? result : await result;\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is NOT\r\n // negotiable; the point of the default is to free a stuck slot. We still\r\n // emit the threshold event first so observers (director / monitor) can\r\n // record the reap, but any extension a listener offers is ignored.\r\n if (idleExceeded && !wallExceeded) {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'idle_timeout',\r\n used: budget.idleMs(),\r\n limit: idleLimit ?? 0,\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n extend: () => {},\r\n deny: () => {},\r\n });\r\n // An idle stall is a passive TIMEOUT (the agent hung), not an explicit\r\n // coordinator stop — surface it as 'timeout' regardless of any\r\n // listener. (Contrast the wall-clock deadline below, where an explicit\r\n // listener deny is a deliberate stop → 'stopped'.)\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('idle_timeout', idleLimit ?? 0, budget.idleMs()));\r\n return;\r\n }\r\n\r\n // PROACTIVE pre-empt: we've passed TIMEOUT_PREEMPT_FRACTION of the wall\r\n // window but NOT the deadline itself. Negotiate an extension now, while\r\n // the agent is still under its limit, so a progressing subagent gets its\r\n // ceiling raised and never enters a timed-out state. Heartbeat-gated on\r\n // the granting side (director / attachAutoExtend): no progress ⇒ decline,\r\n // and we fall through to the real-deadline behaviour below at the cap.\r\n // Asked at most once per window (preemptState === ACTIVE).\r\n if (\r\n wallLimit !== undefined &&\r\n !wallExceeded &&\r\n budget.onThreshold &&\r\n preemptState === PreemptState.ACTIVE &&\r\n elapsed >= wallLimit * preemptFraction\r\n ) {\r\n // Heartbeat gate: only negotiate a pre-empt extension if the agent has\r\n // made progress (a tool call / iteration / streamed output) SINCE the\r\n // last grant. A stalled agent — no new activity since its last\r\n // extension — gets no further pre-empt; we lock and let the real\r\n // deadline reap it. `activityTs` is the wall-clock time of the last\r\n // activity (now − idleMs). Without this gate an always-granting\r\n // listener would extend a wedged agent forever and the deadline would\r\n // never fire (T1).\r\n const activityTs = Date.now() - budget.idleMs();\r\n if (activityTs <= lastGrantActivityTs) {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n scheduleNext();\r\n return;\r\n }\r\n // C1 fix: register the watchdog as active BEFORE calling onThreshold so\r\n // that any concurrent tool.progress → checkTimeout() path sees the flag\r\n // and skips its own wall-clock emission. Cleared on every exit path so\r\n // checkTimeout() resumes normal operation after negotiation completes.\r\n budget.setWatchdogNegotiation(wallLimit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, wallLimit);\r\n if (typeof decision !== 'string' && decision.extend.timeoutMs !== undefined) {\r\n // Granted ahead of the deadline — raise the ceiling and open a\r\n // fresh window (a later pre-empt becomes eligible again, but only\r\n // if there is fresh activity by then — see the heartbeat gate).\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n } else {\r\n // Declined proactively (no progress / no listener). Don't re-ask\r\n // until the real deadline — the wallExceeded path below handles the\r\n // at-cap behaviour (warn+continue or hard stop).\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n }\r\n } catch {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n } finally {\r\n budget.clearWatchdogNegotiation();\r\n }\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out (or a pre-empt was just resolved).\r\n // Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit ?? 0;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // C1 fix: same guard as the pre-empt branch — register before onThreshold\r\n // so concurrent tool.progress → checkTimeout() skips its wall-clock emission.\r\n budget.setWatchdogNegotiation(limit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, limit);\r\n if (decision === 'throw') {\r\n // 'throw' is an explicit signal from the handler: end now rather\r\n // than silently keeping the subagent alive past its deadline.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n if (decision === 'continue') {\r\n // 'continue' — timeout denied but coordinator wants the agent to keep\r\n // running. Re-arm for a full wall window so we ask again later.\r\n // This makes wall-clock timeout a pure warning event: the subagent\r\n // keeps running until it naturally finishes, the next deadline fires,\r\n // or the user stops it.\r\n //\r\n // IMPORTANT: we must lock the pre-empt arm (set preemptState =\r\n // LOCKED) so it does NOT fire again until the ceiling changes.\r\n // The ceiling only changes if a future negotiation returns 'extend'\r\n // and patches budget.limits.timeoutMs. Without the lock, the\r\n // pre-empt would re-arm for ~1 s (Math.max(1_000, limit)) and\r\n // immediately fire again at elapsed > wallLimit × 0.85, creating\r\n // a ping-pong loop of spurious budget.threshold_reached events.\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n if (decision === 'stop') {\r\n // 'stop' — coordinator explicitly denied the extension and wants\r\n // the agent to end. This is a terminal decision: end now.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — nothing to grant → end.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n return;\r\n } finally {\r\n // Always clear the watchdog flag so checkTimeout() resumes wall-clock\r\n // checking on the next tool.progress event.\r\n budget.clearWatchdogNegotiation();\r\n }\r\n };\r\n // First arm: whichever of the idle window / pre-empt point / wall cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n result: result.result,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n // Inline-emit, NOT recordCompletion: these are PENDING tasks that were\r\n // never counted in inFlight. Routing them through recordCompletion would\r\n // decrement inFlight on behalf of a still-running task and suppress that\r\n // task's own completion via the underflow guard, hanging its awaiter.\r\n this.emitPendingAborted(\r\n t,\r\n `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n );\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. Delegates to the shared classifier.\r\n * Re-exported for backward compatibility.\r\n */\r\nexport { classifySubagentError } from './coordinator/error-classifier.js';\r\n","/**\n * SddTaskDecomposer\n *\n * Converts a TaskGraph (from SDD's TaskGenerator) into a dependency-aware\n * sequence of batches for ParallelEternalEngine.\n *\n * Key behaviour:\n * - Each `nextBatch()` call returns up to `parallelSlots` ready tasks\n * (all blockers completed, sorted by priority).\n * - Tasks that are blocked by an in-progress task are NOT included\n * in the batch — they wait for the blocker to complete.\n * - When `isDone()` returns true the whole graph is either completed\n * or deadlocked (all remaining tasks are blocked by failed tasks).\n *\n * Usage:\n * ```\n * const decomposer = new SddTaskDecomposer(tracker, graph, { parallelSlots: 4 });\n * while (!decomposer.isDone()) {\n * const batch = decomposer.nextBatch();\n * if (batch.length === 0) break; // deadlock\n * await fanOut(batch);\n * decomposer.acknowledgeBatch(batch.map(t => t.id));\n * }\n * ```\n */\n\nimport type { TaskNode, TaskGraph } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\n\nexport interface SddTaskDecomposerOptions {\n /** Max tasks per batch. Default: 4. Range 1–16. */\n parallelSlots?: number | undefined;\n}\n\nexport interface TaskBatch {\n /** Tasks ready to execute in this wave. */\n tasks: TaskNode[];\n /** 0-based wave number since the decomposer was constructed. */\n wave: number;\n /** True when every node in the graph is either completed or failed. */\n allDone: boolean;\n /** True when no batch was produced because remaining tasks are all blocked by failed nodes. */\n deadlocked: boolean;\n}\n\nexport class SddTaskDecomposer {\n private readonly slots: number;\n private wave = 0;\n\n constructor(\n private readonly tracker: TaskTracker,\n _graph: TaskGraph,\n opts: SddTaskDecomposerOptions = {},\n ) {\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n }\n\n // -------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------\n\n /**\n * Return the next batch of runnable tasks.\n * Returns `allDone: true` when every node is completed.\n * Returns `deadlocked: true` when no batch can be produced because\n * all remaining tasks are blocked by failed nodes.\n */\n nextBatch(): TaskBatch {\n if (this.isDone()) {\n return { tasks: [], wave: this.wave, allDone: true, deadlocked: false };\n }\n\n const pending = this.pendingReadyNodes();\n\n if (pending.length === 0) {\n // No runnable tasks — check for deadlock\n const hasBlockedTasks = this.hasAnyBlockedTasks();\n return { tasks: [], wave: this.wave, allDone: false, deadlocked: hasBlockedTasks };\n }\n\n const batch = pending.slice(0, this.slots);\n return { tasks: batch, wave: this.wave, allDone: false, deadlocked: false };\n }\n\n /**\n * Advance the wave counter after a batch completes.\n * Call this once per `nextBatch()` result that was fan-out.\n */\n acknowledgeBatch(_completedTaskIds: string[]): void {\n this.wave++;\n }\n\n /**\n * True when every node in the graph is completed.\n * Use this to exit the fan-out loop after `isDone() || deadlocked`.\n */\n isDone(): boolean {\n const progress = this.tracker.getProgress();\n return progress.total > 0 && progress.completed === progress.total;\n }\n\n /**\n * Total waves produced so far.\n */\n getWaveCount(): number {\n return this.wave;\n }\n\n /**\n * All ready (dependency-satisfied) pending tasks, priority-sorted — UNSLICED.\n * The continuous scheduler fills its own free slots from this list, so unlike\n * `nextBatch()` it does not cap at `slots`.\n */\n readyNodes(): TaskNode[] {\n return this.pendingReadyNodes();\n }\n\n /**\n * True when every node has reached a terminal state (completed or failed).\n * This — not `isDone()` (which requires ALL completed) — is the correct loop\n * exit for the continuous scheduler: a terminally-failed task must not keep\n * the run spinning to its backstop.\n */\n isSettled(): boolean {\n const nodes = this.tracker.getAllNodes();\n return nodes.length > 0 && nodes.every((n) => n.status === 'completed' || n.status === 'failed');\n }\n\n // -------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------\n\n /**\n * Return pending nodes whose blockers are all completed.\n * Sorted by priority (critical first), then by creation time.\n */\n private pendingReadyNodes(): TaskNode[] {\n const allPending = this.tracker.getAllNodes({ status: ['pending'] });\n const ready: TaskNode[] = [];\n\n for (const node of allPending) {\n if (this.tracker.canStart(node.id)) {\n ready.push(node);\n }\n }\n\n // Sort by priority first, then by createdAt\n const priorityRank: Record<TaskNode['priority'], number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n };\n\n ready.sort((a, b) => {\n const pr = priorityRank[a.priority] - priorityRank[b.priority];\n if (pr !== 0) return pr;\n return a.createdAt - b.createdAt;\n });\n\n return ready;\n }\n\n /** True when at least one non-completed, non-failed task is blocked. */\n private hasAnyBlockedTasks(): boolean {\n const nodes = this.tracker.getAllNodes({\n status: ['pending', 'in_progress', 'blocked'],\n });\n return nodes.some((n) => n.status === 'blocked');\n }\n}","import { expectDefined } from '../utils/expect-defined.js';\n/**\n * SddParallelRun\n *\n * Drives a TaskGraph through ParallelEternalEngine's infrastructure\n * (DefaultMultiAgentCoordinator + AgentSubagentRunner) but powered by\n * SddTaskDecomposer — producing dependency-aware waves instead of\n * goal-driven iterations.\n *\n * One-shot: completes when all tasks are done OR a deadlock is detected.\n * Does NOT loop — each run() call is a discrete execution.\n *\n * Usage:\n * ```\n * const run = new SddParallelRun({ tracker, graph, agent, projectRoot });\n * await run.run({ onWave });\n * // or with progress callback:\n * await run.run({ onProgress: (p) => console.log(renderProgress(p)) });\n * ```\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner, withDisabledToolFiltering } from '../coordination/agent-subagent-runner.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport { assignNickname } from '../coordination/subagent-nicknames.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { WorktreeHandle, WorktreeManager } from '../worktree/worktree-manager.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\nimport type { TaskGraph, TaskNode, TaskProgress } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport { SddError, ERROR_CODES } from '../types/errors.js';\nimport { SddTaskDecomposer, type TaskBatch } from './sdd-task-decomposer.js';\n/** A sub-task produced by splitting a parent task (see `splitTask`). */\nexport interface SddSubtaskSpec {\n title: string;\n description: string;\n type?: TaskNode['type'] | undefined;\n priority?: TaskNode['priority'] | undefined;\n}\n\n/**\n * Verdict returned by the optional failure supervisor when a task is about to go\n * terminal. `retry` re-queues with a fresh attempt budget; `reassign` swaps the\n * worker model (+ optional provider) then re-queues; `split` breaks the task\n * into sub-tasks; `fail` (or `undefined`) lets it terminal-fail.\n */\nexport type SddSupervisorVerdict =\n | { action: 'retry' }\n | { action: 'reassign'; model?: string | undefined; provider?: string | undefined }\n | { action: 'split'; subtasks: SddSubtaskSpec[] }\n | { action: 'fail' };\n\nexport interface SddParallelRunOptions {\n /** Pre-constructed TaskTracker (must already hold the graph's initial state). */\n tracker: TaskTracker;\n /** The TaskGraph produced by TaskGenerator from an approved spec. */\n graph: TaskGraph;\n /** The main agent — used as the subagent factory. */\n agent: Agent;\n /** Project root (used for coordinator id). */\n projectRoot: string;\n /**\n * Override default parallel slots (1–16). Default: 2 — deliberately low so a\n * run never juggles more git worktrees than a human can review. Independent\n * tasks still run concurrently up to this cap; dependency chains run in order.\n */\n parallelSlots?: number | undefined;\n /**\n * Hard wall-clock cap per task in ms. OPT-IN — `undefined` by default so a\n * long-but-productive task is never killed merely for running long (the old\n * 5-min default hard-killed real coding tasks with `budget_timeout`). When\n * set, the coordinator watchdog enforces it. Prefer `taskIdleTimeoutMs`.\n */\n taskTimeoutMs?: number | undefined;\n /**\n * Idle reaper per task in ms: reap a task only after this long with NO\n * activity (iteration / tool call / streamed token / tool progress). Resets\n * on every sign of forward motion, so an actively-working agent runs until\n * its task naturally ends. Default: 600_000 (10 min of silence = genuinely\n * stuck). This is the default guard — wall-clock (`taskTimeoutMs`) is opt-in.\n */\n taskIdleTimeoutMs?: number | undefined;\n /** Maximum in-run retry attempts for a failed task before it goes terminal. Default: 3. */\n maxRetries?: number | undefined;\n /**\n * After the graph settles with terminal-failed tasks, requeue ALL failed\n * (non-cancelled) tasks to `pending` and run them again — up to this many\n * sweeps. Each sweep gives every failed task a fresh `maxRetries` budget. The\n * loop stops early once a sweep produces no new completions (no progress).\n * 0 = off. Default: 2.\n */\n maxFailedRetrySweeps?: number | undefined;\n /** Override the default agent factory. */\n subagentFactory?: AgentFactory | undefined;\n /**\n * Run-level default model for worker subagents. A task's own\n * `metadata.model` (set per-task in the WebUI) takes precedence; this is the\n * fallback for every task that has no explicit assignment. Undefined → the\n * factory's own default (the leader's model).\n */\n defaultModel?: string | undefined;\n /** Run-level default provider id (same precedence rules as defaultModel). */\n defaultProvider?: string | undefined;\n /**\n * Run-level fallback model chain (entries: `model` / `provider/model`). A\n * task's `metadata.fallbackModels` overrides this. The subagent factory wires\n * these into a fallback extension so a 429/stream-hang rotates to the next.\n */\n fallbackModels?: string[] | undefined;\n /**\n * Post-task verification gate. When set, a task whose worker reported success\n * is NOT marked `completed` (and NOT merged) until this resolves `{ok:true}`.\n * Runs in the task's worktree cwd (or the project root when no worktree). Core\n * stays shell-agnostic — the caller injects a verifier that, e.g., runs the\n * task's `metadata.verificationCommand` (tests / typecheck). A task with no\n * command should return `{ok:true}`. An `{ok:false}` routes the task into the\n * normal failure path (retry while attempts remain, else terminal-fail).\n */\n verifyTask?:\n | ((info: { task: TaskNode; result: TaskResult; cwd: string }) => Promise<{ ok: boolean; reason?: string }>)\n | undefined;\n /**\n * Optional merge-conflict resolver, forwarded to `WorktreeManager.merge`. Given\n * the conflicted files + the base checkout cwd, return `true` once resolved (no\n * markers left). When omitted or it returns `false`, the task is requeued (a\n * re-run forks a fresh worktree off the advanced base) and, if retries are\n * exhausted, terminally failed with its worktree kept for review.\n */\n conflictResolver?:\n | ((info: { task: TaskNode; conflictFiles: string[]; cwd: string }) => Promise<boolean>)\n | undefined;\n /**\n * Failure supervisor: consulted ONLY when a task has exhausted its retries and\n * is about to go terminal-failed. Returning a verdict lets a decision agent\n * keep the run moving — `retry` / `reassign` (swap model) / `split` — instead\n * of dead-ending. Returning `{action:'fail'}` / `undefined` lets it fail. Each\n * task can be rescued at most `maxSupervisorEscalations` times (loop guard).\n */\n superviseFailure?:\n | ((info: { task: TaskNode; error: string; attempts: number }) => Promise<SddSupervisorVerdict | undefined>)\n | undefined;\n /** Max times the supervisor may rescue a single task before it must fail. Default 2. */\n maxSupervisorEscalations?: number | undefined;\n /** Called after each wave completes. */\n onWave?: ((wave: WaveResult) => void) | undefined;\n /** Called with progress stats every ~2s during execution. */\n onProgress?: ((progress: SddProgress) => void) | undefined;\n /** Shared EventBus — when set, the run emits `sdd.*` live-board events. */\n events?: EventBus | undefined;\n /** Stable id correlating all events of this run (default: random). */\n runId?: string | undefined;\n /**\n * Optional git-worktree manager. When set (and the project is a git repo),\n * each task runs in its own isolated worktree and merges back into the base\n * branch after success — so parallel agents never collide on the same files.\n */\n worktrees?: WorktreeManager | undefined;\n /** Run-level backstops (prevent an autonomous run from looping forever). */\n maxTotalWaves?: number | undefined;\n maxWallClockMs?: number | undefined;\n /**\n * Deadlock auto-recovery rounds: when the graph deadlocks on failed blockers,\n * requeue those failed blockers `pending` and try again, up to N times. 0 = off.\n */\n maxRecoveryRounds?: number | undefined;\n}\n\nexport interface SddProgress {\n wave: number;\n total: number;\n completed: number;\n inProgress: number;\n failed: number;\n blocked: number;\n pending: number;\n percent: number;\n deadlocked: boolean;\n}\n\nexport interface WaveResult {\n wave: number;\n batch: TaskBatch;\n results: TaskResult[];\n successCount: number;\n failCount: number;\n durationMs: number;\n stopRequested: boolean;\n}\n\n/** Result of a single task's execution in the continuous scheduler. */\ninterface TaskOutcome {\n taskId: string;\n success: boolean;\n result?: TaskResult | undefined;\n}\n\nexport interface RunResult {\n totalWaves: number;\n totalCompleted: number;\n totalFailed: number;\n totalDurationMs: number;\n deadlocked: boolean;\n stopRequested: boolean;\n finalProgress: TaskProgress;\n}\n\nexport class SddParallelRun {\n private readonly slots: number;\n /** Opt-in hard wall-clock cap (undefined → no cap; idle reaper guards instead). */\n private readonly timeoutMs: number | undefined;\n /** Idle reaper window (ms) — resets on activity; reaps only a genuine stall. */\n private readonly idleTimeoutMs: number;\n private readonly maxRetries: number;\n /** Max supervisor rescues per task before it must terminal-fail (loop guard). */\n private readonly maxSupervisorEscalations: number;\n /** Per-task count of supervisor rescues used (resets nothing — bounds the loop). */\n private supervisorEscalations = new Map<string, number>();\n /** Max end-of-run failed-task sweeps (see `maxFailedRetrySweeps`). */\n private readonly maxFailedSweeps: number;\n /** How many failed-task sweeps have run this `run()` so far. */\n private failedSweeps = 0;\n /** Completed-count snapshot at the last sweep, to detect a no-progress sweep. */\n private lastSweepCompleted = 0;\n private decomposer: SddTaskDecomposer;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private stopRequested = false;\n private retryMap = new Map<string, number>();\n readonly runId: string;\n private readonly events?: EventBus | undefined;\n private readonly maxTotalWaves: number;\n private readonly maxWallClockMs?: number | undefined;\n private readonly maxRecoveryRounds: number;\n private recoveryRounds = 0;\n /** Per-run worker identities, so the board shows \"who is on what\". */\n private usedNicknames = new Set<string>();\n /** Per-task git worktree cwd (Layer 2 worktree isolation; empty otherwise). */\n private taskCwds = new Map<string, string>();\n /** Per-task git worktree branch, for board display. */\n private taskBranches = new Map<string, string>();\n /** Live worktree handles keyed by task id (for commit/merge/release). */\n private taskWorktrees = new Map<string, WorktreeHandle>();\n /** Live subagent id per running task — lets cancelTask() abort exactly one. */\n private taskSubagents = new Map<string, string>();\n /** Tasks the user cancelled mid-flight — skip retry, mark terminal-cancelled. */\n private cancelledTasks = new Set<string>();\n /**\n * Base branch the run's squash commits land on (captured once at start when\n * worktrees are enabled). Anchors a later `rollback()`.\n */\n private baseBranch: string | undefined;\n /**\n * Squash-merge commits this run landed on the base branch, in landing order.\n * `rollback()` reverts these (newest → oldest). Persisted via the board\n * snapshot so a post-run rollback can read them off disk.\n */\n private mergedCommits: Array<{ taskId: string; sha: string; title: string }> = [];\n /** Monotonic dispatch counter (unique subagent ids) + dispatch-round counter. */\n private dispatchSeq = 0;\n private round = 0;\n\n constructor(private readonly opts: SddParallelRunOptions) {\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 2));\n // Wall-clock cap is OPT-IN (undefined → none). The idle reaper is the\n // default guard: it resets on every activity signal so a productive task\n // is never killed for running long — only a genuine stall is reaped.\n this.timeoutMs = opts.taskTimeoutMs;\n this.idleTimeoutMs = Math.max(1, opts.taskIdleTimeoutMs ?? 600_000);\n this.maxRetries = Math.max(0, opts.maxRetries ?? 3);\n this.maxSupervisorEscalations = Math.max(0, opts.maxSupervisorEscalations ?? 2);\n this.maxFailedSweeps = Math.max(0, opts.maxFailedRetrySweeps ?? 2);\n this.runId = opts.runId ?? `sdd-${randomUUID().slice(0, 8)}`;\n this.events = opts.events;\n // Backstop: even with retries + recovery the loop must terminate. Derive a\n // generous ceiling from the graph size unless the caller pins one.\n this.maxTotalWaves =\n opts.maxTotalWaves ?? opts.graph.nodes.size * (this.maxRetries + 2) + 10;\n this.maxWallClockMs = opts.maxWallClockMs;\n this.maxRecoveryRounds = Math.max(0, opts.maxRecoveryRounds ?? 0);\n this.decomposer = new SddTaskDecomposer(opts.tracker, opts.graph, { parallelSlots: this.slots });\n }\n\n /** Type-safe emit on the optional EventBus (no-op when unwired). */\n private emit<K extends keyof import('../kernel/events.js').EventMap>(\n event: K,\n payload: import('../kernel/events.js').EventMap[K],\n ): void {\n this.events?.emit(event, payload);\n }\n\n // -------------------------------------------------------------------\n // Public API\n // -------------------------------------------------------------------\n\n private paused = false;\n\n /** Trigger stop — causes run() to abort after the current wave. */\n stop(): void {\n this.stopRequested = true;\n this.paused = false;\n this.coordinator?.stopAll();\n }\n\n /** Pause: no new wave starts until resume() (the current wave finishes). */\n pause(): void {\n this.paused = true;\n }\n resume(): void {\n this.paused = false;\n }\n isPaused(): boolean {\n return this.paused;\n }\n isRunning(): boolean {\n return !this.stopRequested && !this.decomposer.isSettled();\n }\n\n /** Base branch the run's squash commits land on (undefined when worktrees off). */\n getBaseBranch(): string | undefined {\n return this.baseBranch;\n }\n\n /** Squash commits this run landed on the base branch, in landing order. */\n getMergedCommits(): ReadonlyArray<{ taskId: string; sha: string; title: string }> {\n return this.mergedCommits;\n }\n\n /**\n * Remove every git worktree + branch this run (and any prior run) created.\n * Refuses while the run is still live — cleaning a checkout under an active\n * worker would corrupt it. Stop first. Returns the number of worktrees removed\n * (0 when worktrees are disabled). Idempotent.\n */\n async cleanupWorktrees(): Promise<number> {\n if (this.isRunning()) return 0;\n const wt = this.opts.worktrees;\n if (!wt) return 0;\n // Release any handles this run still holds (kept on stop / needs-review).\n for (const [taskId, handle] of [...this.taskWorktrees]) {\n await wt.release(handle, { keep: false }).catch(() => {});\n this.forgetWorktree(taskId);\n }\n const { removed } = await wt.cleanupAllManaged();\n return removed;\n }\n\n /**\n * Undo the run's merged commits by reverting each on the base branch (history\n * preserving). Refuses while the run is still live (stop first). Returns the\n * revert outcome; a dirty tree or revert conflict surfaces as `ok:false`.\n */\n async rollback(): Promise<{ ok: boolean; reverted: number; reason?: string }> {\n if (this.isRunning()) return { ok: false, reverted: 0, reason: 'run still active — stop it first' };\n const wt = this.opts.worktrees;\n if (!wt || !this.baseBranch) {\n return { ok: false, reverted: 0, reason: 'no worktree run to roll back' };\n }\n return wt.revertCommits(\n this.baseBranch,\n this.mergedCommits.map((c) => c.sha),\n );\n }\n\n /** Requeue a task to `pending` so the scheduler re-runs it (clears retries + cancel marker). */\n retryTask(taskId: string): boolean {\n if (!this.opts.tracker.getNode(taskId)) return false;\n this.retryMap.delete(taskId);\n this.persistRetries(taskId, 0);\n // Clear any cancel marker so a previously-cancelled task can run again.\n this.cancelledTasks.delete(taskId);\n this.opts.tracker.patchMetadata(taskId, { cancelled: undefined });\n this.opts.tracker.updateNodeStatus(taskId, 'pending', 'manual retry');\n return true;\n }\n\n /** Reassign a task to a specific agent name (reflected on the board). */\n reassignTask(taskId: string, agentName: string): boolean {\n if (!this.opts.tracker.getNode(taskId)) return false;\n this.opts.tracker.updateNode(taskId, { assignee: agentName });\n return true;\n }\n\n /**\n * Set/override a task's worker model (and optionally provider) — applied on its\n * NEXT dispatch (a running task must be cancelled + retried to take effect). The\n * assignment lives on node metadata so it survives crash → resume.\n */\n setTaskModel(taskId: string, model: string | undefined, provider?: string | undefined): boolean {\n if (!this.opts.tracker.getNode(taskId)) return false;\n this.opts.tracker.patchMetadata(taskId, { model, ...(provider !== undefined ? { provider } : {}) });\n return true;\n }\n\n /** Set/override a task's fallback model chain (applied on its next dispatch). */\n setTaskFallbacks(taskId: string, fallbackModels: string[] | undefined): boolean {\n if (!this.opts.tracker.getNode(taskId)) return false;\n this.opts.tracker.patchMetadata(taskId, { fallbackModels });\n return true;\n }\n\n /**\n * Set/override a task's verification command (the completion gate runs it in\n * the task's cwd and only lets the task complete on exit 0). Empty/undefined\n * clears it. Applied on the task's next verification — i.e. its next dispatch.\n */\n setTaskVerification(taskId: string, verificationCommand: string | undefined): boolean {\n if (!this.opts.tracker.getNode(taskId)) return false;\n const cmd = verificationCommand?.trim();\n this.opts.tracker.patchMetadata(taskId, { verificationCommand: cmd ? cmd : undefined });\n return true;\n }\n\n /**\n * Cancel a task. If it is currently running, abort its subagent and mark the\n * node terminally failed+cancelled (so the scheduler frees the slot and does\n * NOT retry it). If it has not started, it is simply marked cancelled. Use\n * `retryTask` to bring a cancelled task back. Returns false for an unknown task.\n */\n async cancelTask(taskId: string): Promise<boolean> {\n const node = this.opts.tracker.getNode(taskId);\n if (!node) return false;\n this.cancelledTasks.add(taskId);\n // Terminal failed + cancel marker: failed keeps dependents un-deadlocked,\n // the marker drives the \"Cancelled\" board look and blocks retry/auto-redispatch.\n this.opts.tracker.patchMetadata(taskId, { cancelled: true });\n this.opts.tracker.updateNodeStatus(taskId, 'failed', 'cancelled by user');\n this.emit('sdd.task.failed', { runId: this.runId, taskId, subagentId: '', error: 'cancelled by user' });\n const subagentId = this.taskSubagents.get(taskId);\n if (subagentId && this.coordinator) {\n await this.coordinator.stop(subagentId).catch(() => {});\n }\n return true;\n }\n\n /**\n * Delete a not-yet-started task from the graph (pending/blocked/failed only —\n * never a running task; cancel it first). Removes the node and every edge\n * touching it; dependents lose this blocker. Returns false if missing or running.\n */\n deleteTask(taskId: string): boolean {\n const node = this.opts.tracker.getNode(taskId);\n if (!node) return false;\n if (node.status === 'in_progress' || this.taskSubagents.has(taskId)) return false;\n this.cancelledTasks.delete(taskId);\n this.retryMap.delete(taskId);\n return this.opts.tracker.removeNode(taskId);\n }\n\n /**\n * Split a task into sub-tasks and delegate them to separate workers. The new\n * leaves inherit the parent's blockers (so they don't start before the\n * parent's dependencies are met), every existing dependent is rewired to\n * depend on ALL leaves (so downstream work waits for the whole split), and the\n * parent becomes a `completed` container. Refuses a running task (cancel it\n * first) or empty subtask list. Returns the new leaf ids (empty on refusal).\n * The scheduler picks the new pending leaves up on its next dispatch pass.\n */\n splitTask(taskId: string, subtasks: SddSubtaskSpec[]): string[] {\n const tracker = this.opts.tracker;\n const node = tracker.getNode(taskId);\n if (!node) return [];\n if (node.status === 'in_progress' || this.taskSubagents.has(taskId)) return [];\n if (!subtasks.length) return [];\n\n const blockers = tracker.getBlockers(taskId);\n const dependents = tracker.getDependents(taskId);\n\n const leafIds = subtasks.map(\n (s) =>\n tracker.addNode({\n title: s.title,\n description: s.description,\n type: s.type ?? node.type,\n priority: s.priority ?? node.priority,\n status: 'pending',\n parentId: taskId,\n } as never).id,\n );\n\n for (const leaf of leafIds) {\n // Each leaf inherits the parent's dependencies…\n for (const b of blockers) tracker.addDependency(b, leaf);\n // …and every prior dependent of the parent now waits on every leaf.\n for (const dep of dependents) tracker.addDependency(leaf, dep);\n }\n\n // The parent is now just a grouping node — mark it completed so the graph\n // can settle (its real work lives in the leaves).\n this.retryMap.delete(taskId);\n this.persistRetries(taskId, 0);\n tracker.updateNodeStatus(taskId, 'completed', `split into ${leafIds.length} subtasks`);\n this.emit('sdd.task.split', { runId: this.runId, taskId, subtaskIds: leafIds });\n return leafIds;\n }\n\n private async waitWhilePaused(): Promise<void> {\n while (this.paused && !this.stopRequested) {\n await new Promise((r) => setTimeout(r, 100));\n }\n }\n\n /**\n * Continuous dependency-driven execution. Unlike a wave-barrier loop (where a\n * whole batch must finish before the next starts), this fills free worker\n * slots the instant a task's dependencies are satisfied: a fast task's\n * dependent starts immediately rather than waiting for a slow sibling. Truly\n * independent tasks run in parallel; dependency chains run in order. Returns\n * the final summary when the graph settles, deadlocks, stops, or hits a backstop.\n */\n async run(): Promise<RunResult> {\n this.stopRequested = false;\n this.restoreRetryMap();\n const startTime = Date.now();\n this.round = 0;\n this.dispatchSeq = 0;\n let totalDispatched = 0;\n\n this.buildCoordinator();\n\n // Capture the base branch once so a later rollback knows where the run's\n // squash commits landed (worktree path only; no-op without a manager).\n if (this.opts.worktrees && !this.baseBranch) {\n const base = await this.opts.worktrees.currentBase().catch(() => null);\n if (base) this.baseBranch = base.branch;\n }\n\n this.emit('sdd.run.started', {\n runId: this.runId,\n graphId: this.opts.graph.id,\n specId: this.opts.graph.specId,\n total: this.opts.graph.nodes.size,\n baseBranch: this.baseBranch,\n });\n\n this.recoveryRounds = 0;\n this.failedSweeps = 0;\n this.lastSweepCompleted = 0;\n let deadlocked = false;\n // node id → in-flight executeOne promise. size = live worker count.\n const running = new Map<string, Promise<TaskOutcome>>();\n\n const dispatch = (task: TaskNode): void => {\n totalDispatched++;\n const tracked = (async (): Promise<TaskOutcome> => {\n try {\n return await this.executeOne(task);\n } catch (err) {\n // A dispatch-time throw must not wedge the scheduler: mark the node\n // terminally failed (frees its dependents per failed-blocker rules).\n this.opts.tracker.updateNodeStatus(task.id, 'failed', `dispatch error: ${String(err)}`);\n this.emit('sdd.task.failed', { runId: this.runId, taskId: task.id, subagentId: '', error: String(err) });\n return { taskId: task.id, success: false };\n } finally {\n running.delete(task.id);\n }\n })();\n running.set(task.id, tracked);\n };\n\n while (!this.stopRequested) {\n // Run-level backstops — an autonomous run must always terminate.\n if (totalDispatched >= this.maxTotalWaves) break;\n if (this.maxWallClockMs && Date.now() - startTime >= this.maxWallClockMs) break;\n\n await this.waitWhilePaused();\n if (this.stopRequested) break;\n\n // Fill free slots with ready (dependency-satisfied) tasks not already running.\n let dispatchedThisRound = 0;\n if (running.size < this.slots) {\n const ready = this.decomposer.readyNodes().filter((t) => !running.has(t.id));\n for (const task of ready) {\n if (running.size >= this.slots) break;\n dispatch(task);\n dispatchedThisRound++;\n }\n }\n if (dispatchedThisRound > 0) {\n this.emit('sdd.wave', { runId: this.runId, wave: this.round, batchSize: dispatchedThisRound });\n this.round++;\n }\n\n if (running.size === 0) {\n // Nothing in flight and nothing dispatched this pass.\n if (this.decomposer.isSettled()) {\n // End-of-run failed-task sweep: requeue every terminal-failed\n // (non-cancelled) task and run them again, bounded by\n // maxFailedSweeps. Stop early once a sweep yields no new completions\n // (no progress) so a hopeless task can't spin the loop forever.\n const completed = this.opts.tracker.getProgress().completed;\n const madeProgress = this.failedSweeps === 0 || completed > this.lastSweepCompleted;\n if (this.failedSweeps < this.maxFailedSweeps && madeProgress && this.requeueFailedTasks() > 0) {\n this.lastSweepCompleted = completed;\n this.failedSweeps++;\n continue;\n }\n break;\n }\n const chains = this.computeDeadlockChains();\n if (chains.length > 0) {\n this.emit('sdd.deadlock', { runId: this.runId, chains });\n if (this.recoveryRounds < this.maxRecoveryRounds && this.recoverFailedBlockers()) {\n this.recoveryRounds++;\n continue;\n }\n deadlocked = true;\n }\n // No running, no ready, no recoverable deadlock → no further progress.\n break;\n }\n\n // If we still have a free slot AND a ready task, loop to dispatch it now;\n // otherwise wait for any in-flight task to settle (which may unblock more).\n const moreReadyNow =\n running.size < this.slots && this.decomposer.readyNodes().some((t) => !running.has(t.id));\n if (!moreReadyNow) {\n await Promise.race(running.values());\n this.opts.onProgress?.(this.buildProgress());\n }\n }\n\n // Drain any still-running tasks so the run never returns with live workers.\n if (running.size > 0) await Promise.allSettled(running.values());\n\n // Clean teardown on stop: interrupted tasks reset, worktrees released.\n if (this.stopRequested) await this.teardown();\n\n const finalProgress = this.opts.tracker.getProgress();\n\n this.emit('sdd.run.finished', {\n runId: this.runId,\n deadlocked,\n completed: finalProgress.completed,\n failed: finalProgress.failed,\n stopped: this.stopRequested,\n });\n\n return {\n totalWaves: this.round,\n totalCompleted: finalProgress.completed,\n totalFailed: finalProgress.failed,\n totalDurationMs: Date.now() - startTime,\n deadlocked,\n stopRequested: this.stopRequested,\n finalProgress,\n };\n }\n\n /**\n * Compute the blocking chains for a deadlock: every still-incomplete task and\n * the blockers (by node id) that are NOT completed. Failed blockers are\n * included since they're the usual deadlock cause once retries are exhausted.\n */\n private computeDeadlockChains(): Array<{ blocked: string; blockedBy: string[] }> {\n const tracker = this.opts.tracker;\n const chains: Array<{ blocked: string; blockedBy: string[] }> = [];\n for (const node of tracker.getAllNodes()) {\n if (node.status === 'completed' || node.status === 'failed') continue;\n const blockedBy = tracker\n .getBlockers(node.id)\n .filter((id) => tracker.getNode(id)?.status !== 'completed');\n if (blockedBy.length > 0) chains.push({ blocked: node.id, blockedBy });\n }\n return chains;\n }\n\n /** Requeue failed tasks that block an incomplete dependent. Returns true if any. */\n private recoverFailedBlockers(): boolean {\n const tracker = this.opts.tracker;\n let recovered = false;\n for (const node of tracker.getAllNodes({ status: ['failed'] })) {\n const blocksIncomplete = tracker.getDependents(node.id).some((d) => {\n const s = tracker.getNode(d)?.status;\n return s !== 'completed' && s !== 'failed';\n });\n if (blocksIncomplete) {\n this.retryMap.delete(node.id);\n this.persistRetries(node.id, 0);\n tracker.updateNodeStatus(node.id, 'pending', 'deadlock recovery');\n recovered = true;\n }\n }\n return recovered;\n }\n\n /**\n * Requeue every terminal-failed task that the user did NOT cancel, giving each\n * a fresh `maxRetries` budget. Shared by the automatic end-of-run sweep and\n * the manual \"retry all failed\" control. Returns the number requeued.\n */\n private requeueFailedTasks(reason = 'retry failed sweep'): number {\n const tracker = this.opts.tracker;\n let n = 0;\n for (const node of tracker.getAllNodes({ status: ['failed'] })) {\n if (this.cancelledTasks.has(node.id) || node.metadata?.cancelled) continue;\n this.retryMap.delete(node.id);\n this.persistRetries(node.id, 0);\n tracker.updateNodeStatus(node.id, 'pending', reason);\n this.emit('sdd.task.retrying', {\n runId: this.runId,\n taskId: node.id,\n attempt: 0,\n maxRetries: this.maxRetries,\n });\n n++;\n }\n return n;\n }\n\n /**\n * Manually requeue all failed tasks to `pending` (board \"Retry all failed\").\n * Unlike the automatic sweep this also clears any `cancelled` marker, so a\n * user can bring cancelled tasks back in the same action — mirroring\n * `retryTask`. Picked up by the running scheduler on its next dispatch pass.\n * Returns the number of tasks requeued.\n */\n retryAllFailed(): number {\n const failed = this.opts.tracker.getAllNodes({ status: ['failed'] });\n for (const node of failed) {\n this.cancelledTasks.delete(node.id);\n this.opts.tracker.patchMetadata(node.id, { cancelled: undefined });\n }\n return this.requeueFailedTasks('manual retry all');\n }\n\n /** Restore per-task retry counts persisted in node metadata (resume support). */\n private restoreRetryMap(): void {\n this.retryMap.clear();\n for (const node of this.opts.tracker.getAllNodes()) {\n const r = (node.metadata as { retries?: unknown } | undefined)?.retries;\n if (typeof r === 'number' && r > 0) this.retryMap.set(node.id, r);\n }\n }\n\n /**\n * Reset orphaned `in_progress` tasks (no agent runs them after a crash) back\n * to `pending` so a fresh run re-executes them. Call before constructing a run\n * from a reloaded graph. Static so callers don't need a run instance.\n */\n static resetOrphans(tracker: TaskTracker): number {\n let n = 0;\n for (const node of tracker.getAllNodes({ status: ['in_progress'] })) {\n tracker.updateNodeStatus(node.id, 'pending', 'resume: orphaned in_progress');\n n++;\n }\n return n;\n }\n\n /** Clean teardown after a stop: reset interrupted tasks + release worktrees. */\n private async teardown(): Promise<void> {\n for (const node of this.opts.tracker.getAllNodes({ status: ['in_progress'] })) {\n this.opts.tracker.updateNodeStatus(node.id, 'pending', 'run stopped');\n }\n const wt = this.opts.worktrees;\n if (wt) {\n for (const [taskId, handle] of [...this.taskWorktrees]) {\n await wt.release(handle, { keep: true }).catch(() => {});\n this.forgetWorktree(taskId);\n }\n }\n }\n\n // -------------------------------------------------------------------\n // Internal\n // -------------------------------------------------------------------\n\n private buildCoordinator(): void {\n const config: MultiAgentConfig = {\n coordinatorId: `sdd-parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n // Default budget guard for every spawned worker: idle reaper (resets on\n // activity) plus the opt-in wall-clock cap when one was configured. This\n // ensures the reaper applies even if a per-spawn config path is bypassed.\n defaultBudget: {\n idleTimeoutMs: this.idleTimeoutMs,\n ...(this.timeoutMs ? { timeoutMs: this.timeoutMs } : {}),\n },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const baseFactory = this.opts.subagentFactory ?? this.defaultFactory();\n const filteredFactory = withDisabledToolFiltering(baseFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n private defaultFactory(): AgentFactory {\n return async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n });\n }\n\n /**\n * Execute a batch of tasks together. Retained as a thin wrapper over the\n * single-task primitive `executeOne` so the wave-oriented tests and any\n * batch callers keep working; the continuous scheduler in `run()` calls\n * `executeOne` directly. Throws if no coordinator is wired or a spawn fails\n * (surfaced from `executeOne`), preserving the original all-or-nothing contract.\n */\n async executeWave(batch: TaskBatch): Promise<WaveResult> {\n const waveStart = Date.now();\n const outcomes = await Promise.all(batch.tasks.map((task) => this.executeOne(task)));\n const results = outcomes.map((o) => o.result).filter((r): r is TaskResult => Boolean(r));\n const successCount = outcomes.filter((o) => o.success).length;\n const failCount = outcomes.length - successCount;\n return {\n wave: batch.wave,\n batch,\n results,\n successCount,\n failCount,\n durationMs: Date.now() - waveStart,\n stopRequested: this.stopRequested,\n };\n }\n\n /**\n * Execute one task end-to-end: assign a worker identity, allocate its worktree,\n * spawn + assign the subagent, await its result, then update tracker status\n * (success / retry / terminal-fail / cancelled) and resolve the worktree. This\n * is the unit the continuous scheduler dispatches into a free slot. Throws on a\n * missing coordinator or failed spawn so callers can enforce all-or-nothing.\n */\n async executeOne(task: TaskNode): Promise<TaskOutcome> {\n const taskId = task.id;\n\n // Worker identity (reuse a manual assignment if present), shown on the board.\n let agentName = task.assignee;\n if (!agentName) {\n const nick = assignNickname('executor', this.usedNicknames);\n this.usedNicknames.add(nick.key);\n agentName = nick.display.replace(/\\s*\\([^)]*\\)\\s*$/, '');\n this.opts.tracker.updateNode(taskId, { assignee: agentName });\n }\n\n this.opts.tracker.updateNodeStatus(taskId, 'in_progress');\n\n // Per-task git-worktree isolation: a fresh checkout off the current base\n // (which already holds every dependency's merged work).\n await this.allocateWorktrees([task]);\n\n if (!this.coordinator) throw new SddError({\n message: 'SDD parallel runner requires a coordinator',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n const coordinator = this.coordinator;\n\n const subagentId = `sdd-d${this.dispatchSeq++}`;\n const correlationId = randomUUID();\n\n // Per-task model / provider / fallback resolution: the node's own assignment\n // (set per-task in the WebUI) wins, else the run-level default.\n const meta = (task.metadata ?? {}) as Record<string, unknown>;\n const model = (typeof meta.model === 'string' ? meta.model : undefined) ?? this.opts.defaultModel;\n const provider =\n (typeof meta.provider === 'string' ? meta.provider : undefined) ?? this.opts.defaultProvider;\n const fallbackModels = Array.isArray(meta.fallbackModels)\n ? (meta.fallbackModels as string[])\n : this.opts.fallbackModels;\n\n const spawnResult = await coordinator.spawn({\n id: subagentId,\n name: agentName ?? subagentId,\n role: 'executor',\n // Idle reaper is always on; the hard wall-clock cap only when opted in.\n idleTimeoutMs: this.idleTimeoutMs,\n ...(this.timeoutMs ? { timeoutMs: this.timeoutMs } : {}),\n cwd: this.taskCwds.get(taskId),\n disabledTools: ['delegate'],\n ...(model ? { model } : {}),\n ...(provider ? { provider } : {}),\n ...(fallbackModels && fallbackModels.length ? { fallbackModels } : {}),\n });\n if (!spawnResult.subagentId) {\n throw new SddError({\n message: 'One or more subagent spawns failed',\n code: ERROR_CODES.SDD_INVALID_STATE,\n });\n }\n // Record the live subagent so cancelTask() can abort exactly this task.\n this.taskSubagents.set(taskId, subagentId);\n\n this.emit('sdd.task.started', {\n runId: this.runId,\n taskId,\n subagentId,\n agentName: agentName ?? '',\n worktreeBranch: this.taskBranches.get(taskId),\n });\n\n const directivePreamble = [\n '═══ SDD PARALLEL EXECUTION ═══',\n '',\n `Graph: ${this.opts.graph.title}`,\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned SDD task end-to-end using multiple tool calls.',\n '• Mark the task [done] in the tracker when complete.',\n '• Do not ask before routine in-project tool use; if a permission gate appears, wait for that flow.',\n '• Keep output concise — summarize changes, do not transcribe files.',\n ].join('\\n');\n\n await coordinator.assign({\n id: correlationId,\n description: [\n directivePreamble,\n '',\n `── TASK ──`,\n `[${task.priority.toUpperCase()}] ${task.title}`,\n '',\n task.description,\n ].join('\\n'),\n subagentId,\n ...(this.timeoutMs ? { timeoutMs: this.timeoutMs } : {}),\n });\n\n let result: TaskResult;\n try {\n const got = await coordinator.awaitTasks([correlationId]);\n result = expectDefined(got[0]);\n } catch (err) {\n result = {\n subagentId,\n taskId: correlationId,\n status: 'failed',\n error: { kind: 'unknown', message: String(err), retryable: false },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n };\n }\n\n this.taskSubagents.delete(taskId);\n\n // Cancelled mid-flight: cancelTask() already marked the node terminal — don't\n // resurrect it via the retry path. Discard its worktree and report failure.\n if (this.cancelledTasks.has(taskId)) {\n await this.resolveWorktrees([task]);\n return { taskId, success: false, result };\n }\n\n // Completion gate: a worker-reported success is not trusted until the\n // optional verification gate passes. A rejection here is treated exactly\n // like a task failure (retry while attempts remain, else terminal-fail) and\n // — crucially — happens BEFORE the worktree merge, so unverified work never\n // reaches the base branch.\n let verificationFailReason: string | undefined;\n if (result.status === 'success' && this.opts.verifyTask) {\n const cwd = this.taskCwds.get(taskId) ?? this.opts.projectRoot;\n try {\n const verdict = await this.opts.verifyTask({ task, result, cwd });\n if (!verdict.ok) {\n verificationFailReason = `verification failed: ${verdict.reason ?? 'acceptance criteria not met'}`;\n }\n } catch (err) {\n verificationFailReason = `verification error: ${String(err)}`;\n }\n if (verificationFailReason) {\n this.emit('sdd.task.verification_failed', {\n runId: this.runId,\n taskId,\n reason: verificationFailReason,\n });\n }\n }\n\n let success = false;\n if (result.status === 'success' && !verificationFailReason) {\n // Merge gate: only declare 'completed' once this task's worktree integrates\n // cleanly into the base. An unresolved conflict is treated like any other\n // failure (retry on a fresh base, else terminal-fail) so the run never\n // wedges and dependents never build on un-merged work.\n const merged = await this.integrateWorktree(task, result);\n if (merged.ok) {\n success = true;\n this.opts.tracker.updateNodeStatus(taskId, 'completed');\n this.retryMap.delete(taskId);\n this.persistRetries(taskId, 0);\n this.emit('sdd.task.completed', {\n runId: this.runId,\n taskId,\n subagentId,\n durationMs: result.durationMs,\n });\n } else if (merged.reason) {\n // A conflict-resolved merge that regressed re-verification — the squash\n // commit was reverted. Surface it as a verification failure (not a raw\n // conflict) and let the retry path re-run on a fresh base.\n this.emit('sdd.task.verification_failed', {\n runId: this.runId,\n taskId,\n reason: merged.reason,\n });\n await this.applyTaskFailure(taskId, subagentId, merged.reason);\n } else {\n this.emit('sdd.task.conflict', {\n runId: this.runId,\n taskId,\n conflictFiles: merged.conflictFiles ?? [],\n });\n const reason = `merge conflict${merged.conflictFiles?.length ? `: ${merged.conflictFiles.join(', ')}` : ''}`;\n await this.applyTaskFailure(taskId, subagentId, reason);\n }\n } else {\n const errMsg =\n verificationFailReason ??\n (result.error?.kind\n ? `${result.error.kind}: ${result.error.message}`\n : result.error?.message ?? 'unknown error');\n await this.applyTaskFailure(taskId, subagentId, errMsg);\n // Resolve the worktree for the non-success path (failed → keep, retry → discard).\n await this.resolveWorktrees([task]);\n }\n\n return { taskId, success, result };\n }\n\n /**\n * Apply a task failure: retry (→ pending, bump retry count) while attempts\n * remain, else consult the optional supervisor (which can rescue via\n * retry/reassign/split), else terminal-fail (→ failed). Shared by the\n * worker-failure, verification-gate, and merge-conflict paths so all three\n * negotiate the same retry budget and emit the same events.\n */\n private async applyTaskFailure(taskId: string, subagentId: string, errMsg: string): Promise<void> {\n const currentRetries = this.retryMap.get(taskId) ?? 0;\n if (currentRetries < this.maxRetries) {\n this.retryMap.set(taskId, currentRetries + 1);\n this.persistRetries(taskId, currentRetries + 1);\n this.opts.tracker.updateNodeStatus(\n taskId,\n 'pending',\n `Retry ${currentRetries + 1}/${this.maxRetries}: ${errMsg}`,\n );\n this.emit('sdd.task.retrying', {\n runId: this.runId,\n taskId,\n attempt: currentRetries + 1,\n maxRetries: this.maxRetries,\n });\n return;\n }\n\n // Retries exhausted — give the supervisor a bounded chance to rescue the\n // task before it goes terminal, so a run \"decides\" rather than dead-ends.\n if (await this.trySupervisorRescue(taskId, errMsg)) return;\n\n this.opts.tracker.updateNodeStatus(taskId, 'failed', errMsg);\n this.emit('sdd.task.failed', { runId: this.runId, taskId, subagentId, error: errMsg });\n }\n\n /**\n * Consult `superviseFailure` for a task that has exhausted its retries.\n * Applies the verdict (retry / reassign+retry / split) and returns true when\n * the task was rescued (caller must NOT terminal-fail it). Bounded per task by\n * `maxSupervisorEscalations` so an always-\"retry\" supervisor can't loop forever.\n */\n private async trySupervisorRescue(taskId: string, errMsg: string): Promise<boolean> {\n const supervise = this.opts.superviseFailure;\n if (!supervise) return false;\n const used = this.supervisorEscalations.get(taskId) ?? 0;\n if (used >= this.maxSupervisorEscalations) return false;\n const node = this.opts.tracker.getNode(taskId);\n if (!node) return false;\n\n let verdict: SddSupervisorVerdict | undefined;\n try {\n verdict = await supervise({ task: node, error: errMsg, attempts: used });\n } catch {\n return false; // a flaky supervisor must not block terminal failure\n }\n if (!verdict || verdict.action === 'fail') return false;\n\n this.supervisorEscalations.set(taskId, used + 1);\n const requeue = (reason: string) => {\n this.retryMap.delete(taskId);\n this.persistRetries(taskId, 0);\n this.opts.tracker.updateNodeStatus(taskId, 'pending', reason);\n };\n\n if (verdict.action === 'reassign') {\n this.setTaskModel(taskId, verdict.model, verdict.provider);\n requeue(`supervisor reassign: ${verdict.model ?? 'default'}`);\n this.emit('sdd.supervisor.decision', { runId: this.runId, taskId, action: 'reassign' });\n return true;\n }\n if (verdict.action === 'split') {\n const ids = this.splitTask(taskId, verdict.subtasks);\n if (ids.length === 0) return false; // split refused (e.g. running) → let it fail\n this.emit('sdd.supervisor.decision', { runId: this.runId, taskId, action: 'split' });\n return true;\n }\n // 'retry'\n requeue('supervisor retry');\n this.emit('sdd.supervisor.decision', { runId: this.runId, taskId, action: 'retry' });\n return true;\n }\n\n /**\n * Integrate a verified-successful task's worktree into the base branch.\n * Commits, squash-merges (optionally running `conflictResolver` first), and on\n * success releases the worktree. On an UNRESOLVED conflict it returns\n * `{ok:false}` with the conflicting files so the caller routes the task into\n * the failure path (a retry forks a fresh worktree off the now-advanced base,\n * which usually clears the conflict). No-op `{ok:true}` when worktrees are\n * disabled or none was allocated for this task. Never throws — a merge hiccup\n * degrades to a (retryable) failure rather than wedging the run.\n */\n private async integrateWorktree(\n task: TaskNode,\n result?: TaskResult,\n ): Promise<{ ok: boolean; conflictFiles?: string[]; reason?: string }> {\n const wt = this.opts.worktrees;\n if (!wt) return { ok: true };\n const handle = this.taskWorktrees.get(task.id);\n if (!handle) return { ok: true };\n try {\n await wt.commitAll(handle, `sdd(${task.title}): ${task.id}`);\n // Capture the base tip before merging so a regressed conflict-resolution\n // can be reverted to exactly this commit (see the re-verify branch below),\n // and so we can tell whether this merge actually advanced the base (an\n // empty squash creates no commit → nothing to record for rollback).\n const baseShaBefore = await wt.baseHead(handle);\n const baseSha = this.opts.conflictResolver ? baseShaBefore : null;\n const res = await wt.merge(handle, {\n squash: true,\n ...(this.opts.conflictResolver\n ? {\n resolve: (info: { conflictFiles: string[]; cwd: string }) =>\n this.opts.conflictResolver!({ task, conflictFiles: info.conflictFiles, cwd: info.cwd }),\n }\n : {}),\n });\n if (res.ok) {\n // A merge that only landed because the conflictResolver rewrote files is\n // not trusted blindly: re-run the completion gate against the INTEGRATED\n // base. If it regresses, revert the squash commit so the auto-resolution\n // never sticks, and treat the task as a (retryable) failure.\n if (res.resolved && this.opts.verifyTask && baseSha) {\n let regressed: string | undefined;\n try {\n const verdict = await this.opts.verifyTask({\n task,\n result: result ?? ({} as TaskResult),\n cwd: this.opts.projectRoot,\n });\n if (!verdict.ok) regressed = verdict.reason ?? 'verification failed after conflict resolution';\n } catch (err) {\n regressed = `verification error after conflict resolution: ${String(err)}`;\n }\n if (regressed) {\n await wt.revertBaseTo(handle, baseSha).catch(() => {});\n await wt.release(handle, { keep: false }).catch(() => {});\n this.forgetWorktree(task.id, { keepBranchLabel: true });\n return { ok: false, conflictFiles: [], reason: regressed };\n }\n }\n // Record the squash commit for rollback — but only if the merge actually\n // advanced the base tip (an empty/no-op squash leaves it unchanged).\n const baseShaAfter = await wt.baseHead(handle);\n if (baseShaAfter && baseShaAfter !== baseShaBefore) {\n this.mergedCommits.push({ taskId: task.id, sha: baseShaAfter, title: task.title });\n this.emit('sdd.task.merged', { runId: this.runId, taskId: task.id, sha: baseShaAfter });\n }\n await wt.release(handle, { keep: false });\n this.forgetWorktree(task.id);\n return { ok: true };\n }\n // Unresolved conflict: the manager already hard-reset the base and parked\n // the handle as `needs-review` (force-kept for inspection). Drop our handle\n // reference so a retry allocates a fresh worktree off the advanced base.\n await wt.release(handle, { keep: false }).catch(() => {});\n this.forgetWorktree(task.id, { keepBranchLabel: true });\n return { ok: false, conflictFiles: res.conflictFiles ?? [] };\n } catch {\n // Commit/merge hiccup — don't wedge the run; treat as a retryable failure.\n this.forgetWorktree(task.id);\n return { ok: false, conflictFiles: [] };\n }\n }\n\n /** Allocate a fresh git worktree per task in the batch (no-op without a manager). */\n private async allocateWorktrees(tasks: TaskNode[]): Promise<void> {\n const wt = this.opts.worktrees;\n if (!wt) return;\n for (const task of tasks) {\n if (this.taskWorktrees.has(task.id)) continue;\n try {\n const handle = await wt.allocate(`sdd-${task.id}`, {\n slugHint: task.title,\n ownerLabel: task.title,\n });\n if (handle.status === 'active') {\n this.taskWorktrees.set(task.id, handle);\n this.taskCwds.set(task.id, handle.dir);\n this.taskBranches.set(task.id, handle.branch);\n const node = this.opts.tracker.getNode(task.id);\n if (node) node.metadata = { ...node.metadata, worktreeBranch: handle.branch };\n }\n } catch {\n // Allocation failed → this task runs on the shared working tree.\n }\n }\n }\n\n /**\n * Resolve each task's worktree after its result is known. Serialized merges\n * (one at a time) keep the base branch consistent; the wave structure already\n * guarantees dependency order (a task's blockers merged in an earlier wave).\n */\n private async resolveWorktrees(tasks: TaskNode[]): Promise<void> {\n const wt = this.opts.worktrees;\n if (!wt) return;\n for (const task of tasks) {\n const handle = this.taskWorktrees.get(task.id);\n if (!handle) continue;\n const node = this.opts.tracker.getNode(task.id);\n const status = node?.status;\n const cancelled = Boolean(node?.metadata?.cancelled);\n try {\n if (cancelled) {\n // User cancelled → throw away the partial checkout, don't merge it.\n await wt.release(handle, { keep: false });\n this.forgetWorktree(task.id, { keepBranchLabel: false });\n } else if (status === 'completed') {\n await wt.commitAll(handle, `sdd(${task.title}): ${task.id}`);\n await wt.merge(handle, { squash: true });\n await wt.release(handle, { keep: false });\n this.forgetWorktree(task.id);\n } else if (status === 'failed') {\n // Discard the failed checkout so worktrees don't pile up across a run\n // with many failures. (A genuine merge-conflict handle — status\n // 'needs-review'/'failed' — is force-kept by the manager regardless,\n // so conflicts that actually need a human still stay on disk.)\n await wt.release(handle, { keep: false });\n this.forgetWorktree(task.id, { keepBranchLabel: false });\n } else {\n // Pending again (retry) → discard so the next wave starts clean.\n await wt.release(handle, { keep: false });\n this.forgetWorktree(task.id, { keepBranchLabel: false });\n }\n } catch {\n // Merge/release hiccup must not abort the run; leave the handle parked.\n this.forgetWorktree(task.id);\n }\n }\n }\n\n private forgetWorktree(taskId: string, opts: { keepBranchLabel?: boolean } = {}): void {\n this.taskWorktrees.delete(taskId);\n this.taskCwds.delete(taskId);\n if (!opts.keepBranchLabel) this.taskBranches.delete(taskId);\n }\n\n /** Persist a task's retry count into node metadata (survives crash → resume). */\n private persistRetries(taskId: string, retries: number): void {\n const node = this.opts.tracker.getNode(taskId);\n if (node) node.metadata = { ...node.metadata, retries };\n }\n\n private buildProgress(): SddProgress {\n const gp = this.opts.tracker.getProgress();\n const isDeadlocked = !this.decomposer.isDone() &&\n this.decomposer.nextBatch().deadlocked;\n return {\n wave: this.decomposer.getWaveCount(),\n total: gp.total,\n completed: gp.completed,\n inProgress: gp.inProgress,\n failed: gp.failed,\n blocked: gp.blocked,\n pending: gp.pending,\n percent: gp.percentComplete,\n deadlocked: isDeadlocked,\n };\n }\n}\n","// startSddRun — the shared run-setup core for a multi-agent SDD parallel run.\n//\n// Extracted from the CLI `/sdd execute` handler so every surface (CLI slash\n// command + both WebUI servers) starts a run identically: orphan reset →\n// SddParallelRun → live board projector → run registry → cross-process control\n// drain → run, with deterministic cleanup. The only thing that differs per\n// surface is the `subagentFactory` (CLI's director-backed factory vs the\n// runtime light factory) and whether git worktrees are available — both are\n// passed in, keeping this helper free of CLI/host coupling.\n\nimport type { Agent } from '../core/agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { TaskGraph } from '../types/task-graph.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport type { WorktreeManager } from '../worktree/worktree-manager.js';\nimport { SddBoardProjector } from './sdd-board-projector.js';\nimport type { SddBoardStore } from './sdd-board-store.js';\nimport type { SddRunRegistry } from './sdd-run-registry.js';\nimport {\n SddParallelRun,\n type RunResult,\n type SddProgress,\n type SddParallelRunOptions,\n} from './sdd-parallel-run.js';\n\nexport interface StartSddRunOptions {\n tracker: TaskTracker;\n graph: TaskGraph;\n /** Leader agent — seeds the default factory and the run's project context. */\n agent: Agent;\n projectRoot: string;\n events: EventBus;\n /** Per-task agent factory. Omit to run every task on the leader agent. */\n subagentFactory?: AgentFactory | undefined;\n /** Board snapshot/event persistence (also drained for cross-process control). */\n boardStore: SddBoardStore;\n /** Registry the run is registered with for in-process control. */\n registry?: SddRunRegistry | undefined;\n parallelSlots?: number | undefined;\n /** Opt-in hard wall-clock cap per task (ms). Omit → no cap (idle reaper guards). */\n taskTimeoutMs?: number | undefined;\n /** Idle reaper per task (ms); resets on activity. Default 600_000 (10 min). */\n taskIdleTimeoutMs?: number | undefined;\n /** End-of-run failed-task auto-retry sweeps (bounded). Default 2. */\n maxFailedRetrySweeps?: number | undefined;\n /** Post-task verification gate (forwarded to SddParallelRun). Omit → no gate. */\n verifyTask?: SddParallelRunOptions['verifyTask'];\n /** Merge-conflict resolver (forwarded to SddParallelRun). Omit → retry-on-fresh-base then fail. */\n conflictResolver?: SddParallelRunOptions['conflictResolver'];\n /** Failure supervisor (forwarded to SddParallelRun). Omit → no rescue, plain terminal-fail. */\n superviseFailure?: SddParallelRunOptions['superviseFailure'];\n /** Run-level default worker model / provider / fallback chain (task overrides win). */\n defaultModel?: string | undefined;\n defaultProvider?: string | undefined;\n fallbackModels?: string[] | undefined;\n /** Per-task git worktree isolation. Omit → tasks share the working tree. */\n worktrees?: WorktreeManager | undefined;\n /** Bounded deadlock recovery rounds (default 1). */\n maxRecoveryRounds?: number | undefined;\n /** Progress callback (e.g. CLI renderer line). */\n onProgress?: ((p: SddProgress) => void) | undefined;\n /** Control-file drain interval in ms (default 500). */\n controlDrainMs?: number | undefined;\n}\n\nexport interface SddRunHandle {\n run: SddParallelRun;\n runId: string;\n projector: SddBoardProjector;\n /** Resolves when the run finishes AND all teardown (drain/dispose/clear) is done. */\n completion: Promise<RunResult>;\n /** Request a clean stop (idempotent). */\n stop(): void;\n}\n\n/**\n * Wire up and start an SDD parallel run. Returns immediately with a handle whose\n * `completion` promise resolves once the run finishes and teardown is complete.\n * Orphaned in_progress tasks are reset up-front so a crashed prior run re-executes.\n */\nexport function startSddRun(opts: StartSddRunOptions): SddRunHandle {\n // Resume safety: orphaned in_progress tasks (from a prior crash, no agent\n // running them) are reset to pending so the run re-executes them.\n SddParallelRun.resetOrphans(opts.tracker);\n\n const run = new SddParallelRun({\n tracker: opts.tracker,\n graph: opts.graph,\n agent: opts.agent,\n projectRoot: opts.projectRoot,\n parallelSlots: opts.parallelSlots,\n taskTimeoutMs: opts.taskTimeoutMs,\n taskIdleTimeoutMs: opts.taskIdleTimeoutMs,\n maxFailedRetrySweeps: opts.maxFailedRetrySweeps,\n verifyTask: opts.verifyTask,\n conflictResolver: opts.conflictResolver,\n superviseFailure: opts.superviseFailure,\n subagentFactory: opts.subagentFactory,\n events: opts.events,\n worktrees: opts.worktrees,\n maxRecoveryRounds: opts.maxRecoveryRounds ?? 1,\n onProgress: opts.onProgress,\n defaultModel: opts.defaultModel,\n defaultProvider: opts.defaultProvider,\n fallbackModels: opts.fallbackModels,\n });\n\n // Live board projector: streams sdd.board.snapshot + persists JSON/JSONL.\n const projector = new SddBoardProjector({\n runId: run.runId,\n graph: opts.graph,\n tracker: opts.tracker,\n events: opts.events,\n store: opts.boardStore,\n specId: opts.graph.specId,\n defaultModel: opts.defaultModel,\n defaultProvider: opts.defaultProvider,\n fallbackModels: opts.fallbackModels,\n });\n\n opts.registry?.register({\n runId: run.runId,\n specId: opts.graph.specId,\n pause: () => run.pause(),\n resume: () => run.resume(),\n stop: () => run.stop(),\n retryTask: (id) => run.retryTask(id),\n retryAllFailed: () => run.retryAllFailed(),\n reassignTask: (id, name) => run.reassignTask(id, name),\n setTaskModel: (id, model, provider) => run.setTaskModel(id, model, provider),\n setTaskFallbacks: (id, fb) => run.setTaskFallbacks(id, fb),\n setTaskVerification: (id, cmd) => run.setTaskVerification(id, cmd),\n cancelTask: (id) => run.cancelTask(id),\n deleteTask: (id) => run.deleteTask(id),\n splitTask: (id, subtasks) => run.splitTask(id, subtasks),\n cleanupWorktrees: () => run.cleanupWorktrees(),\n rollback: () => run.rollback(),\n getBaseBranch: () => run.getBaseBranch(),\n getMergedCommits: () => run.getMergedCommits(),\n snapshot: () => projector.snapshot(),\n isRunning: () => run.isRunning(),\n });\n\n // Cross-process control channel: any board surface (e.g. the standalone webui\n // in another process) appends a command to <runId>.control.jsonl; we drain +\n // apply it here so this run stays the single driver.\n const drainMs = opts.controlDrainMs ?? 500;\n const controlTimer = setInterval(() => {\n void opts.boardStore.drainControl(run.runId).then((cmds) => {\n for (const c of cmds) {\n const p = (c.payload ?? {}) as {\n taskId?: string;\n agentName?: string;\n model?: string;\n provider?: string;\n fallbackModels?: string[];\n verificationCommand?: string;\n subtasks?: import('./sdd-parallel-run.js').SddSubtaskSpec[];\n };\n if (c.type === 'pause') run.pause();\n else if (c.type === 'resume') run.resume();\n else if (c.type === 'stop') run.stop();\n else if (c.type === 'retry' && p.taskId) run.retryTask(p.taskId);\n else if (c.type === 'retry_all_failed') run.retryAllFailed();\n else if (c.type === 'reassign' && p.taskId) run.reassignTask(p.taskId, p.agentName ?? '');\n else if (c.type === 'set_task_model' && p.taskId) run.setTaskModel(p.taskId, p.model, p.provider);\n else if (c.type === 'set_task_fallbacks' && p.taskId) run.setTaskFallbacks(p.taskId, p.fallbackModels);\n else if (c.type === 'set_task_verification' && p.taskId)\n run.setTaskVerification(p.taskId, p.verificationCommand);\n else if (c.type === 'cancel_task' && p.taskId) void run.cancelTask(p.taskId);\n else if (c.type === 'delete_task' && p.taskId) run.deleteTask(p.taskId);\n else if (c.type === 'split_task' && p.taskId && p.subtasks?.length) run.splitTask(p.taskId, p.subtasks);\n // Lifecycle: stop the run first, then sweep worktrees / revert commits.\n // (Both are no-ops while the run is still live — the user pairs them with\n // a prior `stop`.)\n else if (c.type === 'cleanup_worktrees') void run.cleanupWorktrees();\n else if (c.type === 'rollback') void run.rollback();\n }\n });\n }, drainMs);\n // Best-effort: don't keep the event loop alive solely for the drain timer.\n (controlTimer as { unref?: () => void }).unref?.();\n\n const completion = (async (): Promise<RunResult> => {\n try {\n return await run.run();\n } finally {\n clearInterval(controlTimer);\n await projector.drain().catch(() => {});\n projector.dispose();\n opts.registry?.clear(run.runId);\n }\n })();\n\n return {\n run,\n runId: run.runId,\n projector,\n completion,\n stop: () => run.stop(),\n };\n}\n","import { spawn } from 'node:child_process';\nimport { mkdir } from 'node:fs/promises';\nimport { join, resolve, sep } from 'node:path';\nimport type { EventBus } from '../kernel/events.js';\nimport { buildChildEnv } from '../utils/child-env.js';\nimport { toErrorMessage } from '../utils/error.js';\n\n/**\n * Lifecycle of a single worktree handle.\n *\n * allocating → active → committing → merging → merged\n * └─→ needs-review (conflict, kept)\n * (any) → failed\n */\nexport type WorktreeStatus =\n | 'allocating'\n | 'active'\n | 'committing'\n | 'merging'\n | 'merged'\n | 'needs-review'\n | 'failed';\n\nexport interface WorktreeHandle {\n /** Stable id (== slug). Used as the event `handleId`. */\n id: string;\n /** Caller-supplied owner (a phase id in AutoPhase). */\n ownerId: string;\n /** Human label for the owner (phase name). */\n ownerLabel: string;\n slug: string;\n /** Absolute path to the worktree checkout. */\n dir: string;\n /** Branch checked out in the worktree (`wstack/ap/<slug>`). */\n branch: string;\n /** Branch the worktree was forked from and merges back into. */\n baseBranch: string;\n status: WorktreeStatus;\n createdAt: number;\n updatedAt: number;\n /** Diff stats from the last commit. */\n insertions: number;\n deletions: number;\n files: number;\n sha?: string | undefined;\n lastError?: string | undefined;\n conflictFiles?: string[] | undefined;\n}\n\nexport interface AllocateOpts {\n /** Friendly basis for the slug/branch (e.g. the phase name). */\n slugHint?: string | undefined;\n ownerLabel?: string | undefined;\n /** Override the detected base branch. */\n baseBranch?: string | undefined;\n}\n\nexport interface MergeOpts {\n squash?: boolean | undefined;\n message?: string | undefined;\n /**\n * Optional conflict resolver. Invoked when the squash-merge conflicts, with\n * the conflicted paths and the base working tree (`cwd`). It must resolve the\n * conflict markers in place and return `true` when done. If it returns `true`\n * and no conflict markers remain, the merge is committed and `merge()` returns\n * `{ ok: true, resolved: true }`. Otherwise the merge is aborted (hard reset)\n * and the handle is parked `needs-review` — exactly as if no resolver were\n * provided, so the base tree is never left dirty.\n */\n resolve?: (info: { conflictFiles: string[]; cwd: string }) => Promise<boolean>;\n}\n\nexport interface MergeResult {\n ok: boolean;\n conflict?: boolean | undefined;\n conflictFiles?: string[] | undefined;\n stderr?: string | undefined;\n /** True when an initial conflict was successfully resolved by `opts.resolve`. */\n resolved?: boolean | undefined;\n}\n\nexport interface RunResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface WorktreeManagerOptions {\n projectRoot: string;\n events?: EventBus | undefined;\n gitBin?: string | undefined;\n /**\n * Test seam. When provided, replaces the real `git` spawn so the manager's\n * sequencing/arg vectors can be asserted without touching a repo.\n */\n run?: (args: string[], cwd: string) => Promise<RunResult>;\n}\n\nconst MAX_SLUG = 40;\n\n/**\n * Owns the git-worktree lifecycle for isolated, parallel work units. Shells out\n * to `git` directly (never via the `git` *tool*) so it can target arbitrary\n * worktree directories without the tool's permission gate or `findGitDir`\n * resolution, and so `@wrongstack/core` keeps no dependency on `@wrongstack/tools`.\n */\nexport class WorktreeManager {\n private readonly projectRoot: string;\n private readonly events?: EventBus | undefined;\n private readonly gitBin: string;\n private readonly runGit: (args: string[], cwd: string) => Promise<RunResult>;\n /** Keyed by ownerId. */\n private readonly handles = new Map<string, WorktreeHandle>();\n private readonly usedSlugs = new Set<string>();\n\n constructor(opts: WorktreeManagerOptions) {\n this.projectRoot = resolve(opts.projectRoot);\n this.events = opts.events;\n this.gitBin = opts.gitBin ?? 'git';\n this.runGit = opts.run ?? ((args, cwd) => this.defaultRun(args, cwd));\n }\n\n /** Create a fresh worktree + branch forked from the current base branch. */\n async allocate(ownerId: string, opts: AllocateOpts = {}): Promise<WorktreeHandle> {\n const existing = this.handles.get(ownerId);\n if (existing && (existing.status === 'allocating' || existing.status === 'active')) {\n return existing;\n }\n\n const slug = this.makeSlug(opts.slugHint ?? ownerId);\n const branch = `wstack/ap/${slug}`;\n const dir = join(this.worktreesRoot(), slug);\n // Guard: slug is generated by makeSlug() which strips non-alphanumeric\n // chars, but double-check the dir resolves inside projectRoot so a\n // malicious slugHint with path traversal can't escape the worktrees dir.\n const absDir = resolve(dir);\n const absRoot = resolve(this.projectRoot);\n if (!absDir.startsWith(absRoot + sep)) {\n throw new Error(`Worktree dir \"${absDir}\" resolves outside project root`);\n }\n\n const baseBranch = opts.baseBranch ?? (await this.detectBaseBranch());\n\n const handle: WorktreeHandle = {\n id: slug,\n ownerId,\n ownerLabel: opts.ownerLabel ?? opts.slugHint ?? ownerId,\n slug,\n dir,\n branch,\n baseBranch,\n status: 'allocating',\n createdAt: Date.now(),\n updatedAt: Date.now(),\n insertions: 0,\n deletions: 0,\n files: 0,\n };\n this.handles.set(ownerId, handle);\n\n try {\n await mkdir(this.worktreesRoot(), { recursive: true });\n // git worktree add -b <branch> <path> <base> — path before commit-ish.\n const res = await this.runGit(\n ['worktree', 'add', '-b', branch, dir, baseBranch],\n this.projectRoot,\n );\n if (res.code !== 0) {\n return this.fail(handle, res.stderr || 'git worktree add failed');\n }\n } catch (err) {\n return this.fail(handle, toErrorMessage(err));\n }\n\n this.setStatus(handle, 'active');\n this.emit('worktree.allocated', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n ownerLabel: handle.ownerLabel,\n slug: handle.slug,\n dir: handle.dir,\n branch: handle.branch,\n baseBranch: handle.baseBranch,\n });\n return handle;\n }\n\n /** Stage everything and commit inside the worktree. */\n async commitAll(handle: WorktreeHandle, message: string): Promise<{ committed: boolean }> {\n this.setStatus(handle, 'committing');\n await this.runGit(['add', '-A'], handle.dir);\n\n // `diff --cached --quiet` exits 1 when there are staged changes, 0 when none.\n const staged = await this.runGit(['diff', '--cached', '--quiet'], handle.dir);\n if (staged.code === 0) {\n this.emitCommitted(handle, false);\n return { committed: false };\n }\n\n const idArgs = await this.identityArgs(handle.dir);\n const committed = await this.runGit([...idArgs, 'commit', '-m', message], handle.dir);\n if (committed.code !== 0) {\n this.fail(handle, committed.stderr || 'git commit failed');\n return { committed: false };\n }\n\n const stats = await this.collectStats(handle.dir);\n handle.insertions = stats.insertions;\n handle.deletions = stats.deletions;\n handle.files = stats.files;\n handle.sha = stats.sha;\n handle.updatedAt = Date.now();\n this.emitCommitted(handle, true);\n return { committed: true };\n }\n\n /** Merge the worktree branch back into the base branch (squash by default). */\n async merge(handle: WorktreeHandle, opts: MergeOpts = {}): Promise<MergeResult> {\n const squash = opts.squash ?? true;\n this.setStatus(handle, 'merging');\n\n const checkout = await this.runGit(['checkout', handle.baseBranch], this.projectRoot);\n if (checkout.code !== 0) {\n this.fail(handle, checkout.stderr || `checkout ${handle.baseBranch} failed`);\n return { ok: false, stderr: checkout.stderr };\n }\n\n const mergeArgs = squash\n ? ['merge', '--squash', handle.branch]\n : ['merge', '--no-ff', handle.branch];\n const merged = await this.runGit(mergeArgs, this.projectRoot);\n\n if (merged.code !== 0) {\n // Prefer the conflicted paths git prints to stdout (\"CONFLICT (...):\n // Merge conflict in <path>\") — deterministic across platforms — and\n // union with the index probe, since `git diff --diff-filter=U` can come\n // back empty on some runners after a `--squash` conflict.\n const fromOutput = parseConflictPaths(`${merged.stdout}\\n${merged.stderr}`);\n const fromIndex = await this.unmergedFiles();\n const conflictFiles = [...new Set([...fromOutput, ...fromIndex])];\n\n // Caller-driven resolution: leave the conflicted tree in place, hand the\n // marked files to the resolver, and finalize the merge commit only if it\n // cleared every marker. Any failure falls through to the safe reset below,\n // so the base tree is never left dirty.\n if (opts.resolve) {\n const finalized = await this.tryResolveConflict(handle, conflictFiles, opts);\n if (finalized) return finalized;\n }\n\n // `merge --squash` leaves no MERGE_HEAD, so `merge --abort` won't work;\n // hard-reset the base tree — the work is safe on the branch.\n await this.runGit(['reset', '--hard', 'HEAD'], this.projectRoot);\n handle.conflictFiles = conflictFiles;\n this.setStatus(handle, 'needs-review', { lastError: merged.stderr });\n this.emit('worktree.conflict', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n conflictFiles,\n });\n return { ok: false, conflict: true, conflictFiles, stderr: merged.stderr };\n }\n\n if (squash) {\n // --squash stages the changes but does not commit; finish the commit.\n const msg = opts.message ?? `merge ${handle.branch} (squash)`;\n const idArgs = await this.identityArgs(this.projectRoot);\n const commit = await this.runGit([...idArgs, 'commit', '-m', msg], this.projectRoot);\n // A no-op squash (empty diff) returns nonzero \"nothing to commit\" — fine.\n if (commit.code !== 0 && !/nothing to commit/i.test(commit.stdout + commit.stderr)) {\n this.fail(handle, commit.stderr || 'squash commit failed');\n return { ok: false, stderr: commit.stderr };\n }\n }\n\n this.setStatus(handle, 'merged');\n this.emit('worktree.merged', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n baseBranch: handle.baseBranch,\n squash,\n });\n return { ok: true };\n }\n\n /**\n * Current tip SHA of a handle's base branch (without checking it out). Capture\n * this before a merge so a regressed merge can be reverted to exactly this\n * commit — unambiguous even when a squash produced no diff. Returns null on\n * failure (caller then skips the revert).\n */\n async baseHead(handle: WorktreeHandle): Promise<string | null> {\n const res = await this.runGit(['rev-parse', handle.baseBranch], this.projectRoot);\n const sha = res.stdout.trim();\n return res.code === 0 && sha ? sha : null;\n }\n\n /**\n * Hard-reset the base branch back to `sha` (a value previously returned by\n * {@link baseHead}). Used to undo a squash-merge whose integrated result failed\n * re-verification, so an auto-resolved-but-broken merge never sticks on base.\n * Safe because SDD merges are serialized — no other commit lands in between.\n */\n async revertBaseTo(handle: WorktreeHandle, sha: string): Promise<boolean> {\n const co = await this.runGit(['checkout', handle.baseBranch], this.projectRoot);\n if (co.code !== 0) return false;\n const reset = await this.runGit(['reset', '--hard', sha], this.projectRoot);\n return reset.code === 0;\n }\n\n /**\n * Current base branch + tip SHA, captured WITHOUT a handle. The SDD run calls\n * this once at start so a later rollback knows which branch the run's squash\n * commits landed on. Returns null when not in a usable git state.\n */\n async currentBase(): Promise<{ branch: string; sha: string } | null> {\n const branch = await this.detectBaseBranch();\n const head = await this.runGit(['rev-parse', 'HEAD'], this.projectRoot);\n const sha = head.stdout.trim();\n return head.code === 0 && sha ? { branch, sha } : null;\n }\n\n /**\n * Force-remove EVERY managed worktree + branch this project owns, without\n * relying on the in-memory `handles` map — so it works post-run (a fresh\n * manager can clean up a previous run's leftovers). Enumerates\n * `git worktree list --porcelain`, removes every checkout living under the\n * `.wrongstack/worktrees` root, deletes every `wstack/ap/*` branch, then prunes.\n * Returns the number of worktrees removed. Never throws — best-effort cleanup.\n */\n async cleanupAllManaged(): Promise<{ removed: number }> {\n const root = resolve(this.worktreesRoot());\n let removed = 0;\n try {\n const listed = await this.runGit(['worktree', 'list', '--porcelain'], this.projectRoot);\n // Porcelain emits a `worktree <abs-path>` line per checkout (blank-line\n // separated records). Match the ones under our worktrees root.\n for (const line of listed.stdout.split('\\n')) {\n const m = line.match(/^worktree\\s+(.+?)\\s*$/);\n if (!m?.[1]) continue;\n const dir = resolve(m[1]);\n if (dir !== root && (dir === root || dir.startsWith(root + sep))) {\n const rm = await this.runGit(['worktree', 'remove', '--force', dir], this.projectRoot);\n if (rm.code === 0) removed++;\n }\n }\n } catch {\n // best-effort\n }\n // Delete every wstack/ap/* branch (covers branches whose worktree was already\n // gone, e.g. a merged task whose checkout was released but branch lingered).\n try {\n const branches = await this.runGit(\n ['branch', '--list', '--format=%(refname:short)', 'wstack/ap/*'],\n this.projectRoot,\n );\n for (const b of branches.stdout.split('\\n').map((s) => s.trim()).filter(Boolean)) {\n await this.runGit(['branch', '-D', b], this.projectRoot);\n }\n } catch {\n // best-effort\n }\n await this.runGit(['worktree', 'prune'], this.projectRoot).catch(() => undefined);\n // Drop any in-memory handles too, so a still-live manager forgets them.\n this.handles.clear();\n this.emit('worktree.released', {\n handleId: 'cleanup-all',\n ownerId: 'cleanup-all',\n branch: 'wstack/ap/*',\n kept: false,\n });\n return { removed };\n }\n\n /**\n * Undo a run's squash commits by reverting each (newest → oldest) on the base\n * branch — history-preserving, never a destructive reset. Refuses on a dirty\n * working tree (so uncommitted work is never clobbered) and aborts cleanly if a\n * revert conflicts, reporting which SHA. `shas` are the run commit SHAs in the\n * order they landed; this reverses them. Returns the count reverted.\n */\n async revertCommits(\n baseBranch: string,\n shas: string[],\n ): Promise<{ ok: boolean; reverted: number; reason?: string }> {\n if (shas.length === 0) return { ok: true, reverted: 0, reason: 'nothing to revert' };\n\n const status = await this.runGit(['status', '--porcelain'], this.projectRoot);\n if (status.stdout.trim().length > 0) {\n return { ok: false, reverted: 0, reason: 'working tree has uncommitted changes — commit or stash first' };\n }\n\n const co = await this.runGit(['checkout', baseBranch], this.projectRoot);\n if (co.code !== 0) {\n return { ok: false, reverted: 0, reason: co.stderr || `checkout ${baseBranch} failed` };\n }\n\n const idArgs = await this.identityArgs(this.projectRoot);\n let reverted = 0;\n // Newest commit first so each revert applies cleanly on top of the prior one.\n for (const sha of [...shas].reverse()) {\n const res = await this.runGit([...idArgs, 'revert', '--no-edit', sha], this.projectRoot);\n if (res.code !== 0) {\n // Conflict or bad ref — abort the in-progress revert so the tree is clean.\n await this.runGit(['revert', '--abort'], this.projectRoot).catch(() => undefined);\n return {\n ok: false,\n reverted,\n reason: `revert of ${sha.slice(0, 8)} failed: ${(res.stderr || res.stdout).trim().split('\\n')[0] ?? 'conflict'}`,\n };\n }\n reverted++;\n }\n return { ok: true, reverted };\n }\n\n /**\n * Run the caller-supplied resolver against a conflicted squash-merge, then\n * commit if it cleared every marker. Returns a successful `MergeResult` on a\n * clean resolution, or `null` to signal the caller should fall back to the\n * abort path. Never leaves the base tree committed-but-dirty: a partial or\n * failed resolution returns `null` and the caller hard-resets.\n */\n private async tryResolveConflict(\n handle: WorktreeHandle,\n conflictFiles: string[],\n opts: MergeOpts,\n ): Promise<MergeResult | null> {\n let resolved = false;\n try {\n resolved = opts.resolve ? await opts.resolve({ conflictFiles, cwd: this.projectRoot }) : false;\n } catch {\n resolved = false;\n }\n if (!resolved) return null;\n\n // Stage the resolver's edits, then refuse to commit if any conflict marker\n // survived (a half-resolved file is worse than a clean abort).\n await this.runGit(['add', '-A'], this.projectRoot);\n if (await this.hasConflictMarkers()) return null;\n\n const idArgs = await this.identityArgs(this.projectRoot);\n const msg = opts.message ?? `merge ${handle.branch} (squash, conflict resolved)`;\n const commit = await this.runGit([...idArgs, 'commit', '-m', msg], this.projectRoot);\n if (commit.code !== 0 && !/nothing to commit/i.test(commit.stdout + commit.stderr)) {\n return null;\n }\n\n handle.conflictFiles = conflictFiles;\n this.setStatus(handle, 'merged');\n this.emit('worktree.merged', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n baseBranch: handle.baseBranch,\n squash: true,\n });\n return { ok: true, resolved: true, conflictFiles };\n }\n\n /**\n * True when staged content still carries conflict markers. `git diff --cached\n * --check` exits nonzero and prints a \"leftover conflict marker\" line for each\n * survivor; whitespace-only errors (also flagged by --check) are ignored so a\n * clean resolution with unrelated whitespace is not rejected.\n */\n private async hasConflictMarkers(): Promise<boolean> {\n const check = await this.runGit(['diff', '--cached', '--check'], this.projectRoot);\n if (check.code === 0) return false;\n return /conflict marker/i.test(`${check.stdout}\\n${check.stderr}`);\n }\n\n /**\n * Remove the worktree + branch. Conflicted/failed handles (or `keep:true`)\n * are left on disk for inspection.\n */\n async release(handle: WorktreeHandle, opts: { keep?: boolean | undefined } = {}): Promise<void> {\n const keep = opts.keep || handle.status === 'needs-review' || handle.status === 'failed';\n if (!keep) {\n await this.runGit(['worktree', 'remove', '--force', handle.dir], this.projectRoot);\n await this.runGit(['branch', '-D', handle.branch], this.projectRoot);\n await this.runGit(['worktree', 'prune'], this.projectRoot);\n this.handles.delete(handle.ownerId);\n }\n this.emit('worktree.released', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n kept: keep,\n });\n }\n\n get(ownerId: string): WorktreeHandle | undefined {\n return this.handles.get(ownerId);\n }\n\n list(): WorktreeHandle[] {\n return [...this.handles.values()];\n }\n\n // ── internals ────────────────────────────────────────────────────────────\n\n private worktreesRoot(): string {\n return join(this.projectRoot, '.wrongstack', 'worktrees');\n }\n\n private async detectBaseBranch(): Promise<string> {\n const head = await this.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], this.projectRoot);\n const name = head.stdout.trim();\n if (name && name !== 'HEAD') return name;\n // Detached HEAD — fall back to the commit SHA.\n const sha = await this.runGit(['rev-parse', 'HEAD'], this.projectRoot);\n return sha.stdout.trim() || 'HEAD';\n }\n\n private makeSlug(hint: string): string {\n let base = hint\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^[-.]+/, '')\n .replace(/[-.]+$/, '')\n .slice(0, MAX_SLUG)\n .replace(/[-.]+$/, '');\n if (!base) base = 'wt';\n let slug = `${base}-${crypto.randomUUID().slice(0, 6)}`;\n while (this.usedSlugs.has(slug)) slug = `${base}-${crypto.randomUUID().slice(0, 6)}`;\n this.usedSlugs.add(slug);\n return slug;\n }\n\n private async collectStats(\n dir: string,\n ): Promise<{ insertions: number; deletions: number; files: number; sha: string }> {\n const sha = (await this.runGit(['rev-parse', 'HEAD'], dir)).stdout.trim();\n const numstat = await this.runGit(['show', '--numstat', '--format=', 'HEAD'], dir);\n let insertions = 0;\n let deletions = 0;\n let files = 0;\n for (const line of numstat.stdout.split('\\n')) {\n const m = line.trim().match(/^(\\d+|-)\\t(\\d+|-)\\t(.+)$/);\n if (!m) continue;\n files++;\n if (m[1] !== '-') insertions += Number(m[1]);\n if (m[2] !== '-') deletions += Number(m[2]);\n }\n return { insertions, deletions, files, sha };\n }\n\n /**\n * `git -c user.*` fallback so commits succeed on machines and CI runners\n * that have no global git identity configured. Returns `[]` when both\n * `user.name` and `user.email` are already set (the common case), so a real\n * user's identity is never overridden. The worktree branch commits are\n * squashed away on merge, so the fallback identity never reaches the base\n * branch history.\n */\n private async identityArgs(cwd: string): Promise<string[]> {\n const name = (await this.runGit(['config', 'user.name'], cwd)).stdout.trim();\n const email = (await this.runGit(['config', 'user.email'], cwd)).stdout.trim();\n if (name && email) return [];\n return [\n '-c',\n `user.name=${name || 'AutoPhase'}`,\n '-c',\n `user.email=${email || 'autophase@agent.local'}`,\n ];\n }\n\n private async unmergedFiles(): Promise<string[]> {\n const res = await this.runGit(['diff', '--name-only', '--diff-filter=U'], this.projectRoot);\n return res.stdout\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean);\n }\n\n private emitCommitted(handle: WorktreeHandle, committed: boolean): void {\n this.emit('worktree.committed', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n committed,\n insertions: handle.insertions,\n deletions: handle.deletions,\n files: handle.files,\n sha: handle.sha,\n });\n }\n\n private fail(handle: WorktreeHandle, error: string): WorktreeHandle {\n this.setStatus(handle, 'failed', { lastError: error });\n this.emit('worktree.failed', {\n handleId: handle.id,\n ownerId: handle.ownerId,\n branch: handle.branch,\n error,\n });\n return handle;\n }\n\n private setStatus(\n handle: WorktreeHandle,\n status: WorktreeStatus,\n patch?: Partial<WorktreeHandle> | undefined,\n ): void {\n handle.status = status;\n handle.updatedAt = Date.now();\n if (patch) Object.assign(handle, patch);\n }\n\n private emit<E extends Parameters<EventBus['emit']>[0]>(\n event: E,\n payload: Parameters<EventBus['emit']>[1],\n ): void {\n this.events?.emit(event, payload as never);\n }\n\n private defaultRun(args: string[], cwd: string): Promise<RunResult> {\n return new Promise((res) => {\n let stdout = '';\n let stderr = '';\n // Bound the captured output — a merge/status against a huge worktree\n // can emit MBs that nothing reads in full (parseConflictPaths only\n // scans for CONFLICT lines). 1 MB matches grep.ts's buffer cap.\n const MAX_GIT_OUTPUT = 1_000_000;\n const child = spawn(this.gitBin, args, {\n cwd,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n signal: AbortSignal.timeout(30_000),\n windowsHide: true,\n });\n child.stdout?.on('data', (c: Buffer) => {\n if (stdout.length < MAX_GIT_OUTPUT) stdout += c.toString();\n });\n child.stderr?.on('data', (c: Buffer) => {\n if (stderr.length < MAX_GIT_OUTPUT) stderr += c.toString();\n });\n child.on('error', (err) => res({ code: 1, stdout, stderr: err.message }));\n child.on('close', (code) => res({ code: code ?? 1, stdout, stderr }));\n });\n }\n}\n\n/**\n * Extract conflicted paths from git merge output. Git prints one\n * `CONFLICT (<kind>): Merge conflict in <path>` line per conflicted file to\n * stdout — a portable signal that doesn't depend on the post-merge index\n * state (which `git diff --diff-filter=U` can report as empty on some runners\n * after a `--squash` conflict).\n */\nexport function parseConflictPaths(output: string): string[] {\n const paths = new Set<string>();\n for (const line of output.split('\\n')) {\n const m = line.match(/^CONFLICT \\([^)]*\\): Merge conflict in (.+?)\\s*$/);\n if (m?.[1]) paths.add(m[1]);\n }\n return [...paths];\n}\n\n/** Throw if `dir` resolves outside `projectRoot`. */\nexport function assertSafePath(dir: string, projectRoot: string): void {\n const root = resolve(projectRoot);\n const abs = resolve(dir);\n if (abs !== root && !abs.startsWith(root + sep)) {\n throw new Error(`worktree path escapes project root: ${dir}`);\n }\n}\n","// SDD run lifecycle — post-run, disk-level operations.\n//\n// While a run is live, the in-process `SddRunControl` (registered in\n// `SddRunRegistry`) owns stop / cleanup / rollback. Once a run finishes the\n// registry is cleared and its `WorktreeManager` is gone, so these helpers\n// re-derive everything from disk: a fresh `WorktreeManager` for git surgery and\n// the persisted board snapshot for the run's base branch + merged commits.\n//\n// Used by the CLI/WebUI when there is no active run (e.g. `/sdd rollback` after\n// the run already settled, or `/sdd destroy` to wipe the project).\n\nimport * as fsp from 'node:fs/promises';\nimport { WorktreeManager } from '../worktree/worktree-manager.js';\nimport { SddBoardStore } from './sdd-board-store.js';\n\n/** Force-remove every git worktree + branch a previous run left behind. */\nexport async function cleanupSddWorktrees(projectRoot: string): Promise<{ removed: number }> {\n const wt = new WorktreeManager({ projectRoot });\n return wt.cleanupAllManaged();\n}\n\nexport interface RollbackFromDiskOptions {\n projectRoot: string;\n /** Directory holding persisted board snapshots (`wpaths.projectSddBoards`). */\n boardsDir: string;\n /** Specific run to roll back. Omit → the most recently updated board. */\n runId?: string | undefined;\n}\n\n/**\n * Roll back a finished run's merged commits by reading its persisted board\n * snapshot (base branch + commit SHAs) and reverting each. History-preserving;\n * refuses on a dirty tree or revert conflict (surfaced in `reason`). Returns\n * `ok:false` with a reason when there is no board, no base branch, or nothing to\n * revert.\n */\nexport async function rollbackSddRunFromDisk(\n opts: RollbackFromDiskOptions,\n): Promise<{ ok: boolean; reverted: number; reason?: string }> {\n const store = new SddBoardStore({ baseDir: opts.boardsDir });\n const runId = opts.runId ?? (await store.list())[0]?.runId;\n if (!runId) return { ok: false, reverted: 0, reason: 'no SDD board found to roll back' };\n\n const snap = await store.load(runId);\n if (!snap) return { ok: false, reverted: 0, reason: `board \"${runId}\" not found` };\n if (!snap.baseBranch) {\n return { ok: false, reverted: 0, reason: 'this run did not record a base branch (no worktree run)' };\n }\n const shas = (snap.mergedCommits ?? []).map((c) => c.sha);\n if (shas.length === 0) {\n return { ok: false, reverted: 0, reason: 'no merged commits recorded for this run' };\n }\n\n const wt = new WorktreeManager({ projectRoot: opts.projectRoot });\n return wt.revertCommits(snap.baseBranch, shas);\n}\n\nexport interface DestroySddProjectOptions {\n projectRoot: string;\n /** Resolved wstack paths to delete. */\n paths: {\n projectSpecs: string;\n projectTaskGraphs: string;\n projectSddSession: string;\n projectSddBoards: string;\n };\n}\n\nexport interface DestroySddProjectResult {\n worktreesRemoved: number;\n /** Human labels of the artifacts that were deleted. */\n deleted: string[];\n}\n\n/**\n * Destroy an SDD project: clean every worktree + branch, then delete the on-disk\n * artifacts (specs, task-graphs, session, boards). Does NOT roll back git commits\n * — that is the separate, explicit `rollbackSddRunFromDisk`. Best-effort: a\n * missing path is simply skipped. The caller is responsible for stopping any\n * active run first.\n */\nexport async function destroySddProject(\n opts: DestroySddProjectOptions,\n): Promise<DestroySddProjectResult> {\n const { removed } = await cleanupSddWorktrees(opts.projectRoot).catch(() => ({ removed: 0 }));\n const deleted: string[] = [];\n\n const rmDir = async (dir: string, label: string) => {\n try {\n await fsp.rm(dir, { recursive: true, force: true });\n deleted.push(label);\n } catch {\n // already gone\n }\n };\n const rmFile = async (file: string, label: string) => {\n try {\n await fsp.unlink(file);\n deleted.push(label);\n } catch {\n // already gone\n }\n };\n\n await rmFile(opts.paths.projectSddSession, 'session');\n await rmDir(opts.paths.projectSpecs, 'specs');\n await rmDir(opts.paths.projectTaskGraphs, 'task-graphs');\n await rmDir(opts.paths.projectSddBoards, 'boards');\n\n return { worktreesRemoved: removed, deleted };\n}\n","import type { SpecTemplate } from '../types/spec.js';\n\n/**\n * Built-in spec templates for common development scenarios.\n */\nexport const SPEC_TEMPLATES: SpecTemplate[] = [\n {\n id: 'feature',\n name: 'New Feature',\n description: 'Template for new feature development',\n sections: [\n { type: 'overview', title: 'Overview', level: 2 },\n { type: 'requirements', title: 'Requirements', level: 2 },\n { type: 'architecture', title: 'Architecture', level: 2 },\n { type: 'api', title: 'API Design', level: 2 },\n { type: 'data', title: 'Data Model', level: 2 },\n { type: 'security', title: 'Security', level: 2 },\n { type: 'acceptance', title: 'Acceptance Criteria', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'non-functional', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'bugfix',\n name: 'Bug Fix',\n description: 'Template for bug fix specifications',\n sections: [\n { type: 'overview', title: 'Bug Description', level: 2 },\n { type: 'requirements', title: 'Root Cause Analysis', level: 2 },\n { type: 'acceptance', title: 'Fix Verification', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'critical', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'refactor',\n name: 'Refactor',\n description: 'Template for code refactoring',\n sections: [\n { type: 'overview', title: 'Current State', level: 2 },\n { type: 'requirements', title: 'Refactoring Goals', level: 2 },\n { type: 'architecture', title: 'Target Architecture', level: 2 },\n { type: 'acceptance', title: 'Verification', level: 2 },\n ],\n defaultRequirements: [\n { type: 'non-functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'infra',\n name: 'Infrastructure',\n description: 'Template for infrastructure/tooling changes',\n sections: [\n { type: 'overview', title: 'What and Why', level: 2 },\n { type: 'requirements', title: 'Requirements', level: 2 },\n { type: 'architecture', title: 'Design', level: 2 },\n { type: 'security', title: 'Security Impact', level: 2 },\n { type: 'acceptance', title: 'Rollout Plan', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'security', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'integration',\n name: 'Integration',\n description: 'Template for integrating external services or APIs',\n sections: [\n { type: 'overview', title: 'Integration Overview', level: 2 },\n { type: 'requirements', title: 'Integration Requirements', level: 2 },\n { type: 'api', title: 'API Contract', level: 2 },\n { type: 'architecture', title: 'Architecture', level: 2 },\n { type: 'security', title: 'Auth & Security', level: 2 },\n { type: 'acceptance', title: 'Testing Strategy', level: 2 },\n ],\n defaultRequirements: [\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'security', priority: 'critical', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'performance', priority: 'medium', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n {\n id: 'cli-command',\n name: 'CLI Command',\n description: 'Template for new CLI commands/slash commands',\n sections: [\n { type: 'overview', title: 'Command Overview', level: 2 },\n { type: 'requirements', title: 'Command Requirements', level: 2 },\n { type: 'api', title: 'Command Interface', level: 2 },\n { type: 'acceptance', title: 'Usage Examples', level: 2 },\n ],\n defaultRequirements: [\n { type: 'ux', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n { type: 'functional', priority: 'high', acceptanceCriteria: [], blockedBy: [], implements: [] },\n ],\n },\n];\n\n/**\n * Get a template by ID.\n */\nexport function getTemplate(id: string): SpecTemplate | undefined {\n return SPEC_TEMPLATES.find((t) => t.id === id);\n}\n\n/**\n * List all available templates.\n */\nexport function listTemplates(): Array<{ id: string; name: string; description: string }> {\n return SPEC_TEMPLATES.map((t) => ({ id: t.id, name: t.name, description: t.description }));\n}\n\n/**\n * Generate a markdown skeleton from a template.\n */\nexport function templateToMarkdown(template: SpecTemplate, title?: string): string {\n const lines: string[] = [];\n lines.push(`# ${title ?? 'Untitled Specification'}`);\n lines.push('Version: 0.1.0');\n lines.push('');\n\n for (const section of template.sections) {\n lines.push(`${'#'.repeat(section.level + 1)} ${section.title}`);\n lines.push(`_<!-- ${section.type} section content -->_`);\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n","import type { TaskGraph, TaskNode, TaskProgress } from '../types/task-graph.js';\nimport { computeTaskProgress } from '../types/task-graph.js';\nimport type { Specification } from '../types/spec.js';\nimport { truncate } from '../utils/string.js';\n\nconst STATUS_ICON: Record<TaskNode['status'], string> = {\n pending: '○',\n in_progress: '◐',\n blocked: '⊘',\n failed: '✗',\n review: '◑',\n completed: '●',\n};\n\nconst PRIORITY_ICON: Record<TaskNode['priority'], string> = {\n critical: '🔴',\n high: '🟠',\n medium: '🟡',\n low: '🟢',\n};\n\nconst TYPE_ICON: Record<TaskNode['type'], string> = {\n feature: '⚡',\n bugfix: '🐛',\n refactor: '♻️',\n docs: '📝',\n test: '🧪',\n chore: '🔧',\n};\n\n/**\n * Render a task graph as ASCII art for terminal display.\n */\nexport function renderTaskGraph(graph: TaskGraph, opts?: { compact?: boolean | undefined }): string {\n const lines: string[] = [];\n const compact = opts?.compact ?? false;\n\n // Header\n lines.push(`╭─ Task Graph: ${graph.title} ─╮`);\n lines.push(`│ Spec: ${graph.specId.slice(0, 8)}... │ Nodes: ${graph.nodes.size} │ Edges: ${graph.edges.length} │`);\n lines.push('╰' + '─'.repeat(Math.max(50, graph.title.length + 30)) + '╯');\n lines.push('');\n\n // Progress bar\n const progress = computeTaskProgress(graph);\n lines.push(renderProgress(progress));\n lines.push('');\n\n // Build adjacency for display\n const childrenMap = new Map<string, string[]>();\n for (const edge of graph.edges) {\n if (edge.type === 'depends_on') {\n // edge.from depends on edge.to → edge.to is a blocker\n const deps = childrenMap.get(edge.from) ?? [];\n deps.push(edge.to);\n childrenMap.set(edge.from, deps);\n }\n }\n\n // Render root nodes and their dependents\n const rendered = new Set<string>();\n const rootNodes = graph.rootNodes.filter((id) => graph.nodes.has(id));\n\n // If no root nodes, use all nodes\n const startNodes = rootNodes.length > 0\n ? rootNodes\n : Array.from(graph.nodes.keys()).filter((id) => {\n const deps = childrenMap.get(id);\n return !deps || deps.length === 0;\n });\n\n for (const rootId of startNodes) {\n renderNode(graph, rootId, lines, rendered, childrenMap, compact, '');\n }\n\n // Render any orphan nodes\n for (const [id] of graph.nodes) {\n if (!rendered.has(id)) {\n renderNode(graph, id, lines, rendered, childrenMap, compact, '');\n }\n }\n\n // Legend\n lines.push('');\n lines.push('Legend: ● done ◐ in-progress ○ pending ⊗ blocked ✗ failed ◒ review');\n\n return lines.join('\\n');\n}\n\nfunction renderNode(\n graph: TaskGraph,\n nodeId: string,\n lines: string[],\n rendered: Set<string>,\n childrenMap: Map<string, string[]>,\n compact: boolean,\n prefix: string,\n): void {\n if (rendered.has(nodeId)) return;\n rendered.add(nodeId);\n\n const node = graph.nodes.get(nodeId);\n if (!node) return;\n\n const icon = STATUS_ICON[node.status];\n const prioIcon = PRIORITY_ICON[node.priority];\n const typeIcon = TYPE_ICON[node.type];\n const title = compact ? truncate(node.title, 40) : node.title;\n\n const blockedBy = childrenMap.get(nodeId) ?? [];\n const depsStr = blockedBy.length > 0\n ? ` ← [${blockedBy.map((d) => graph.nodes.get(d)?.title?.slice(0, 12) ?? '?').join(', ')}]`\n : '';\n\n lines.push(`${prefix}${icon} ${typeIcon} ${prioIcon} ${title}${depsStr}`);\n\n if (!compact && node.description) {\n const descLines = node.description.split('\\n').slice(0, 3);\n for (const dl of descLines) {\n lines.push(`${prefix} └ ${truncate(dl, 60)}`);\n }\n }\n\n // Render nodes that depend on this one\n const dependents = graph.edges\n .filter((e) => e.type === 'depends_on' && e.to === nodeId)\n .map((e) => e.from)\n .filter((id) => graph.nodes.has(id));\n\n for (const depId of dependents) {\n renderNode(graph, depId, lines, rendered, childrenMap, compact, prefix + ' ');\n }\n}\n\n/**\n * Render a progress bar.\n */\nexport function renderProgress(progress: TaskProgress): string {\n const barWidth = 30;\n const filled = Math.round((progress.percentComplete / 100) * barWidth);\n const empty = barWidth - filled;\n const bar = '█'.repeat(filled) + '░'.repeat(empty);\n\n return [\n `Progress: [${bar}] ${progress.percentComplete}%`,\n ` ${progress.completed} done │ ${progress.inProgress} active │ ${progress.pending} pending │ ${progress.blocked} blocked │ ${progress.failed} failed`,\n ].join('\\n');\n}\n\n/**\n * Render a compact task list (for quick status checks).\n */\nexport function renderTaskList(graph: TaskGraph): string {\n const lines: string[] = [];\n const nodes = Array.from(graph.nodes.values());\n\n // Group by status\n const groups: Record<string, TaskNode[]> = {\n in_progress: [],\n pending: [],\n blocked: [],\n review: [],\n failed: [],\n completed: [],\n };\n\n for (const node of nodes) {\n groups[node.status]?.push(node);\n }\n\n for (const [status, group] of Object.entries(groups)) {\n if (group.length === 0) continue;\n const icon = STATUS_ICON[status as TaskNode['status']];\n lines.push(`${icon} ${status.toUpperCase()} (${group.length})`);\n for (const node of group) {\n const prio = PRIORITY_ICON[node.priority];\n const type = TYPE_ICON[node.type];\n lines.push(` ${type} ${prio} ${node.title}`);\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render spec analysis summary.\n */\nexport function renderSpecAnalysis(\n spec: Specification,\n analysis: { completeness: number; gaps: string[]; risks: string[]; suggestions: string[] },\n): string {\n const lines: string[] = [];\n\n lines.push(`╭─ Spec Analysis: ${spec.title} ─╮`);\n lines.push('');\n\n // Completeness\n const barWidth = 20;\n const filled = Math.round((analysis.completeness / 100) * barWidth);\n const bar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);\n lines.push(`Completeness: [${bar}] ${analysis.completeness}%`);\n lines.push('');\n\n if (analysis.gaps.length > 0) {\n lines.push('⚠ Gaps:');\n for (const gap of analysis.gaps) {\n lines.push(` • ${gap}`);\n }\n lines.push('');\n }\n\n if (analysis.risks.length > 0) {\n lines.push('🔴 Risks:');\n for (const risk of analysis.risks) {\n lines.push(` • ${risk}`);\n }\n lines.push('');\n }\n\n if (analysis.suggestions.length > 0) {\n lines.push('💡 Suggestions:');\n for (const sug of analysis.suggestions) {\n lines.push(` • ${sug}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n","import { expectDefined } from '../utils/expect-defined.js';\nimport type { TaskGraph } from '../types/task-graph.js';\nimport { topologicalSort } from '../types/task-graph.js';\n/**\n * Enhanced critical path analysis with bottleneck detection,\n * parallel execution groups, and time estimation.\n */\nexport interface CriticalPathAnalysis {\n /** Ordered list of critical path task IDs. */\n criticalPath: string[];\n /** Total estimated hours for the critical path. */\n totalHours: number;\n /** Tasks that block the most downstream work. */\n bottlenecks: BottleneckTask[];\n /** Groups of tasks that can run in parallel. */\n parallelGroups: string[][];\n /** Recommended execution order respecting dependencies. */\n executionOrder: string[];\n /** Tasks with no blockers (can start immediately). */\n readyTasks: string[];\n /** Tasks that are blocked and cannot start. */\n blockedTasks: string[];\n}\n\nexport interface BottleneckTask {\n taskId: string;\n title: string;\n /** Number of tasks directly or transitively blocked by this task. */\n blockedCount: number;\n /** Total estimated hours of blocked downstream work. */\n blockedHours: number;\n /** Severity score (0-100). */\n severity: number;\n}\n\n/**\n * Analyze a task graph and return critical path analysis.\n */\nexport function analyzeCriticalPath(graph: TaskGraph): CriticalPathAnalysis {\n const nodes = Array.from(graph.nodes.values());\n const topoOrder = topologicalSort(graph);\n\n // Build adjacency: blocker → blocked tasks\n const blockedByMap = new Map<string, Set<string>>();\n const blocksMap = new Map<string, Set<string>>();\n\n for (const edge of graph.edges) {\n if (edge.type === 'depends_on') {\n // edge.from depends on edge.to\n if (!blockedByMap.has(edge.from)) blockedByMap.set(edge.from, new Set());\n blockedByMap.get(edge.from)?.add(edge.to);\n\n if (!blocksMap.has(edge.to)) blocksMap.set(edge.to, new Set());\n blocksMap.get(edge.to)?.add(edge.from);\n }\n }\n\n // Find ready tasks (no blockers or all blockers completed)\n const readyTasks: string[] = [];\n const blockedTasks: string[] = [];\n\n for (const node of nodes) {\n if (node.status === 'completed') continue;\n const blockers = blockedByMap.get(node.id);\n if (!blockers || blockers.size === 0) {\n readyTasks.push(node.id);\n } else {\n const allCompleted = Array.from(blockers).every((id) => {\n const n = graph.nodes.get(id);\n return n?.status === 'completed';\n });\n if (allCompleted) {\n readyTasks.push(node.id);\n } else {\n blockedTasks.push(node.id);\n }\n }\n }\n\n // Compute bottleneck scores\n const bottlenecks: BottleneckTask[] = [];\n for (const node of nodes) {\n if (node.status === 'completed') continue;\n const downstream = getTransitiveBlocked(graph, node.id, blocksMap);\n if (downstream.size > 0) {\n const blockedHours = Array.from(downstream).reduce((sum, id) => {\n const n = graph.nodes.get(id);\n return sum + (n?.estimateHours ?? 0);\n }, 0);\n bottlenecks.push({\n taskId: node.id,\n title: node.title,\n blockedCount: downstream.size,\n blockedHours,\n severity: Math.min(100, Math.round((downstream.size / nodes.length) * 100)),\n });\n }\n }\n\n bottlenecks.sort((a, b) => b.severity - a.severity);\n\n // Compute critical path (longest path by estimated hours)\n const criticalPath = computeCriticalPath(graph, topoOrder, blockedByMap);\n\n // Total hours on critical path\n const totalHours = criticalPath.reduce((sum, id) => {\n const n = graph.nodes.get(id);\n return sum + (n?.estimateHours ?? 0);\n }, 0);\n\n // Parallel execution groups\n const parallelGroups = computeParallelGroups(graph, blockedByMap);\n\n // Execution order: topo sort filtered to non-completed tasks\n const executionOrder = topoOrder.filter((id) => {\n const n = graph.nodes.get(id);\n return n && n.status !== 'completed';\n });\n\n return {\n criticalPath,\n totalHours,\n bottlenecks,\n parallelGroups,\n executionOrder,\n readyTasks,\n blockedTasks,\n };\n}\n\n/**\n * Get all tasks transitively blocked by a given task.\n */\nfunction getTransitiveBlocked(\n _graph: TaskGraph,\n taskId: string,\n blocksMap: Map<string, Set<string>>,\n): Set<string> {\n const visited = new Set<string>();\n const queue = [taskId];\n\n while (queue.length > 0) {\n const current = expectDefined(queue.shift());\n const blocked = blocksMap.get(current);\n if (!blocked) continue;\n for (const id of blocked) {\n if (!visited.has(id) && id !== taskId) {\n visited.add(id);\n queue.push(id);\n }\n }\n }\n\n return visited;\n}\n\n/**\n * Compute the critical path (longest path by estimated hours).\n */\nfunction computeCriticalPath(\n graph: TaskGraph,\n _topoOrder: string[],\n blockedByMap: Map<string, Set<string>>,\n): string[] {\n // Use all nodes in the graph, not just topo-reachable ones\n const allIds = Array.from(graph.nodes.keys());\n if (allIds.length === 0) return [];\n\n const dist = new Map<string, number>();\n const prev = new Map<string, string | null>();\n\n // Initialize each node's distance to its own estimate\n for (const id of allIds) {\n dist.set(id, graph.nodes.get(id)?.estimateHours ?? 1);\n prev.set(id, null);\n }\n\n // Build reverse map: blocker → tasks it blocks\n const blocksMap = new Map<string, Set<string>>();\n for (const [taskId, blockers] of blockedByMap) {\n for (const blockerId of blockers) {\n if (!blocksMap.has(blockerId)) blocksMap.set(blockerId, new Set());\n blocksMap.get(blockerId)?.add(taskId);\n }\n }\n\n // Relax edges repeatedly (Bellman-Ford style) since topoOrder may be incomplete.\n // Run N-1 iterations to handle longest path in DAG.\n const n = allIds.length;\n for (let i = 0; i < n - 1; i++) {\n let changed = false;\n for (const id of allIds) {\n const blocked = blocksMap.get(id);\n if (!blocked) continue;\n for (const blockedId of blocked) {\n const candidateDist = (dist.get(id) ?? 0) + (graph.nodes.get(blockedId)?.estimateHours ?? 1);\n if (candidateDist > (dist.get(blockedId) ?? 0)) {\n dist.set(blockedId, candidateDist);\n prev.set(blockedId, id);\n changed = true;\n }\n }\n }\n if (!changed) break;\n }\n\n // Find the node with maximum distance (end of critical path)\n let maxDist = 0;\n let maxId = expectDefined(allIds[0]);\n for (const id of allIds) {\n const d = dist.get(id) ?? 0;\n if (d > maxDist) {\n maxDist = d;\n maxId = id;\n }\n }\n\n // Trace back the critical path\n const path: string[] = [];\n let current: string | null = maxId;\n const visited = new Set<string>();\n while (current && !visited.has(current)) {\n visited.add(current);\n path.unshift(current);\n current = prev.get(current) ?? null;\n }\n\n return path;\n}\n\n/**\n * Compute groups of tasks that can run in parallel.\n * Tasks in the same group have no dependencies on each other.\n */\nfunction computeParallelGroups(\n graph: TaskGraph,\n blockedByMap: Map<string, Set<string>>,\n): string[][] {\n const groups: string[][] = [];\n const assigned = new Set<string>();\n const nodes = Array.from(graph.nodes.values()).filter((n) => n.status !== 'completed');\n\n // Topological levels\n const remaining = new Set(nodes.map((n) => n.id));\n\n while (remaining.size > 0) {\n const group: string[] = [];\n for (const id of remaining) {\n const blockers = blockedByMap.get(id);\n if (!blockers || blockers.size === 0) {\n group.push(id);\n } else {\n const allAssigned = Array.from(blockers).every((b) => assigned.has(b));\n if (allAssigned) {\n group.push(id);\n }\n }\n }\n\n if (group.length === 0) {\n // Circular dependency or all remaining are blocked by non-completed\n // Just take the first remaining\n const first = Array.from(remaining)[0];\n if (first) group.push(first);\n }\n\n for (const id of group) {\n assigned.add(id);\n remaining.delete(id);\n }\n groups.push(group);\n }\n\n return groups;\n}\n","import type { Specification, SpecRequirement } from '../types/spec.js';\nimport type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport { assertNever } from '../utils/assert-never.js';\n\nexport interface SpecVersion {\n version: string;\n spec: Specification;\n timestamp: number;\n changeDescription?: string | undefined;\n}\n\nexport interface SpecDiff {\n added: SpecRequirement[];\n removed: SpecRequirement[];\n modified: Array<{\n requirement: SpecRequirement;\n previousVersion: SpecRequirement;\n changes: string[];\n }>;\n summary: string;\n}\n\n/**\n * Track spec versions and compute diffs between versions.\n */\nexport class SpecVersioning {\n private versions = new Map<string, SpecVersion[]>();\n\n /** Record a new version of a spec. */\n recordVersion(spec: Specification, changeDescription?: string): SpecVersion {\n const version: SpecVersion = {\n version: spec.version,\n spec: { ...spec },\n timestamp: Date.now(),\n changeDescription,\n };\n\n const history = this.versions.get(spec.id) ?? [];\n history.push(version);\n this.versions.set(spec.id, history);\n\n return version;\n }\n\n /** Get version history for a spec. */\n getHistory(specId: string): SpecVersion[] {\n return this.versions.get(specId) ?? [];\n }\n\n /** Get a specific version of a spec. */\n getVersion(specId: string, version: string): SpecVersion | undefined {\n const history = this.versions.get(specId) ?? [];\n return history.find((v) => v.version === version);\n }\n\n /** Get the latest version of a spec. */\n getLatest(specId: string): SpecVersion | undefined {\n const history = this.versions.get(specId) ?? [];\n return history[history.length - 1];\n }\n\n /** Compute diff between two versions of a spec. */\n diff(oldSpec: Specification, newSpec: Specification): SpecDiff {\n const oldReqs = new Map(oldSpec.requirements.map((r) => [r.id, r]));\n const newReqs = new Map(newSpec.requirements.map((r) => [r.id, r]));\n\n const added: SpecRequirement[] = [];\n const removed: SpecRequirement[] = [];\n const modified: SpecDiff['modified'] = [];\n\n // Find added and modified\n for (const [id, newReq] of newReqs) {\n const oldReq = oldReqs.get(id);\n if (!oldReq) {\n added.push(newReq);\n } else {\n const changes = this.compareRequirements(oldReq, newReq);\n if (changes.length > 0) {\n modified.push({\n requirement: newReq,\n previousVersion: oldReq,\n changes,\n });\n }\n }\n }\n\n // Find removed\n for (const [id, oldReq] of oldReqs) {\n if (!newReqs.has(id)) {\n removed.push(oldReq);\n }\n }\n\n const parts: string[] = [];\n if (added.length > 0) parts.push(`${added.length} added`);\n if (removed.length > 0) parts.push(`${removed.length} removed`);\n if (modified.length > 0) parts.push(`${modified.length} modified`);\n\n return {\n added,\n removed,\n modified,\n summary: parts.length > 0 ? parts.join(', ') : 'No changes',\n };\n }\n\n /**\n * Update a task graph incrementally based on spec changes.\n * - Added requirements → new tasks\n * - Removed requirements → remove tasks\n * - Modified requirements → update task descriptions\n * Returns the updated graph and list of changes made.\n */\n updateTaskGraph(\n graph: TaskGraph,\n oldSpec: Specification,\n newSpec: Specification,\n ): { graph: TaskGraph; changes: string[] } {\n const specDiff = this.diff(oldSpec, newSpec);\n const changes: string[] = [];\n\n // Map requirement IDs to task nodes\n const reqToTask = new Map<string, TaskNode>();\n for (const node of graph.nodes.values()) {\n if (node.specRequirementId) {\n reqToTask.set(node.specRequirementId, node);\n }\n }\n\n // Remove tasks for removed requirements\n for (const req of specDiff.removed) {\n const task = reqToTask.get(req.id);\n if (task) {\n graph.nodes.delete(task.id);\n graph.edges = graph.edges.filter((e) => e.from !== task.id && e.to !== task.id);\n changes.push(`Removed task: ${task.title}`);\n }\n }\n\n // Update tasks for modified requirements\n for (const mod of specDiff.modified) {\n const task = reqToTask.get(mod.requirement.id);\n if (task) {\n task.title = mod.requirement.description;\n task.description = this.buildTaskDescription(mod.requirement);\n task.priority = mod.requirement.priority;\n task.updatedAt = Date.now();\n changes.push(`Updated task: ${task.title} (${mod.changes.join(', ')})`);\n }\n }\n\n // Add tasks for new requirements\n for (const req of specDiff.added) {\n const now = Date.now();\n const newTask: TaskNode = {\n id: crypto.randomUUID(),\n title: req.description,\n description: this.buildTaskDescription(req),\n type: this.mapReqType(req.type),\n priority: req.priority,\n status: 'pending',\n specRequirementId: req.id,\n tags: [req.type, req.priority],\n createdAt: now,\n updatedAt: now,\n };\n graph.nodes.set(newTask.id, newTask);\n graph.rootNodes.push(newTask.id);\n changes.push(`Added task: ${newTask.title}`);\n }\n\n graph.updatedAt = Date.now();\n return { graph, changes };\n }\n\n private compareRequirements(old: SpecRequirement, current: SpecRequirement): string[] {\n const changes: string[] = [];\n if (old.description !== current.description) changes.push('description');\n if (old.priority !== current.priority) changes.push('priority');\n if (old.type !== current.type) changes.push('type');\n if (JSON.stringify(old.acceptanceCriteria) !== JSON.stringify(current.acceptanceCriteria)) {\n changes.push('acceptance criteria');\n }\n if (JSON.stringify(old.blockedBy) !== JSON.stringify(current.blockedBy)) {\n changes.push('dependencies');\n }\n return changes;\n }\n\n private buildTaskDescription(req: SpecRequirement): string {\n const lines = [req.description, '', `**Type:** ${req.type}`, `**Priority:** ${req.priority}`];\n if (req.acceptanceCriteria.length > 0) {\n lines.push('', '**Acceptance Criteria:**');\n for (const ac of req.acceptanceCriteria) {\n lines.push(`- ${ac}`);\n }\n }\n return lines.join('\\n');\n }\n\n private mapReqType(type: SpecRequirement['type']): TaskNode['type'] {\n switch (type) {\n case 'functional':\n return 'feature';\n case 'non-functional':\n return 'feature';\n case 'security':\n return 'feature';\n case 'performance':\n return 'feature';\n case 'ux':\n return 'feature';\n default:\n return assertNever(type);\n }\n }\n}\n","import type { TaskGraph, TaskNode } from '../types/task-graph.js';\nimport type { Specification } from '../types/spec.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { TaskTracker } from './task-tracker.js';\nimport { analyzeCriticalPath } from './critical-path.js';\n\nexport interface AutoExecutorOptions {\n tracker: TaskTracker;\n events: EventBus;\n /** Maximum concurrent tasks. Defaults to 1 (sequential). */\n maxConcurrent?: number | undefined;\n /** Maximum retry attempts for failed tasks. */\n maxRetries?: number | undefined;\n /** Custom task executor function. */\n executeTask: (task: TaskNode, context: TaskExecutionContext) => Promise<TaskExecutionResult>;\n /** Called before each task starts. */\n onTaskStart?: (((task: TaskNode) => void)) | undefined;\n /** Called after each task completes. */\n onTaskComplete?: (task: TaskNode, result: TaskExecutionResult) => void;\n /** Called when a task fails. */\n onTaskFail?: (task: TaskNode, error: Error, retryCount: number) => void;\n /** Called when all tasks are done or no more can execute. */\n onDone?: (((summary: ExecutionSummary) => void)) | undefined;\n}\n\nexport interface TaskExecutionContext {\n /** The spec being implemented. */\n spec: Specification;\n /** The full task graph. */\n graph: TaskGraph;\n /** The current task being executed. */\n task: TaskNode;\n /** Tasks that this task depends on. */\n dependencies: TaskNode[];\n /** Tasks that depend on this task. */\n dependents: TaskNode[];\n /** Retry count for this task (0 = first attempt). */\n retryCount: number;\n}\n\nexport interface TaskExecutionResult {\n success: boolean;\n output?: string | undefined;\n error?: string | undefined;\n /** If true, the task will be retried. */\n retry?: boolean | undefined;\n}\n\nexport interface ExecutionSummary {\n total: number;\n completed: number;\n failed: number;\n skipped: number;\n retried: number;\n duration: number;\n criticalPath: string[];\n}\n\n/**\n * Auto-executor that drives task execution with dependency resolution,\n * retry logic, and critical path awareness.\n */\nexport class AutoExecutor {\n private readonly opts: AutoExecutorOptions;\n private stopped = false;\n private retryMap = new Map<string, number>();\n\n constructor(opts: AutoExecutorOptions) {\n this.opts = opts;\n }\n\n /**\n * Execute all tasks in the graph, respecting dependencies.\n */\n async execute(graph: TaskGraph, spec: Specification): Promise<ExecutionSummary> {\n this.stopped = false;\n this.retryMap.clear();\n const startTime = Date.now();\n\n const critical = analyzeCriticalPath(graph);\n let completed = 0;\n let failed = 0;\n const skipped = 0;\n let retried = 0;\n\n while (!this.stopped) {\n const readyTasks = this.getReadyTasks(graph);\n\n if (readyTasks.length === 0) {\n // Check if all tasks are done\n const allDone = Array.from(graph.nodes.values()).every(\n (n) => n.status === 'completed' || n.status === 'failed',\n );\n if (allDone) break;\n\n // Check for deadlock (all remaining tasks are blocked by failed tasks)\n const hasDeadlock = this.detectDeadlock(graph);\n if (hasDeadlock) break;\n\n break;\n }\n\n // Execute batch\n const batch = readyTasks.slice(0, this.opts.maxConcurrent ?? 1);\n\n const results = await Promise.allSettled(\n batch.map((task) => this.executeTaskWithRetry(task, graph, spec)),\n );\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n const task = batch[i];\n if (!result || !task) continue;\n\n if (result.status === 'fulfilled') {\n const { result: execResult, retries } = result.value;\n if (execResult.success) {\n this.opts.tracker.updateNodeStatus(task.id, 'completed');\n completed++;\n if (retries > 0) retried++;\n this.opts.onTaskComplete?.(task, execResult);\n } else if (execResult.retry) {\n retried++;\n // Task will be retried on next iteration\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'failed', execResult.error);\n failed++;\n }\n } else {\n this.opts.tracker.updateNodeStatus(task.id, 'failed', String(result.reason));\n failed++;\n this.opts.onTaskFail?.(task, result.reason as Error, 0);\n }\n }\n }\n\n const duration = Date.now() - startTime;\n const summary: ExecutionSummary = {\n total: graph.nodes.size,\n completed,\n failed,\n skipped,\n retried,\n duration,\n criticalPath: critical.criticalPath,\n };\n\n this.opts.onDone?.(summary);\n return summary;\n }\n\n /** Stop execution. */\n stop(): void {\n this.stopped = true;\n }\n\n /** Get tasks that are ready to execute (all dependencies completed). */\n private getReadyTasks(graph: TaskGraph): TaskNode[] {\n const ready: TaskNode[] = [];\n\n for (const node of graph.nodes.values()) {\n if (node.status !== 'pending') continue;\n\n // Check if all blockers are completed\n const blockers = graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === node.id)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n\n const allBlockersDone = blockers.every((b) => b.status === 'completed');\n if (allBlockersDone) {\n ready.push(node);\n }\n }\n\n // Sort by priority\n const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n ready.sort((a, b) => (priorityOrder[a.priority] ?? 4) - (priorityOrder[b.priority] ?? 4));\n\n return ready;\n }\n\n /** Execute a single task with retry logic. */\n private async executeTaskWithRetry(\n task: TaskNode,\n graph: TaskGraph,\n spec: Specification,\n ): Promise<{ result: TaskExecutionResult; retries: number }> {\n const maxRetries = this.opts.maxRetries ?? 2;\n let retryCount = this.retryMap.get(task.id) ?? 0;\n\n while (retryCount <= maxRetries) {\n this.opts.tracker.updateNodeStatus(task.id, 'in_progress');\n this.opts.onTaskStart?.(task);\n\n const dependencies = this.getTaskDependencies(task.id, graph);\n const dependents = this.getTaskDependents(task.id, graph);\n\n const context: TaskExecutionContext = {\n spec,\n graph,\n task,\n dependencies,\n dependents,\n retryCount,\n };\n\n try {\n const result = await this.opts.executeTask(task, context);\n\n if (result.success) {\n const retriesForTask = this.retryMap.get(task.id) ?? 0;\n this.retryMap.delete(task.id);\n return { result, retries: retriesForTask };\n }\n\n if (result.retry && retryCount < maxRetries) {\n retryCount++;\n this.retryMap.set(task.id, retryCount);\n this.opts.tracker.updateNodeStatus(task.id, 'pending');\n continue;\n }\n\n return { result, retries: retryCount };\n } catch (error) {\n if (retryCount < maxRetries) {\n retryCount++;\n this.retryMap.set(task.id, retryCount);\n this.opts.tracker.updateNodeStatus(task.id, 'pending');\n this.opts.onTaskFail?.(task, error as Error, retryCount);\n continue;\n }\n\n return {\n result: {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n },\n retries: retryCount,\n };\n }\n }\n\n return { result: { success: false, error: 'Max retries exceeded' }, retries: retryCount };\n }\n\n /** Get tasks that this task depends on. */\n private getTaskDependencies(taskId: string, graph: TaskGraph): TaskNode[] {\n return graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === taskId)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n }\n\n /** Get tasks that depend on this task. */\n private getTaskDependents(taskId: string, graph: TaskGraph): TaskNode[] {\n return graph.edges\n .filter((e) => e.type === 'depends_on' && e.to === taskId)\n .map((e) => graph.nodes.get(e.from))\n .filter(Boolean) as TaskNode[];\n }\n\n /** Detect deadlock: all remaining tasks are blocked by failed tasks. */\n private detectDeadlock(graph: TaskGraph): boolean {\n const remaining = Array.from(graph.nodes.values()).filter(\n (n) => n.status === 'pending' || n.status === 'blocked',\n );\n\n if (remaining.length === 0) return false;\n\n return remaining.every((node) => {\n const blockers = graph.edges\n .filter((e) => e.type === 'depends_on' && e.from === node.id)\n .map((e) => graph.nodes.get(e.to))\n .filter(Boolean) as TaskNode[];\n\n return blockers.some((b) => b.status === 'failed');\n });\n }\n}\n\n/**\n * Create an auto-executor that works with TaskFlow.\n */\nexport function createAutoExecutor(opts: {\n tracker: TaskTracker;\n events: EventBus;\n executeTask: AutoExecutorOptions['executeTask'];\n maxConcurrent?: number | undefined;\n maxRetries?: number | undefined;\n}): AutoExecutor {\n return new AutoExecutor({\n tracker: opts.tracker,\n events: opts.events,\n executeTask: opts.executeTask,\n maxConcurrent: opts.maxConcurrent,\n maxRetries: opts.maxRetries,\n });\n}\n","/**\n * Cross-provider fallback model extension.\n *\n * Lives in core so EVERY agent surface can reuse it: the CLI leader, the CLI\n * director/host subagent factory, and the runtime light subagent factory (used\n * by standalone SDD runs). It wraps the provider runner and, when the active\n * model 429s / overloads / stream-hangs, rotates through a fallback chain. The\n * chain is recomputed from live config every turn, so changes take effect\n * without a restart; an empty chain makes the wrapper a no-op.\n *\n * Moved here from `@wrongstack/cli` (it only ever depended on core types) so the\n * runtime light factory can wire fallbacks for SDD worker subagents.\n */\nimport type { AgentExtension } from '../extension/extension-points.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { Config, ProviderConfig } from '../types/config.js';\n\nfunction visibleProviderModels(config: Config, providerId: string, providerModels: string[]): string[] {\n const entry = config.providers?.[providerId];\n return entry?.models !== undefined ? [...entry.models] : providerModels;\n}\nimport type { Logger } from '../types/logger.js';\nimport { type Provider, ProviderError, StreamHangError } from '../types/provider.js';\n\nexport interface FallbackModelDeps {\n /** Returns the live config (re-read each turn so `/model` switches are honored). */\n getConfig: () => Config;\n /**\n * Builds a credential-resolved Provider for a provider id (alias-resolved),\n * WITHOUT persisting anything to config/configStore. Supplied by the boot\n * path, which shares this with the `/model` switch logic. May be async — the\n * subagent host resolves a provider's real context window asynchronously.\n */\n buildProvider: (providerId: string) => Provider | Promise<Provider>;\n /**\n * Called after the active model changes (a fallback hop or the primary\n * restore) so the host can refresh the auto-compaction / context-window\n * denominator — important when a fallback crosses to a smaller-window model.\n */\n onModelSwitch?: (providerId: string, modelId: string) => void | Promise<void>;\n events: EventBus;\n /** Optional — warnings about un-buildable fallback providers. */\n logger?: Logger | undefined;\n}\n\ninterface ModelRef {\n provider?: string | undefined;\n model: string;\n}\n\n/** Parse a fallback entry: `model`, `provider/model`, or `provider model`. */\nexport function parseModelRef(ref: string): ModelRef {\n const trimmed = ref.trim();\n const slash = trimmed.indexOf('/');\n if (slash !== -1) {\n // An empty provider (leading slash, e.g. \"/gpt\") means \"use the primary\n // provider\" — collapse to undefined so the `?? cfg.provider` fallback fires.\n return {\n provider: trimmed.slice(0, slash) || undefined,\n model: trimmed.slice(slash + 1).trim(),\n };\n }\n const parts = trimmed.split(/\\s+/);\n if (parts.length >= 2) {\n return { provider: parts[0], model: parts.slice(1).join(' ') };\n }\n return { model: trimmed };\n}\n\n/**\n * Check if an error should trigger a fallback. Returns the status for\n * logging, or null if the error doesn't warrant a fallback attempt.\n *\n * Triggers on:\n * - StreamHangError (always — the upstream endpoint stalled mid-response)\n * - HTTP 429 (rate limited)\n * - HTTP 529 (overloaded)\n * - HTTP 5xx (server error)\n * - HTTP 0 / network error (connection failure, DNS failure, etc.)\n */\nfunction shouldFallback(err: unknown): number | null {\n if (err instanceof StreamHangError) {\n // Stream hangs are always worth falling back — the endpoint is\n // likely overloaded or has a routing issue.\n return 599;\n }\n if (!(err instanceof ProviderError)) return null;\n const s = err.status;\n // Network errors (status 0) — connection couldn't be established\n if (s === 0) return s;\n // Rate limits, overload, and server errors\n if (s === 429 || s === 529 || s >= 500) return s;\n return null;\n}\n\n/** A provider is usable as a fallback target when it has a stored key, a key\n * list, or a populated env var. Mirrors `setmodel.providerHasKey`. */\nfunction providerHasKey(entry: ProviderConfig | undefined): boolean {\n if (!entry) return false;\n if (typeof entry.apiKey === 'string' && entry.apiKey.length > 0) return true;\n if (Array.isArray(entry.apiKeys) && entry.apiKeys.some((k) => k?.apiKey)) return true;\n if (Array.isArray(entry.envVars) && entry.envVars.some((v) => !!process.env[v])) return true;\n return false;\n}\n\n/** Hard ceiling on the auto-derived chain so we don't burn through a dozen\n * models on a transient blip. */\nconst SMART_DEFAULT_MAX = 4;\n\n/**\n * Derive a fallback chain from the configured providers when the user has not\n * set an explicit `fallbackModels` list. Picks declared models from every\n * keyed provider — same-provider alternatives first (same key, cheapest\n * failover), then cross-provider — excluding the active leader model. Returns\n * `[]` when nothing usable is configured (e.g. providers with no `models`\n * list), in which case the extension is a no-op.\n */\nexport function smartDefaultFallbackChain(config: Config): string[] {\n const leaderProvider = config.provider;\n const leaderModel = config.model;\n const providers = config.providers ?? {};\n const seen = new Set<string>();\n const sameProvider: string[] = [];\n const crossProvider: string[] = [];\n\n // Leader provider first so its other models lead the chain.\n const ids = Object.keys(providers).sort((a, b) =>\n a === leaderProvider ? -1 : b === leaderProvider ? 1 : a.localeCompare(b),\n );\n\n for (const id of ids) {\n const entry = providers[id];\n if (!providerHasKey(entry)) continue;\n const models = visibleProviderModels(config, id, entry?.models ?? []);\n for (const model of models) {\n if (id === leaderProvider && model === leaderModel) continue;\n const ref = `${id}/${model}`;\n if (seen.has(ref)) continue;\n seen.add(ref);\n (id === leaderProvider ? sameProvider : crossProvider).push(ref);\n }\n }\n return [...sameProvider, ...crossProvider].slice(0, SMART_DEFAULT_MAX);\n}\n\n/**\n * The effective fallback chain for a turn: the explicit `fallbackModels` list\n * when non-empty, otherwise the smart default (unless `fallbackAuto` is off).\n */\nexport function effectiveFallbackChain(config: Config): string[] {\n const explicit = config.fallbackModels ?? [];\n const filteredExplicit = explicit.filter((ref) => {\n const parsed = parseModelRef(ref);\n if (!parsed.model) return false;\n const providerId = parsed.provider ?? config.provider;\n const entry = config.providers?.[providerId];\n if (!entry?.models) return true;\n return entry.models.includes(parsed.model);\n });\n if (filteredExplicit.length > 0) return filteredExplicit;\n if (config.fallbackAuto === false) return [];\n return smartDefaultFallbackChain(config);\n}\n\n/**\n * Build the cross-provider fallback extension. Always returns an extension —\n * the effective chain (`effectiveFallbackChain`) is recomputed every turn from\n * the live config, so a chain that is empty at boot but populated later (via\n * `/fallback add` or the smart default kicking in once a key is added) takes\n * effect WITHOUT a restart. An empty chain makes the wrapper a no-op (it just\n * rethrows the original error).\n *\n * Mechanism (see plan): wraps the provider runner. The inner runner already\n * applies the per-model retry policy (backoff, up to 5 tries for 429), so the\n * fallback only engages AFTER the active model's own retries are exhausted.\n * Because the wrapper resolves within a single provider call, it does not\n * consume the agent loop's `recoveryRetries` budget — chains longer than two\n * entries work. `beforeRun` restores the configured primary at the start of\n * every turn, giving Claude's \"retry the primary each user turn\" semantics.\n */\nexport function createFallbackModelExtension(deps: FallbackModelDeps): AgentExtension {\n // True when a prior turn left the live context on a fallback model.\n let dirty = false;\n\n return {\n name: 'fallback-model',\n\n beforeRun: async (ctx) => {\n if (!dirty) return;\n const cfg = deps.getConfig();\n try {\n ctx.provider = await deps.buildProvider(cfg.provider);\n ctx.model = cfg.model;\n await deps.onModelSwitch?.(cfg.provider, cfg.model);\n } catch (err) {\n deps.logger?.warn(\n `fallback-model: could not restore primary \"${cfg.provider}/${cfg.model}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n dirty = false;\n },\n\n wrapProviderRunner: async (ctx, request, inner) => {\n try {\n return await inner(ctx, request);\n } catch (firstErr) {\n let lastErr: unknown = firstErr;\n const cfg = deps.getConfig();\n const chain = effectiveFallbackChain(cfg);\n\n for (const ref of chain) {\n const status = shouldFallback(lastErr);\n if (status === null) break; // not a fallback-worthy error\n\n const parsed = parseModelRef(ref);\n if (!parsed.model) continue;\n const targetProviderId = parsed.provider ?? cfg.provider;\n\n const from = { providerId: ctx.provider.id, model: ctx.model };\n\n let nextProvider: Provider;\n try {\n nextProvider = await deps.buildProvider(targetProviderId);\n } catch (err) {\n deps.logger?.warn(\n `fallback-model: skipping \"${ref}\" — cannot build provider \"${targetProviderId}\": ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n continue;\n }\n\n const providerSwitched = nextProvider.id !== from.providerId;\n ctx.provider = nextProvider;\n ctx.model = parsed.model;\n request.model = parsed.model;\n dirty = true;\n await deps.onModelSwitch?.(targetProviderId, parsed.model);\n\n deps.events.emit('provider.fallback', {\n from,\n to: { providerId: nextProvider.id, model: parsed.model },\n status,\n providerSwitched,\n });\n\n try {\n return await inner(ctx, request);\n } catch (err) {\n lastErr = err;\n }\n }\n\n throw lastErr;\n }\n },\n };\n}\n","// SddSupervisor — a decision agent over an SDD parallel run.\n//\n// When a task has exhausted its retries and is about to go terminal, the\n// SddParallelRun consults `superviseFailure` (see SddParallelRunOptions). This\n// supervisor answers that consult by asking a BrainArbiter (policy → LLM →\n// human, reused from the coordination layer) whether to retry, reassign to a\n// different model, split the task into sub-tasks, or give up. The goal is the\n// user's: a run should \"decide\" rather than dead-end — never silently get stuck.\n//\n// Safe by default: with the conservative DefaultBrainArbiter (no LLM) the\n// `fallback: 'continue'` policy resolves to a plain retry, so wiring a supervisor\n// never makes a run worse — it only adds intelligence when an LLM brain is wired.\n\nimport type { BrainArbiter } from '../coordination/brain.js';\nimport { parseModelRef } from '../core/fallback-model.js';\nimport type { TaskNode } from '../types/task-graph.js';\nimport type { SddSubtaskSpec, SddSupervisorVerdict } from './sdd-parallel-run.js';\n\nexport interface SddSupervisorOptions {\n /** Decision authority (policy/LLM/human). Reuse the session's TOKENS.BrainArbiter. */\n brain: BrainArbiter;\n /**\n * Models to rotate through on a `reassign` verdict (e.g. the run's fallback\n * chain). Omit to drop the reassign option entirely.\n */\n reassignModels?: string[] | undefined;\n /**\n * Optional sub-task generator for a `split` verdict — typically an LLM call\n * that decomposes the failing task into smaller pieces. Omit to drop the split\n * option. Returning an empty array degrades the split into a retry.\n */\n generateSubtasks?:\n | ((info: { task: TaskNode; error: string }) => Promise<SddSubtaskSpec[]>)\n | undefined;\n /**\n * Let the tiered brain's LLM layer actually pick the verdict.\n *\n * Default (false) requests `fallback: 'continue'`, which the policy layer\n * answers immediately (a bounded retry) — the LLM never runs, so `reassign`/\n * `split` can't be chosen. Set true to request `fallback: 'ask_human'`, which\n * makes the policy escalate so the autonomous (LLM) layer decides.\n *\n * ONLY enable this when the supplied `brain` will NOT block on a human prompt\n * for an unresolved decision (i.e. it has an autonomous layer and is NOT\n * wrapped in `HumanEscalatingBrainArbiter`). When the LLM can't decide (no\n * autonomous layer / over the risk ceiling / LLM down) the brain returns\n * `ask_human`, which the supervisor degrades to a **bounded retry** (never a\n * block, never a dead-end). A human-escalating brain would instead block\n * inside `decide()` and wedge the run — keep this false there.\n */\n requestLlmVerdict?: boolean | undefined;\n}\n\nexport class SddSupervisor {\n constructor(private readonly opts: SddSupervisorOptions) {}\n\n /**\n * Bind this as `SddParallelRunOptions.superviseFailure`. Returns a verdict the\n * run applies, or `undefined`/`{action:'fail'}` to let the task terminal-fail.\n */\n readonly superviseFailure = async (info: {\n task: TaskNode;\n error: string;\n attempts: number;\n }): Promise<SddSupervisorVerdict | undefined> => {\n const { task, error, attempts } = info;\n const canReassign = (this.opts.reassignModels?.length ?? 0) > 0;\n const canSplit = Boolean(this.opts.generateSubtasks);\n\n const decision = await this.opts.brain.decide({\n id: `sdd-supervisor-${task.id}-${attempts}`,\n source: 'system',\n question: `SDD task \"${task.title}\" exhausted its retries. How should the run proceed?`,\n context: `Error: ${error}\\nSupervisor rescues already used: ${attempts}`,\n options: [\n { id: 'retry', label: 'Retry the task as-is', recommended: true },\n ...(canReassign ? [{ id: 'reassign', label: 'Reassign to a different model' }] : []),\n ...(canSplit ? [{ id: 'split', label: 'Split into smaller sub-tasks' }] : []),\n { id: 'fail', label: 'Give up and mark the task failed' },\n ],\n // Higher risk once we've already rescued it once — pushes a wired LLM/human\n // toward a decisive verdict instead of looping retries.\n risk: attempts >= 1 ? 'high' : 'medium',\n // `continue` → policy answers in place (bounded retry, LLM never runs).\n // `ask_human` → policy escalates so the autonomous LLM layer can actually\n // pick reassign/split (see requestLlmVerdict's safety contract).\n fallback: this.opts.requestLlmVerdict ? 'ask_human' : 'continue',\n });\n\n // A hard deny is a decisive \"give up\" → terminal fail. An unresolved\n // escalation (`ask_human`: the LLM declined / was unavailable / over the\n // ceiling) degrades to a bounded retry so the run keeps moving rather than\n // dead-ending — the never-stuck invariant. (A human-escalating brain would\n // have blocked inside decide() already; requestLlmVerdict forbids that.)\n if (decision.type === 'deny') return { action: 'fail' };\n if (decision.type !== 'answer') return { action: 'retry' };\n // DefaultBrainArbiter's 'continue' answer carries no optionId → retry.\n const choice = decision.optionId ?? 'retry';\n\n if (choice === 'fail') return { action: 'fail' };\n if (choice === 'reassign' && canReassign) {\n const models = this.opts.reassignModels as string[];\n // Rotate through the chain by rescue count; a `provider/model` entry sets\n // both fields so the worker dispatches on the right provider (a bare model\n // keeps the task's current provider).\n const ref = models[attempts % models.length];\n const parsed = ref ? parseModelRef(ref) : undefined;\n return { action: 'reassign', model: parsed?.model, provider: parsed?.provider };\n }\n if (choice === 'split' && this.opts.generateSubtasks) {\n const subtasks = await this.opts\n .generateSubtasks({ task, error })\n .catch(() => [] as SddSubtaskSpec[]);\n return subtasks.length ? { action: 'split', subtasks } : { action: 'retry' };\n }\n return { action: 'retry' };\n };\n}\n","// makeCommandVerifier — the shared completion-gate verifier for an SDD parallel\n// run. Both surfaces that start a run (the CLI `/sdd parallel` handler and the\n// standalone WebUI wizard) need an identical `verifyTask`: when a task declares\n// `metadata.verificationCommand`, run it in the task's worktree cwd and only let\n// the task complete on exit 0. No command → no-op. Bounded by a timeout so a\n// hung verifier can't wedge the run.\n//\n// core may use node:child_process directly — it already does for git detection.\n\nimport { spawn } from 'node:child_process';\nimport type { TaskNode } from '../types/task-graph.js';\nimport type { TaskResult } from '../types/multi-agent.js';\n\nexport interface CommandVerifierOptions {\n /** Metadata key holding the shell command to run. Default 'verificationCommand'. */\n metadataKey?: string;\n /** Kill + fail the verification after this many ms. Default 180_000 (3 min). */\n timeoutMs?: number;\n}\n\n/**\n * Build a `verifyTask` closure (shape matches {@link SddParallelRunOptions.verifyTask}).\n * Returns `{ ok: true }` immediately when the task carries no verification command,\n * otherwise spawns the command in `cwd` (shell, output discarded) and resolves\n * `{ ok: false, reason }` on non-zero exit, spawn error, or timeout.\n */\nexport function makeCommandVerifier(options: CommandVerifierOptions = {}) {\n const metadataKey = options.metadataKey ?? 'verificationCommand';\n const timeoutMs = options.timeoutMs ?? 180_000;\n\n return async function verifyTask(info: {\n task: TaskNode;\n result: TaskResult;\n cwd: string;\n }): Promise<{ ok: boolean; reason?: string }> {\n const cmd = info.task.metadata?.[metadataKey];\n if (typeof cmd !== 'string' || !cmd.trim()) return { ok: true };\n\n return await new Promise((resolve) => {\n const child = spawn(cmd, { cwd: info.cwd, shell: true, windowsHide: true, stdio: 'ignore' });\n const timer = setTimeout(() => {\n child.kill();\n resolve({ ok: false, reason: `verification timed out: ${cmd}` });\n }, timeoutMs);\n child.on('exit', (code) => {\n clearTimeout(timer);\n resolve(\n code === 0 ? { ok: true } : { ok: false, reason: `verification failed (exit ${code}): ${cmd}` },\n );\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n resolve({ ok: false, reason: `verification spawn error: ${String(err)}` });\n });\n });\n };\n}\n","// makeLlmSubtaskGenerator — the LLM auto-split backing for the SDD supervisor.\n//\n// When the supervisor's brain returns a `split` verdict for a retry-exhausted\n// task, it calls `generateSubtasks(task, error)` to decompose the failing task\n// into smaller pieces. This helper produces that closure from a single `run`\n// callback (one isolated LLM turn → text), so core stays free of agent-spawning\n// coupling: each surface supplies the runner via its own subagent factory (the\n// same isolated-turn pattern as the interview driver).\n//\n// Safety: the result is heavily validated and bounded. A leaf can only be split\n// into ≥2 well-formed sub-tasks; anything else (parse failure, 0/1 items, junk)\n// returns [] and the supervisor degrades the split into a bounded retry. The\n// per-task `maxSupervisorEscalations` guard already caps how often this runs, so\n// recursive splitting can't run away.\n\nimport type { TaskNode, TaskPriority, TaskType } from '../types/task-graph.js';\nimport type { SddSubtaskSpec } from './sdd-parallel-run.js';\n\nconst TASK_TYPES = new Set<TaskType>(['feature', 'bugfix', 'refactor', 'docs', 'test', 'chore']);\nconst PRIORITIES = new Set<TaskPriority>(['critical', 'high', 'medium', 'low']);\n\nexport interface SubtaskGeneratorOptions {\n /** Runs one self-contained, isolated LLM turn and resolves its final text. */\n run: (prompt: string) => Promise<string>;\n /** Minimum well-formed sub-tasks required to accept a split. Default 2. */\n minSubtasks?: number;\n /** Maximum sub-tasks kept (excess is dropped). Default 4. */\n maxSubtasks?: number;\n}\n\n/** Extract a JSON array from model output (```json fence or first bare `[...]`). */\nfunction extractJsonArray(text: string): string | null {\n const fence = text.match(/```(?:json)?\\s*(\\[[\\s\\S]*?\\])\\s*```/);\n if (fence?.[1]) return fence[1].trim();\n const bare = text.match(/(\\[[\\s\\S]*\\])/);\n if (bare?.[1]) {\n try {\n if (Array.isArray(JSON.parse(bare[1]))) return bare[1];\n } catch {\n // not valid JSON — fall through\n }\n }\n return null;\n}\n\nfunction buildPrompt(task: TaskNode, error: string, min: number, max: number): string {\n return [\n 'You are an engineering lead triaging a software task that FAILED after every',\n 'automated retry was exhausted. Break it into smaller, independently-executable',\n `sub-tasks (between ${min} and ${max}) so separate workers can each tackle a`,\n 'narrower slice. Each sub-task must be strictly smaller than the parent — never',\n 'restate the whole task as one sub-task.',\n '',\n `Parent task title: ${task.title}`,\n `Parent description: ${task.description}`,\n `Failure / error: ${error || '(none recorded)'}`,\n '',\n 'Respond with ONLY a JSON array (no prose) of objects with this shape:',\n '[{\"title\": \"...\", \"description\": \"...\", \"type\": \"feature|bugfix|refactor|docs|test|chore\", \"priority\": \"critical|high|medium|low\"}]',\n '`type` and `priority` are optional (they default to the parent\\'s).',\n ].join('\\n');\n}\n\n/**\n * Build a `SddSupervisorOptions.generateSubtasks` closure backed by an LLM turn.\n * Returns [] on any failure (parse error, too few valid items, runner throw), so\n * the supervisor safely degrades a `split` verdict into a retry.\n */\nexport function makeLlmSubtaskGenerator(opts: SubtaskGeneratorOptions) {\n const min = Math.max(2, opts.minSubtasks ?? 2);\n const max = Math.max(min, opts.maxSubtasks ?? 4);\n\n return async function generateSubtasks(info: {\n task: TaskNode;\n error: string;\n }): Promise<SddSubtaskSpec[]> {\n let text: string;\n try {\n text = await opts.run(buildPrompt(info.task, info.error, min, max));\n } catch {\n return [];\n }\n\n const json = extractJsonArray(text ?? '');\n if (!json) return [];\n\n let raw: unknown;\n try {\n raw = JSON.parse(json);\n } catch {\n return [];\n }\n if (!Array.isArray(raw)) return [];\n\n const specs: SddSubtaskSpec[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const title = typeof r['title'] === 'string' ? r['title'].trim() : '';\n const description = typeof r['description'] === 'string' ? r['description'].trim() : '';\n if (!title || !description) continue;\n const type = TASK_TYPES.has(r['type'] as TaskType) ? (r['type'] as TaskType) : undefined;\n const priority = PRIORITIES.has(r['priority'] as TaskPriority)\n ? (r['priority'] as TaskPriority)\n : undefined;\n specs.push({ title, description, type, priority });\n if (specs.length >= max) break;\n }\n\n // A split must yield at least `min` genuinely smaller pieces — otherwise it's\n // not a decomposition and we let the supervisor retry instead.\n return specs.length >= min ? specs : [];\n };\n}\n","// makePreferSideConflictResolver — a conservative, opt-in merge-conflict resolver\n// for an SDD parallel run's worktree integration.\n//\n// Wired as `SddParallelRunOptions.conflictResolver`, it is consulted when a\n// completed task's worktree can't squash-merge cleanly. It rewrites each\n// conflicted file by keeping ONE side of every conflict hunk:\n// • 'incoming' — the worktree's changes (theirs); good for generated artefacts\n// a worker is expected to regenerate wholesale.\n// • 'base' — the already-merged base (ours); discards the worktree's edit.\n// The WorktreeManager re-stages and REJECTS the resolution if any conflict marker\n// survives (`git diff --cached --check`), so a malformed rewrite degrades safely\n// to the conservative retry-on-fresh-base path rather than corrupting the base.\n//\n// This is intentionally blunt (no semantic merge). It is OFF by default — callers\n// opt in explicitly — because auto-picking a side can silently drop work.\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { join, isAbsolute } from 'node:path';\nimport type { TaskNode } from '../types/task-graph.js';\n\nexport type ConflictSide = 'incoming' | 'base';\n\nconst START = '<<<<<<<';\nconst BASE = '|||||||';\nconst SEP = '=======';\nconst END = '>>>>>>>';\n\n/**\n * Resolve every standard git conflict hunk in `text` by keeping `side`. Handles\n * both 2-way (`<<<<<<< / ======= / >>>>>>>`) and diff3 (`||||||| base`) markers.\n * Returns the rewritten text (markers removed).\n */\nexport function resolveConflictText(text: string, side: ConflictSide): string {\n const out: string[] = [];\n // 'normal' | 'ours' | 'base' | 'theirs'\n let state: 'normal' | 'ours' | 'base' | 'theirs' = 'normal';\n for (const line of text.split('\\n')) {\n const marker = line.slice(0, 7);\n if (state === 'normal' && marker === START) {\n state = 'ours';\n continue;\n }\n if (state !== 'normal' && marker === BASE) {\n state = 'base';\n continue;\n }\n if (state !== 'normal' && marker === SEP) {\n state = 'theirs';\n continue;\n }\n if (state !== 'normal' && marker === END) {\n state = 'normal';\n continue;\n }\n if (state === 'normal') out.push(line);\n else if (state === 'ours' && side === 'base') out.push(line);\n else if (state === 'theirs' && side === 'incoming') out.push(line);\n // 'base' section + the non-selected side are dropped.\n }\n return out.join('\\n');\n}\n\n/** True when `text` still contains a git conflict marker line. */\nexport function hasConflictMarkers(text: string): boolean {\n return text.split('\\n').some((l) => {\n const m = l.slice(0, 7);\n return m === START || m === SEP || m === END || m === BASE;\n });\n}\n\n/**\n * Build a `conflictResolver` that keeps `side` of every hunk in each conflicted\n * file. Returns false (abort → conservative fail) if any file can't be read,\n * written, or still has markers after the rewrite.\n */\nexport function makePreferSideConflictResolver(side: ConflictSide) {\n return async function conflictResolver(info: {\n task: TaskNode;\n conflictFiles: string[];\n cwd: string;\n }): Promise<boolean> {\n if (info.conflictFiles.length === 0) return false;\n for (const rel of info.conflictFiles) {\n const abs = isAbsolute(rel) ? rel : join(info.cwd, rel);\n let content: string;\n try {\n content = await readFile(abs, 'utf8');\n } catch {\n return false; // can't read → don't risk a partial resolution\n }\n const resolved = resolveConflictText(content, side);\n if (hasConflictMarkers(resolved)) return false; // refuse a half-resolved file\n try {\n await writeFile(abs, resolved, 'utf8');\n } catch {\n return false;\n }\n }\n return true;\n };\n}\n\nexport interface LlmConflictResolverOptions {\n /** Runs one self-contained, isolated LLM turn and resolves its final text. */\n run: (prompt: string) => Promise<string>;\n /**\n * Reject a resolution that shrinks the file below this fraction of its original\n * non-marker line count — a crude guard against the model dropping content.\n * Default 0.5.\n */\n minRetainedFraction?: number;\n}\n\n/** Strip a single surrounding ``` code fence (any/no language) if present. */\nfunction unfence(text: string): string {\n const m = text.match(/^[\\s\\S]*?```[^\\n]*\\n([\\s\\S]*?)\\n```[\\s\\S]*$/);\n return m?.[1] !== undefined ? m[1] : text.trim();\n}\n\n/** Original line count ignoring conflict-marker lines (the resolution baseline). */\nfunction nonMarkerLineCount(text: string): number {\n return text.split('\\n').filter((l) => {\n const m = l.slice(0, 7);\n return m !== START && m !== SEP && m !== END && m !== BASE;\n }).length;\n}\n\n/**\n * Build an LLM-backed `conflictResolver`: for each conflicted file it asks the\n * model (via one isolated `run` turn) to produce the fully resolved file and\n * writes it back. Heavily guarded — returns false (→ conservative abort/retry)\n * if the model leaves a marker, returns junk, or drops too much content. The\n * WorktreeManager STILL rejects any surviving marker, and (when a `verifyTask`\n * is configured) the run re-verifies the integrated base and reverts a\n * regression — so a bad LLM merge can never silently stick. OFF by default.\n */\nexport function makeLlmConflictResolver(opts: LlmConflictResolverOptions) {\n const minFraction = opts.minRetainedFraction ?? 0.5;\n\n return async function conflictResolver(info: {\n task: TaskNode;\n conflictFiles: string[];\n cwd: string;\n }): Promise<boolean> {\n if (info.conflictFiles.length === 0) return false;\n for (const rel of info.conflictFiles) {\n const abs = isAbsolute(rel) ? rel : join(info.cwd, rel);\n let content: string;\n try {\n content = await readFile(abs, 'utf8');\n } catch {\n return false;\n }\n if (!hasConflictMarkers(content)) continue; // already clean — nothing to do\n\n const prompt = [\n 'You are resolving a git MERGE CONFLICT in a single file. Below is the',\n 'full file with conflict markers (<<<<<<<, =======, >>>>>>>, and possibly',\n '||||||| for diff3). Combine both sides into the correct, complete file —',\n 'keep ALL non-conflicting content verbatim and reconcile each hunk sensibly.',\n 'Return ONLY the fully resolved file contents (no conflict markers, no',\n 'commentary), optionally wrapped in a single ``` code fence.',\n '',\n `File: ${rel}`,\n '--- BEGIN ---',\n content,\n '--- END ---',\n ].join('\\n');\n\n let out: string;\n try {\n out = await opts.run(prompt);\n } catch {\n return false;\n }\n const resolved = unfence(out ?? '');\n if (!resolved.trim() || hasConflictMarkers(resolved)) return false;\n // Content-drop guard: a resolution far smaller than the original almost\n // certainly lost real work — abort rather than write it.\n if (resolved.split('\\n').length < Math.floor(nonMarkerLineCount(content) * minFraction)) {\n return false;\n }\n try {\n await writeFile(abs, resolved, 'utf8');\n } catch {\n return false;\n }\n }\n return true;\n };\n}\n"]}
|