opencode-swarm 7.142.1 → 7.143.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.
Files changed (45) hide show
  1. package/.opencode/skills/execute/SKILL.md +1 -1
  2. package/.opencode/skills/phase-wrap/SKILL.md +2 -2
  3. package/dist/cli/{config-doctor-2a3qmp5p.js → config-doctor-t1r5qwxk.js} +2 -2
  4. package/dist/cli/{core-h9z49ant.js → core-e30p4vz9.js} +1 -1
  5. package/dist/cli/{curator-mtz194wy.js → curator-ctasdmmq.js} +17 -17
  6. package/dist/cli/{curator-llm-factory-9fr243kj.js → curator-llm-factory-y9xg7k6k.js} +17 -17
  7. package/dist/cli/{evidence-summary-service-fgckng0a.js → evidence-summary-service-7bmg5r8y.js} +6 -6
  8. package/dist/cli/{gate-evidence-ppna7em4.js → gate-evidence-1v0cj4c6.js} +2 -2
  9. package/dist/cli/{guardrail-explain-ejdvvnjz.js → guardrail-explain-6x9psbwz.js} +18 -18
  10. package/dist/cli/{guardrail-log-adjs25ye.js → guardrail-log-pma4m8vr.js} +3 -3
  11. package/dist/cli/{hive-promoter-jejme31e.js → hive-promoter-g16grej1.js} +17 -17
  12. package/dist/cli/{index-kbshtwha.js → index-15h4dpsn.js} +3 -3
  13. package/dist/cli/{index-0r4qs243.js → index-1g473508.js} +19 -19
  14. package/dist/cli/{index-ajfa2wmj.js → index-28jr28fg.js} +3 -3
  15. package/dist/cli/{index-ktazgjqw.js → index-2n8y67b4.js} +2 -2
  16. package/dist/cli/{index-sdqtecsd.js → index-336ra397.js} +1 -1
  17. package/dist/cli/{index-vy11zjvh.js → index-6texwk9p.js} +1 -1
  18. package/dist/cli/{index-vefjxxmb.js → index-96h1v2jw.js} +1 -1
  19. package/dist/cli/{index-9wmx9ca8.js → index-9v53ez3a.js} +2 -2
  20. package/dist/cli/{index-2mb5y2w1.js → index-fhxh447f.js} +1 -1
  21. package/dist/cli/{index-gtkk5rx7.js → index-fprxtq3q.js} +3 -3
  22. package/dist/cli/{index-bkkxxwcd.js → index-g0pbvfhw.js} +1 -1
  23. package/dist/cli/{index-xfhe29z3.js → index-htmsm37t.js} +5 -5
  24. package/dist/cli/{index-j02ez59y.js → index-keskta0w.js} +4 -4
  25. package/dist/cli/{index-9kf3mj08.js → index-kxpz3ncd.js} +1 -1
  26. package/dist/cli/{index-h7ye3bzp.js → index-m4v9kab1.js} +47 -47
  27. package/dist/cli/{index-rthq1a6w.js → index-n96ay8w4.js} +1 -1
  28. package/dist/cli/{index-we279je2.js → index-q8st0mtw.js} +1 -1
  29. package/dist/cli/{index-xah70t2t.js → index-r0tn9kpa.js} +1 -1
  30. package/dist/cli/{index-bb4pcn58.js → index-s89y08tk.js} +2 -2
  31. package/dist/cli/{index-myav90y6.js → index-sb16w4wj.js} +1 -1
  32. package/dist/cli/{index-k1xsjzm3.js → index-x6qq39e9.js} +3 -3
  33. package/dist/cli/index.js +17 -17
  34. package/dist/cli/{knowledge-escalator-0b80ryka.js → knowledge-escalator-1b2hmcgn.js} +6 -6
  35. package/dist/cli/{knowledge-events-8x2wt562.js → knowledge-events-vx4fqjzb.js} +4 -4
  36. package/dist/cli/{knowledge-store-d0xj6wht.js → knowledge-store-t2qyr4yr.js} +1 -1
  37. package/dist/cli/{knowledge-validator-ewfj679a.js → knowledge-validator-c7871bjc.js} +2 -2
  38. package/dist/cli/{scan-cursor-hfyz7zpw.js → scan-cursor-pnbpfjjc.js} +2 -2
  39. package/dist/cli/{schema-ney3c685.js → schema-47xpcghn.js} +1 -1
  40. package/dist/cli/{scope-persistence-dbfgs7gh.js → scope-persistence-wxx1jpfw.js} +4 -4
  41. package/dist/cli/{skill-generator-p651jex5.js → skill-generator-s456hfta.js} +7 -7
  42. package/dist/cli/{worktree-isolation-513vx61s.js → worktree-isolation-d0xgp705.js} +17 -17
  43. package/dist/hooks/delegation-gate.d.ts +65 -0
  44. package/dist/index.js +22 -18
  45. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.142.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.143.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -751,8 +751,19 @@ Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:""
751
751
 
752
752
  (no recorded snapshot to diff against)`;throw Error(message)}}function isPlainObject3(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function readSignalField(source,key){try{return source[key]}catch{return}}function pushSignalValue(parts,value){if(typeof value==="string"){parts.push(value);return}if(typeof value==="number"||typeof value==="boolean")parts.push(String(value))}function appendSelectedFields(parts,source,keys){for(let key of keys)pushSignalValue(parts,readSignalField(source,key))}function appendNestedErrorSignal(parts,value){if(typeof value==="string"){parts.push(value);return}if(value instanceof Error){parts.push(value.name,value.message),appendSelectedFields(parts,value,["code","status","statusCode"]);return}if(!isPlainObject3(value))return;appendSelectedFields(parts,value,["code","status","statusCode","message","error_type"])}function extractErrorSignal(errorContent){if(typeof errorContent==="string")return errorContent;if(errorContent==null)return"";let parts=[];try{if(errorContent instanceof Error)return parts.push(errorContent.name,errorContent.message),appendSelectedFields(parts,errorContent,["code","status","statusCode"]),parts.join(" ");if(!isPlainObject3(errorContent))return"";appendSelectedFields(parts,errorContent,["code","status","statusCode","message","error_type"]),appendNestedErrorSignal(parts,readSignalField(errorContent,"error"));let metadata=readSignalField(errorContent,"metadata");if(isPlainObject3(metadata))appendSelectedFields(parts,metadata,["code","status","statusCode","error_type"]);appendNestedErrorSignal(parts,readSignalField(errorContent,"cause"))}catch{return parts.join(" ")}return parts.join(" ")}function touchNoOpSession(sessionID,count){toolCallsSinceLastWrite.delete(sessionID),toolCallsSinceLastWrite.set(sessionID,count),evictNoOpStateIfOverBound()}function evictNoOpStateIfOverBound(){while(toolCallsSinceLastWrite.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=toolCallsSinceLastWrite.keys().next().value;if(stalestKey===void 0)break;toolCallsSinceLastWrite.delete(stalestKey),noOpWarningIssued.delete(stalestKey),noOpStrongWarningIssued.delete(stalestKey)}while(noOpWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpWarningIssued.delete(stalestKey)}while(noOpStrongWarningIssued.size>MAX_TRACKED_NO_OP_SESSIONS){let stalestKey=noOpStrongWarningIssued.values().next().value;if(stalestKey===void 0)break;noOpStrongWarningIssued.delete(stalestKey)}}function extractPhaseNumber2(phaseString){if(!phaseString)return 1;let match=phaseString.match(/^Phase (\d+):/);return match?parseInt(match[1],10):1}function isWriteTool2(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isGateTool(toolName){let normalized=normalizeToolName(toolName);return["diff","syntax_check","placeholder_scan","imports","lint","build_check","pre_check_batch","secretscan","sast_scan","quality_budget"].includes(normalized)}function isAgentDelegation(toolName,args2){let normalized=normalizeToolName(toolName);if(normalized!=="Task"&&normalized!=="task")return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function createGuardrailsHooks(directory,directoryOrConfig,config2,authorityConfig,worktreeBaseDirOverrides,resolveAgentModel){let guardrailsConfig;if(directory&&typeof directory==="object"&&"enabled"in directory)warn("[guardrails] Legacy call without directory, falling back to process.cwd()"),guardrailsConfig=directory;else if(directoryOrConfig&&typeof directoryOrConfig==="object"&&"enabled"in directoryOrConfig)guardrailsConfig=directoryOrConfig;else guardrailsConfig=config2;let effectiveDirectory=(()=>{if(typeof directory==="string")return directory;let cwd=process.cwd();return warn(`[guardrails] effectiveDirectory resolved to process.cwd() "${cwd}" — `+"pass an explicit directory string to createGuardrailsHooks to avoid .swarm artifacts in wrong locations"),cwd})();if(guardrailsConfig?.enabled===!1)return{toolBefore:async()=>{},toolAfter:async()=>{},messagesTransform:async()=>{}};let precomputedAuthorityRules=buildEffectiveRules(authorityConfig),verifierPaths=authorityConfig?.verifier_config_paths;if(verifierPaths&&verifierPaths.length>0){let existingArchitect=precomputedAuthorityRules.architect??{};precomputedAuthorityRules.architect={...existingArchitect,blockedGlobs:[...existingArchitect.blockedGlobs??[],...verifierPaths]}}let universalDenyPrefixes=authorityConfig?.universal_deny_prefixes??[],cfg=guardrailsConfig,requiredQaGates=cfg.qa_gates?.required_tools??["diff","syntax_check","placeholder_scan","lint","pre_check_batch"],requireReviewerAndTestEngineer=cfg.qa_gates?.require_reviewer_test_engineer??!0,interpreterAllowedAgents=cfg.interpreter_allowed_agents,shellAuditEnabled=cfg.shell_audit_log??!0,shellAuditPath=path77.join(effectiveDirectory,".swarm","session","shell-audit.jsonl"),consecutiveNoToolTurns=new Map,lastCountedAssistantMsgId=new Map,pendingReviewerScopeWrites=new Map,pendingGateTasksBySession=new Map,takePendingGateTask=(sessionID,callID)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID),pending=sessionTasks?.get(callID);if(sessionTasks){if(sessionTasks.delete(callID),sessionTasks.size===0)pendingGateTasksBySession.delete(sessionID)}return pending},rememberPendingGateTask=(sessionID,callID,taskId,generation)=>{let sessionTasks=pendingGateTasksBySession.get(sessionID);if(!sessionTasks){if(pendingGateTasksBySession.size>=MAX_PENDING_GATE_RECEIPT_SESSIONS)throw Error("GATE_RECEIPT_CAPACITY: too many sessions have live gate calls; wait for a pending gate call to finish");sessionTasks=new Map,pendingGateTasksBySession.set(sessionID,sessionTasks)}if(!sessionTasks.has(callID)&&sessionTasks.size>=MAX_PENDING_GATE_RECEIPTS_PER_SESSION)throw Error("GATE_RECEIPT_CAPACITY: this session has too many live gate calls; wait for a pending gate call to finish");sessionTasks.set(callID,{sessionID,taskId,generation})},scopeLeaseRenewal=createScopeLeaseRenewalTracker(),rememberReviewerScopeWrite=(input)=>{if(!pendingReviewerScopeWrites.has(input.callID)&&pendingReviewerScopeWrites.size>=256){let oldest=pendingReviewerScopeWrites.keys().next().value;if(oldest!==void 0)pendingReviewerScopeWrites.delete(oldest)}let pending=pendingReviewerScopeWrites.get(input.callID)??[],candidate={parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,file:input.file};if(!pending.some((entry)=>entry.parentSessionID===candidate.parentSessionID&&entry.taskId===candidate.taskId&&entry.coderCallID===candidate.coderCallID&&entry.file===candidate.file)&&pending.length<256)pending.push(candidate);pendingReviewerScopeWrites.set(input.callID,pending)},executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},baseToolBefore=createToolBeforeHandler({effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditPath,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,rememberReviewerScopeWrite,rememberScopeLeaseCandidate:scopeLeaseRenewal.remember,getSandboxExecutor:_internals59.getSandboxExecutor}),toolBefore=async(input,output)=>{if(isGateTool(input.tool)){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId;if(taskId){let workflow=isStrictTaskId2(taskId)?getTaskWorkflowSnapshot(await readTaskEvidence(effectiveDirectory,taskId)):null;rememberPendingGateTask(input.sessionID,input.callID,taskId,workflow?.generation??0)}}try{await baseToolBefore(input,output)}catch(error49){throw takePendingGateTask(input.sessionID,input.callID),error49}},messagesTransform=createMessagesTransformHandler({effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId,resolveAgentModel});return{toolBefore,toolAfter:async(input,output)=>{let pendingGateTask=takePendingGateTask(input.sessionID,input.callID)??(_internals59.allowUncorrelatedGateReceipts?(()=>{let testSession=swarmState.agentSessions.get(input.sessionID);return testSession?{sessionID:input.sessionID,taskId:testSession.currentTaskId??`${input.sessionID}:unknown`,generation:testSession.currentTaskId&&isStrictTaskId2(testSession.currentTaskId)?testSession.taskWorkflowCache?.get(testSession.currentTaskId)?.generation??0:0}:void 0})():void 0),pendingReviewerScopeWrite=pendingReviewerScopeWrites.get(input.callID);pendingReviewerScopeWrites.delete(input.callID);let correlatedExecution=takeToolExecution(input.sessionID,input.callID);if(correlatedExecution&&!isToolExecutionCurrent(input.sessionID,correlatedExecution)){await scopeLeaseRenewal.consume({...input,output:null});return}let malformedOutput=!output||typeof output!=="object",safeOutput=malformedOutput?{title:"",output:"",metadata:null}:output;await scopeLeaseRenewal.consume({...input,output:malformedOutput?null:safeOutput});let session=swarmState.agentSessions.get(input.sessionID);if(session){if(isGateTool(input.tool)&&pendingGateTask?.sessionID===input.sessionID){let taskId=pendingGateTask.taskId;if(!session.gateLog.has(taskId))session.gateLog.set(taskId,new Set);session.gateLog.get(taskId)?.add(input.tool);let outputStr=typeof safeOutput.output==="string"?safeOutput.output:"";if(normalizeToolName(input.tool)==="pre_check_batch"){let verdict=decodePreCheckResult(safeOutput.output);if(verdict.kind==="fail"||verdict.kind==="invalid"){if(session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now(),code:verdict.code},verdict.kind==="fail"&&isStrictTaskId2(taskId))try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_failed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){warn("Failed to persist Stage A failure",{taskId,error:String(err)})}}else if(verdict.kind==="pass"){if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)==="pre_check_batch")session.lastGateFailure=null;if(!isStrictTaskId2(taskId))advanceTaskState(session,taskId,"pre_check_passed");try{let updated=await transitionTaskWorkflowEvidence(effectiveDirectory,taskId,{type:"stage_a_passed",expectedGeneration:pendingGateTask.generation,transitionId:`pre-check:${input.callID}`}),next=getTaskWorkflowSnapshot(updated);session.taskWorkflowStates.set(taskId,next.state),updateTaskWorkflowCache(session,taskId,next)}catch(err){warn("Failed to advance task state after pre_check_batch pass",{taskId,error:String(err)})}}}else if(safeOutput.output===null||safeOutput.output===void 0||outputStr.includes("FAIL")||outputStr.includes("error")||outputStr.toLowerCase().includes("gates_passed: false"))session.lastGateFailure={tool:input.tool,taskId,timestamp:Date.now()};else if(session.lastGateFailure?.taskId===taskId&&normalizeToolName(session.lastGateFailure.tool)===normalizeToolName(input.tool))session.lastGateFailure=null}let inputArgs=input.args??getStoredInputArgs(input.callID),delegation=isAgentDelegation(input.tool,inputArgs);if(delegation.isDelegation&&(delegation.targetAgent==="reviewer"||delegation.targetAgent==="test_engineer")){let currentPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan){let phaseString=extractCurrentPhaseFromPlan(plan);currentPhase=extractPhaseNumber2(phaseString)}}catch(error49){log("[Guardrails] loadPlan failed during reviewer tracking",{error:error49 instanceof Error?error49.message:String(error49)})}let count=session.reviewerCallCount.get(currentPhase)??0;session.reviewerCallCount.set(currentPhase,count+1)}if(delegation.isDelegation&&delegation.targetAgent==="coder"){let exactGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:input.sessionID,coderCallID:input.callID}),completedTaskId=exactGeneration?.taskId??session.lastCoderDelegationTaskId;if(completedTaskId){session.currentTaskId=completedTaskId;let exactGenerationFiles=exactGeneration?.modifiedFiles??session.modifiedFilesThisCoderTask;if(!session.revisionLimitHit){if(session.coderRevisions++,session.coderRevisions>1&&session.qaSkipCount===0){let conflictPhase=1;try{let plan=await loadPlan(effectiveDirectory);if(plan)conflictPhase=extractPhaseNumber2(extractCurrentPhaseFromPlan(plan))}catch{}resolveAgentConflict({sessionID:input.sessionID,phase:conflictPhase,taskId:session.currentTaskId??void 0,sourceAgent:"reviewer",targetAgent:"coder",conflictType:"feedback_rejection",rejectionCount:session.coderRevisions-1,summary:`Coder revision ${session.coderRevisions} for task ${session.currentTaskId??"unknown"}`}),session.lastDelegationReason="review_rejected"}let maxRevisions=cfg.max_coder_revisions??5;if(session.coderRevisions>=maxRevisions)session.revisionLimitHit=!0,telemetry.revisionLimitHit(input.sessionID,session.agentName),pushAdvisory(session,`CODER REVISION LIMIT: Agent has been revised ${session.coderRevisions} times (max: ${maxRevisions}) for task ${session.currentTaskId??"unknown"}. Escalate to user or consider a fundamentally different approach.`),swarmState.pendingEvents++}if(session.partialGateWarningsIssuedForTask?.delete(session.currentTaskId),session.declaredCoderScope!==null){let undeclaredFiles=exactGenerationFiles.map((f)=>f.replace(/[\r\n\t]/g,"_")).filter((f)=>!isInDeclaredScope(f,session.declaredCoderScope,directory));if(undeclaredFiles.length>=1){let safeTaskId=String(session.currentTaskId??"").replace(/[\r\n\t]/g,"_");session.lastScopeViolation=`Scope violation for task ${safeTaskId}: ${undeclaredFiles.length} undeclared files modified: `+undeclaredFiles.join(", "),session.scopeViolationDetected=!0,telemetry.scopeViolation(input.sessionID,session.agentName,session.currentTaskId??"unknown","undeclared files modified")}}session.modifiedFilesThisCoderTask=[]}}}recordExecutionStallToolAfter({sessionID:input.sessionID,tool:input.tool,callID:input.callID,args:input.args??getStoredInputArgs(input.callID),output:safeOutput,directory:effectiveDirectory,options:executionStallOptions});let sessionId=input.sessionID,normalizedToolName=normalizeToolName(input.tool),isSubagentDispatch=new Set(["dispatch_lanes","dispatch_lanes_async"]).has(normalizedToolName)||isAgentDelegation(input.tool,input.args??getStoredInputArgs(input.callID)).isDelegation;if(isWriteTool2(normalizedToolName)||isSubagentDispatch)touchNoOpSession(sessionId,0),noOpWarningIssued.delete(sessionId),noOpStrongWarningIssued.delete(sessionId);else{let count=(toolCallsSinceLastWrite.get(sessionId)??0)+1;touchNoOpSession(sessionId,count);let threshold=cfg.no_op_warning_threshold??15,strongThreshold=threshold*2;if(count>=threshold&&!noOpWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`WARNING: Agent has made ${count} tool calls with no file modifications and no subagent dispatches. If you are stuck, state what is blocking you and report BLOCKED rather than continuing to probe.`);if(count>=strongThreshold&&!noOpStrongWarningIssued.has(sessionId)&&session?.pendingAdvisoryMessages)noOpStrongWarningIssued.add(sessionId),evictNoOpStateIfOverBound(),pushAdvisory(session,`CRITICAL: Agent has made ${count} tool calls with no file modifications and no subagent dispatches — twice the point at which you were first warned. STOP investigating; report BLOCKED to the user now with what you tried.`),telemetry.noOpStrongWarning(sessionId,session.agentName,count,strongThreshold)}let outcome=malformedOutput?{kind:"unknown",signal:""}:classifyToolOutcome(input,safeOutput,correlatedExecution);if(pendingReviewerScopeWrite&&classifyTaskResult(safeOutput)==="success"){let completedFingerprints=[],aggregateBytes=0,captureFailed=!1;for(let pendingWrite of pendingReviewerScopeWrite){let fingerprint2=captureReviewerScopeFileFingerprint(effectiveDirectory,pendingWrite.file,MAX_REVIEWER_SCOPE_FINGERPRINT_AGGREGATE_BYTES-aggregateBytes);if(!fingerprint2){captureFailed=!0;break}if(fingerprint2.kind==="file")aggregateBytes+=fingerprint2.size;completedFingerprints.push({pendingWrite,fingerprint:fingerprint2})}if(!captureFailed&&completedFingerprints.length===pendingReviewerScopeWrite.length&&aggregateBytes<=MAX_REVIEWER_SCOPE_FINGERPRINT_AGGREGATE_BYTES)for(let{pendingWrite,fingerprint:fingerprint2}of completedFingerprints)recordReviewerScopeGenerationFileFingerprint({parentSessionID:pendingWrite.parentSessionID,taskId:pendingWrite.taskId,coderCallID:pendingWrite.coderCallID,fingerprint:fingerprint2})}if(outcome.kind==="fatal")recordNonTransientFailure(input.sessionID,outcome.category,outcome.signal);else if(outcome.kind==="success"||outcome.kind==="neutral")clearNonTransientCircuit(input.sessionID);else if(outcome.kind==="failure"){let circuitSignal=extractErrorSignal(outcome.signal),circuitStatus=extractStatusCode(circuitSignal),circuitIsTransient=circuitStatus!==null&&TRANSIENT_STATUS_CODES.has(circuitStatus)||TRANSIENT_MODEL_ERROR_PATTERN.test(circuitSignal),circuitIsDegraded=DEGRADED_ERROR_PATTERN.test(circuitSignal);if(circuitIsTransient||circuitIsDegraded)clearNonTransientCircuit(input.sessionID);else recordNonTransientFailure(input.sessionID,"general_permanent",outcome.signal)}let window2=getActiveWindow(input.sessionID);if(!window2)return;if(outcome.kind==="fatal"){window2.consecutiveErrors++;return}if(outcome.kind==="failure"){let errorSignal=extractErrorSignal(outcome.signal),extractedStatus=extractStatusCode(errorSignal),isTransientStatusCode=extractedStatus!==null&&TRANSIENT_STATUS_CODES.has(extractedStatus),isTransientPatternMatch=TRANSIENT_MODEL_ERROR_PATTERN.test(errorSignal),isTransientMatch=isTransientStatusCode||isTransientPatternMatch,maxTransientRetries=cfg.max_transient_retries??5,isTransient=!!session&&isTransientMatch&&window2.transientRetryCount<maxTransientRetries,isDegraded=!isTransient&&DEGRADED_ERROR_PATTERN.test(errorSignal);if(isTransient)window2.transientRetryCount++;else if(isDegraded){let isContentFilter=CONTENT_FILTER_PATTERN.test(errorSignal);if(session&&!session.modelFallbackExhausted){session.model_fallback_index++;let swarmId=_internals59.extractSwarmIdFromAgentName(session.agentName),baseAgentName=session.agentName?session.agentName.replace(/^[^_]+[_]/,""):"",fallbackModels=_internals59.getSwarmAgents(swarmId)?.[baseAgentName]?.fallback_models;if(session.modelFallbackExhausted=!fallbackModels||session.model_fallback_index>fallbackModels.length,isContentFilter)pushAdvisory(session,`DEGRADED: Content policy violation detected (content filter). Fallback model ${session.model_fallback_index}/${fallbackModels?.length??0} considered. The input may need content modification to comply with provider policies.`);else pushAdvisory(session,`DEGRADED: Context-limit or token-limit error detected. Fallback model ${session.model_fallback_index}/${fallbackModels?.length??0} considered. Consider reducing input size or using /swarm handoff to switch models.`)}else if(session)if(isContentFilter)pushAdvisory(session,"DEGRADED: Content policy violation detected (content filter). No fallback models available. The input may need content modification to comply with provider policies.");else pushAdvisory(session,'DEGRADED: Context-limit or token-limit error detected. No fallback models available. Consider reducing input size or add "fallback_models" config.')}else window2.consecutiveErrors++;let modelFallbackAdvisoryEmitted=!1;if(session&&isTransientMatch&&!session.modelFallbackExhausted&&!isDegraded){session.model_fallback_index++;let swarmId=_internals59.extractSwarmIdFromAgentName(session.agentName),baseAgentName=session.agentName?session.agentName.replace(/^[^_]+[_]/,""):"",swarmAgents=_internals59.getSwarmAgents(swarmId),fallbackModels=swarmAgents?.[baseAgentName]?.fallback_models;session.modelFallbackExhausted=!fallbackModels||session.model_fallback_index>fallbackModels.length;let fallbackModel=_internals59.resolveFallbackModel(baseAgentName,session.model_fallback_index,swarmAgents),primaryModel=swarmAgents?.[baseAgentName]?.model??"default";if(fallbackModel){if(swarmAgents?.[baseAgentName])swarmAgents[baseAgentName].model=fallbackModel;pushAdvisory(session,`MODEL FALLBACK: Applied fallback model "${fallbackModel}" (attempt ${session.model_fallback_index}). Using /swarm handoff to reset to primary model.`),modelFallbackAdvisoryEmitted=!0}else pushAdvisory(session,`MODEL FALLBACK: Transient model error detected (attempt ${session.model_fallback_index}). No fallback models configured for this agent. Add "fallback_models": ["model-a", "model-b"] to the agent's config in opencode-swarm.json.`),modelFallbackAdvisoryEmitted=!0;telemetry.modelFallback(input.sessionID,session.agentName,primaryModel,fallbackModel??"none","transient_model_error"),swarmState.pendingEvents++}if(session&&isTransient&&isTransientMatch&&!modelFallbackAdvisoryEmitted){if(!session.pendingAdvisoryMessages?.some((m)=>m.startsWith("TRANSIENT ERROR:")||m.startsWith("MODEL FALLBACK:")))pushAdvisory(session,`TRANSIENT ERROR: Provider error detected (attempt ${window2.transientRetryCount}/${maxTransientRetries}). Retrying...`)}}else if(window2.consecutiveErrors=0,window2.transientRetryCount=0,window2.lastSuccessTimeMs=Date.now(),session){if(session.model_fallback_index>0)session.model_fallback_index=0,session.modelFallbackExhausted=!1}},messagesTransform}}var MAX_PENDING_GATE_RECEIPTS_PER_SESSION=256,MAX_PENDING_GATE_RECEIPT_SESSIONS=500,_internals59,SPEC_DRIFT_BLOCKED_TOOLS,DEGRADED_ERROR_PATTERN,CONTENT_FILTER_PATTERN,MAX_TRACKED_NO_OP_SESSIONS=200,toolCallsSinceLastWrite,noOpWarningIssued,noOpStrongWarningIssued;var init_guardrails=__esm(()=>{init_agents2();init_constants();init_schema();init_gate_evidence();init_manager();init_executor();init_scope_lease_renewal();init_state2();init_telemetry();init_utils();init_logger();init_provider_error_classification();init_spec_hash();init_task_id();init_conflict_resolution();init_extractors();init_normalize_tool_name();init_reviewer_scope_file_fingerprint();init_task_result_classifier();init_destructive_command();init_execution_stall();init_file_authority();init_helpers();init_messages_transform();init_nontransient_circuit();init_pre_check_result();init_stored_input_args();init_tool_before();init_helpers();_internals59={extractSwarmIdFromAgentName,getSwarmAgents,getMostRecentAssistantText,getProviderFailureFingerprint,isTransientProviderFailureText,resolveFallbackModel,dcCheckJunctionCreation,extractErrorSignal,getSandboxExecutor:getExecutor,allowUncorrelatedGateReceipts:!1,MAX_PENDING_GATE_RECEIPTS_PER_SESSION,MAX_PENDING_GATE_RECEIPT_SESSIONS,noOpStateSize:()=>toolCallsSinceLastWrite.size,hasNoOpState:(sessionID)=>toolCallsSinceLastWrite.has(sessionID)},SPEC_DRIFT_BLOCKED_TOOLS=new Set(["save_plan","update_task_status","phase_complete","lean_turbo_run_phase","lean_turbo_acquire_locks"]);DEGRADED_ERROR_PATTERN=/context.?length|token.?(limit|budget)|input.?too.?long|content.?filter|exceeds?.?(maximum.?)?tokens|maximum.?context|context.?window|too.?many.?tokens|prompt.?too.?long|message.?too.?long|request.?too.?large|max.?tokens/i,CONTENT_FILTER_PATTERN=/content.?filter/i,toolCallsSinceLastWrite=new Map,noOpWarningIssued=new Set,noOpStrongWarningIssued=new Set});var init_guardrails2=__esm(()=>{init_file_authority();init_guardrails();init_stored_input_args()});var exports_task_envelope={};__export(exports_task_envelope,{parseTaskEnvelope:()=>parseTaskEnvelope,extractDispatchIds:()=>extractDispatchIds});function parseTaskEnvelope(text){if(typeof text!=="string"||text.length===0)return null;let match=text.match(TASK_ENVELOPE_RE);if(!match)return null;let sessionId=match[1],rawState=match[2],state=rawState==="canceled"?"cancelled":rawState;if(!sessionId)return null;let summary=extractTagText(text,"summary"),resultRaw=state==="error"||state==="cancelled"?extractTagText(text,"task_error")??extractTagText(text,"task_result"):extractTagText(text,"task_result"),bounded=boundEnvelopeText(resultRaw);return{sessionId,state,...summary!==void 0?{summary}:{},...state==="error"||state==="cancelled"?{...bounded?{errorText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}:{},...state!=="error"&&state!=="cancelled"&&bounded?{resultText:bounded.text,resultChars:bounded.chars,resultTruncated:bounded.truncated}:{}}}function extractTagText(text,tag){let re=new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`),match=text.match(re);if(!match)return;return match[1]}function boundEnvelopeText(text){if(text===void 0)return;if(text.length<=20000)return{text,chars:text.length,truncated:!1};let suffix=`
753
753
  [... ${text.length-20000} chars truncated by task-envelope ...]`,maxContent=Math.max(0,20000-suffix.length);return{text:`${text.slice(0,maxContent)}${suffix}`,chars:text.length,truncated:!0}}function extractDispatchIds(output){let subagentSessionId=null,jobId=null;if(typeof output==="object"&&output!==null){let o=output,metadata=o.metadata;if(typeof metadata==="object"&&metadata!==null){let rawJobId=metadata.jobId;if(typeof rawJobId==="string"&&rawJobId.length>0)jobId=rawJobId}let rendered=o.output,envelope=parseTaskEnvelope(typeof rendered==="string"?rendered:void 0);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}else if(typeof output==="string"){let envelope=parseTaskEnvelope(output);if(envelope&&envelope.state==="running")subagentSessionId=envelope.sessionId}if(!subagentSessionId&&jobId)subagentSessionId=jobId;return{subagentSessionId,jobId}}var TASK_ENVELOPE_RE;var init_task_envelope=__esm(()=>{TASK_ENVELOPE_RE=/<task\s+id="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"\s*>/});import*as fs48 from"node:fs";import*as path78 from"node:path";function clearPendingCoderScope(){pendingCoderScopeByTaskId.clear()}async function prepareCoderScope(directory,input,args2){let plan=await loadPlanJsonOnly(directory);if(!plan){let rawTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"";if(isStrictTaskId2(rawTaskId)){let feedbackScope=await consumePrFeedbackScopeDeclaration(directory,input.sessionID,rawTaskId,input.callID);if(feedbackScope){let directives2=extractTaskFileDirectives(args2);if(directives2.present&&!directives2.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let resolved2=resolveCoderScopeSources({explicitFiles:feedbackScope.files,planFiles:null,fileDirectiveFiles:directives2.files});if(!resolved2.ok)throw Error(formatCoderScopeConflict(resolved2));let binding2=createPrFeedbackScopeBinding({directory,taskId:rawTaskId,files:resolved2.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",workflowSessionId:input.sessionID,workflowRevisionDigest:feedbackScope.revisionDigest});if(!binding2)throw Error("SCOPE_NOT_DECLARED: PR-feedback scope could not be bound to this Task invocation.");return{plan:null,taskId:rawTaskId,declaredFiles:resolved2.files,binding:binding2}}}let planPath=path78.join(directory,".swarm","plan.json");throw Error(`SCOPE_NOT_DECLARED: no valid plan found at ${planPath} (file missing or invalid). Declare a plan via save_plan or run /swarm plan first.`)}let planTaskIds=new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),taskId=resolveDelegatedPlanTaskId(args2,planTaskIds);if(!taskId)throw Error(`SCOPE_NOT_DECLARED: ${describeCoderScopeFailure(args2,planTaskIds)}`);if(!planTaskIds.has(taskId))throw Error(`SCOPE_NOT_DECLARED: task_id "${taskId}" does not match any known plan task id. Known: ${[...planTaskIds].sort().join(", ")||"(none)"}. Update the dispatch or revise the plan.`);let directives=extractTaskFileDirectives(args2);if(directives.present&&!directives.files)throw Error("SCOPE_NOT_DECLARED: FILE: directives are present but empty or ambiguous; provide one complete relative path per FILE: line.");let explicitResolution=resolveScopeBindingFromDisk({directory,plan,taskId,ownerSessionId:input.sessionID,requireDeclaration:!0,includeExpired:!0});if(explicitResolution.status==="ambiguous"||explicitResolution.status==="expired"||explicitResolution.status==="overloaded")throw Error(formatScopeResolutionDiagnostic({resolution:explicitResolution,taskId,sessionId:input.sessionID})??"SCOPE_NOT_DECLARED: durable declaration resolution failed.");let explicitBinding=explicitResolution.status==="found"?explicitResolution.binding:null,declaredFiles=getPlanTaskDeclaredFiles(plan,taskId),resolved=resolveCoderScopeSources({explicitFiles:explicitBinding?.files,planFiles:declaredFiles,fileDirectiveFiles:directives.files});if(!resolved.ok)throw Error(formatCoderScopeConflict(resolved));let binding=createScopeBinding({directory,plan,taskId,files:resolved.files,ownerSessionId:input.sessionID,ownerMessageId:input.callID,dispatchCallId:input.callID,activation:"pending_child",source:resolved.source});if(!binding)throw Error("SCOPE_NOT_DECLARED: coder scope could not be bound to this Task invocation.");return{plan,taskId,declaredFiles,binding}}function isBackgroundTrue(value){return value===!0||value==="true"}function outputLooksLikeBackgroundRunning(output){if(typeof output!=="object"||output===null)return!1;let o=output;if(o.state==="running")return!0;let metadata=o.metadata;return typeof metadata==="object"&&metadata!==null&&metadata.background===!0}function isEnvelope(obj){if(typeof obj!=="object"||obj===null)return!1;let e=obj;return typeof e.taskId==="string"&&typeof e.targetAgent==="string"&&typeof e.action==="string"}function parseDelegationEnvelope(content,directory){let validateEnvelopePaths=(envelope2)=>{if(directory)for(let filePath of envelope2.files){try{validateSwarmPath(directory,filePath)}catch{return null}let resolvedPath=path78.resolve(directory,filePath);if(!fs48.existsSync(resolvedPath))return null}return envelope2};try{let parsed=JSON.parse(content);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{let match=content.match(/\{[\s\S]*\}/);if(match)try{let parsed=JSON.parse(match[0]);if(isEnvelope(parsed))return validateEnvelopePaths(parsed)}catch{}}let lines=content.split(`
754
- `),keyValueMap={};for(let line of lines){let match=line.match(/^([^:]+):\s*(.+)$/);if(match){let key=match[1].trim().toLowerCase(),value=match[2].trim();keyValueMap[key]=value}}let keyNormalization={taskid:"taskId",task_id:"taskId",targetagent:"targetAgent",target_agent:"targetAgent",commandtype:"commandType",command_type:"commandType",acceptancecriteria:"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",technicalcontext:"technicalContext",technical_context:"technicalContext",errorstrategy:"errorStrategy",error_strategy:"errorStrategy",platformnotes:"platformNotes",platform_notes:"platformNotes",action:"action",files:"files"},normalizedMap={};for(let[key,value]of Object.entries(keyValueMap)){let normalized=keyNormalization[key]||key;normalizedMap[normalized]=value}if(Object.keys(normalizedMap).length<3)return null;let requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!normalizedMap[field])return null;let parseArrayField=(value)=>{let parts=value.split(",");if(parts.length===1)parts=value.split(";");return parts.map((s)=>s.trim()).filter((s)=>s.length>0)},envelope={taskId:normalizedMap.taskId,targetAgent:normalizedMap.targetAgent,action:normalizedMap.action,commandType:normalizedMap.commandType,files:parseArrayField(normalizedMap.files),acceptanceCriteria:parseArrayField(normalizedMap.acceptanceCriteria),technicalContext:normalizedMap.technicalContext||""};if(normalizedMap.technicalContext)envelope.technicalContext=normalizedMap.technicalContext;if(normalizedMap.errorStrategy)envelope.errorStrategy=normalizedMap.errorStrategy;if(normalizedMap.platformNotes)envelope.platformNotes=normalizedMap.platformNotes;return validateEnvelopePaths(envelope)}function validateDelegationEnvelope(envelope,context){if(typeof envelope!=="object"||envelope===null)return{valid:!1,reason:"envelope_not_object"};let e=envelope,requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!(field in e)||e[field]===void 0||e[field]===null)return{valid:!1,reason:`missing_field_${field}`};if(e.commandType==="slash_command")return{valid:!1,reason:"slash_command_delegation_blocked"};let taskId=e.taskId;if(context.planTasks.length>0&&!context.planTasks.includes(taskId))return{valid:!1,reason:"taskId_not_in_plan"};let rawAgent=e.targetAgent,normalizedAgent=stripKnownSwarmPrefix(rawAgent);if(!context.validAgents.includes(normalizedAgent))return{valid:!1,reason:"invalid_target_agent"};let{action,files}=e;if((action==="implement"||action==="review")&&(!Array.isArray(files)||files.length===0))return{valid:!1,reason:"files_required_for_action"};let acceptanceCriteria=e.acceptanceCriteria;if(!Array.isArray(acceptanceCriteria)||acceptanceCriteria.length===0)return{valid:!1,reason:"acceptanceCriteria_required"};if("specCriteria"in e&&e.specCriteria!==void 0&&e.specCriteria!==null){let spec=e.specCriteria;if(typeof spec!=="object"||Array.isArray(spec))return{valid:!1,reason:"specCriteria_malformed"};let specObj=spec;for(let member of["fr","sc","acceptance"]){let value=specObj[member];if(value===void 0||value===null)continue;if(!Array.isArray(value)||!value.every((entry)=>typeof entry==="string"))return{valid:!1,reason:`specCriteria_${member}_malformed`}}}return{valid:!0}}function appendDelegationEnvelopeAdvisory(session,promptText,context){try{let envelope=parseDelegationEnvelope(promptText);if(!envelope)return null;let result=validateDelegationEnvelope(envelope,context);if(!result.valid)pushAdvisory(session,`DELEGATION ENVELOPE ADVISORY: a parsed delegation envelope failed validation (${result.reason}). `+"This is advisory-only — the delegation was NOT blocked. Review the envelope's structured "+"fields (including the optional specCriteria acceptance/FR/SC arrays) before the next dispatch.");return result}catch{return null}}function validateCoderReviewerAcceptanceField(promptText){let lines=promptText.split(/\r?\n/),headerRe=/^ACCEPTANCE:[ \t]*(.*)$/i,nextFieldRe=/^[A-Z][A-Z0-9_]*:/;for(let i=0;i<lines.length;i++){let match=headerRe.exec(lines[i]);if(!match)continue;if(match[1].trim().length>0)return{valid:!0};for(let j=i+1;j<lines.length;j++){if(nextFieldRe.test(lines[j]))break;if(lines[j].trim().length>0)return{valid:!0}}return{valid:!1,reason:"acceptance_field_empty"}}return{valid:!1,reason:"acceptance_field_missing"}}function extractSpecRequirementBodyById(specText,id){let escapedId=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lines=specText.split(/\r?\n/),headerRe=new RegExp(`^\\s*[-*]?\\s*\\*\\*\\s*${escapedId}\\b`),headerIdx=-1;for(let i=0;i<lines.length;i++)if(headerRe.test(lines[i])){headerIdx=i;break}if(headerIdx===-1)return null;let headerLine=lines[headerIdx],openIdx=headerLine.indexOf("**"),closeIdx=openIdx===-1?-1:headerLine.indexOf("**",openIdx+2);if(closeIdx===-1)return null;let body=headerLine.slice(closeIdx+2);for(let i=headerIdx+1;i<lines.length;i++){let line=lines[i];if(line.trim().length===0)break;if(/^#/.test(line))break;if(/^\s*[-*]\s/.test(line))break;if(/^\s*[-*]?\s*\*\*\s*(?:FR|SC)-/.test(line))break;body+=` ${line}`}return body}function normalizeAcceptanceText(s){return s.normalize("NFC").replace(/`/g,"").replace(/\*\*/g,"").replace(/\*/g,"").replace(/^[ \t]*[-*][ \t]+/gm,"").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[—–]/g,"-").replace(/-{2,}/g,"-").replace(/Â?§/g," section ").replace(/\s+/g," ").trim().toLowerCase()}function describeCoverageMiss(params){let{normalizedExpected,normalizedAcceptance}=params,divergenceOffset=0,maxScan=Math.min(normalizedExpected.length,COVERAGE_DIAG_MAX_SCAN);while(divergenceOffset<maxScan&&normalizedAcceptance.includes(normalizedExpected.slice(0,divergenceOffset+1)))divergenceOffset++;let expectedSnippet=normalizedExpected.slice(divergenceOffset,divergenceOffset+COVERAGE_DIAG_SNIPPET_CAP),matchedPrefix=normalizedExpected.slice(0,divergenceOffset),foundIdx=matchedPrefix.length>0?normalizedAcceptance.indexOf(matchedPrefix):-1,foundPos=foundIdx>=0?foundIdx+matchedPrefix.length:0,foundSnippet=normalizedAcceptance.slice(foundPos,foundPos+COVERAGE_DIAG_SNIPPET_CAP),raw=`${params.rawExpectedBody}
755
- ${params.rawAcceptanceText}`,corruptionHint;if(/�/.test(raw))corruptionHint="the text contains U+FFFD (the Unicode replacement char), a sign spec.md was decoded with the wrong encoding — re-save spec.md as UTF-8";else if(/\?{2,}/.test(raw))corruptionHint="the text contains a '??' run — a non-UTF-8 save can turn characters like § into ?? on disk; open .swarm/spec.md and re-type the affected character, then re-save as UTF-8";else if(/Ã.|â€|Â[^\s]/.test(raw))corruptionHint="the text contains a Latin-1 mojibake byte sequence (e.g. §, é) — re-save spec.md as UTF-8";return{expectedSnippet,foundSnippet,divergenceOffset,...corruptionHint?{corruptionHint}:{}}}function checkAcceptanceCoversFrRefs(params){let normalizedAcceptance=normalizeAcceptanceText(params.acceptanceText);for(let id of params.frRefs){let body=extractSpecRequirementBodyById(params.specText,id);if(body===null)continue;let normalizedBody=normalizeAcceptanceText(body);if(normalizedBody.length===0)continue;if(!normalizedAcceptance.includes(normalizedBody))return{covered:!1,missingId:id,diagnostic:describeCoverageMiss({rawExpectedBody:body,rawAcceptanceText:params.acceptanceText,normalizedExpected:normalizedBody,normalizedAcceptance}),expectedBody:body}}return{covered:!0}}function extractTaskLine(text){let match=text.match(/TASK:\s*(.+?)(?:\n|$)/i);return match?match[1].trim():null}function extractPlanTaskId(text){let taskListMatch=text.match(/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ]/m);if(taskListMatch)return taskListMatch[1];let taskLineMatch=text.match(/TASK:\s*(?:.+?\s)?(\d+\.\d+(?:\.\d+)*)(?:\s|$|:)/i);if(taskLineMatch)return taskLineMatch[1];return null}function outputText(output){if(typeof output==="string")return output;if(typeof output==="number"||typeof output==="boolean")return String(output);if(Array.isArray(output))return output.map(outputText).filter(Boolean).join(`
754
+ `),keyValueMap={};for(let line of lines){let match=line.match(/^([^:]+):\s*(.+)$/);if(match){let key=match[1].trim().toLowerCase(),value=match[2].trim();keyValueMap[key]=value}}let keyNormalization={taskid:"taskId",task_id:"taskId",targetagent:"targetAgent",target_agent:"targetAgent",commandtype:"commandType",command_type:"commandType",acceptancecriteria:"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",technicalcontext:"technicalContext",technical_context:"technicalContext",errorstrategy:"errorStrategy",error_strategy:"errorStrategy",platformnotes:"platformNotes",platform_notes:"platformNotes",action:"action",files:"files"},normalizedMap={};for(let[key,value]of Object.entries(keyValueMap)){let normalized=keyNormalization[key]||key;normalizedMap[normalized]=value}if(Object.keys(normalizedMap).length<3)return null;let requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!normalizedMap[field])return null;let parseArrayField=(value)=>{let parts=value.split(",");if(parts.length===1)parts=value.split(";");return parts.map((s)=>s.trim()).filter((s)=>s.length>0)},envelope={taskId:normalizedMap.taskId,targetAgent:normalizedMap.targetAgent,action:normalizedMap.action,commandType:normalizedMap.commandType,files:parseArrayField(normalizedMap.files),acceptanceCriteria:parseArrayField(normalizedMap.acceptanceCriteria),technicalContext:normalizedMap.technicalContext||""};if(normalizedMap.technicalContext)envelope.technicalContext=normalizedMap.technicalContext;if(normalizedMap.errorStrategy)envelope.errorStrategy=normalizedMap.errorStrategy;if(normalizedMap.platformNotes)envelope.platformNotes=normalizedMap.platformNotes;return validateEnvelopePaths(envelope)}function validateDelegationEnvelope(envelope,context){if(typeof envelope!=="object"||envelope===null)return{valid:!1,reason:"envelope_not_object"};let e=envelope,requiredFields=["taskId","targetAgent","action","commandType","files","acceptanceCriteria"];for(let field of requiredFields)if(!(field in e)||e[field]===void 0||e[field]===null)return{valid:!1,reason:`missing_field_${field}`};if(e.commandType==="slash_command")return{valid:!1,reason:"slash_command_delegation_blocked"};let taskId=e.taskId;if(context.planTasks.length>0&&!context.planTasks.includes(taskId))return{valid:!1,reason:"taskId_not_in_plan"};let rawAgent=e.targetAgent,normalizedAgent=stripKnownSwarmPrefix(rawAgent);if(!context.validAgents.includes(normalizedAgent))return{valid:!1,reason:"invalid_target_agent"};let{action,files}=e;if((action==="implement"||action==="review")&&(!Array.isArray(files)||files.length===0))return{valid:!1,reason:"files_required_for_action"};let acceptanceCriteria=e.acceptanceCriteria;if(!Array.isArray(acceptanceCriteria)||acceptanceCriteria.length===0)return{valid:!1,reason:"acceptanceCriteria_required"};if("specCriteria"in e&&e.specCriteria!==void 0&&e.specCriteria!==null){let spec=e.specCriteria;if(typeof spec!=="object"||Array.isArray(spec))return{valid:!1,reason:"specCriteria_malformed"};let specObj=spec;for(let member of["fr","sc","acceptance"]){let value=specObj[member];if(value===void 0||value===null)continue;if(!Array.isArray(value)||!value.every((entry)=>typeof entry==="string"))return{valid:!1,reason:`specCriteria_${member}_malformed`}}}return{valid:!0}}function appendDelegationEnvelopeAdvisory(session,promptText,context){try{let envelope=parseDelegationEnvelope(promptText);if(!envelope)return null;let result=validateDelegationEnvelope(envelope,context);if(!result.valid)pushAdvisory(session,`DELEGATION ENVELOPE ADVISORY: a parsed delegation envelope failed validation (${result.reason}). `+"This is advisory-only — the delegation was NOT blocked. Review the envelope's structured "+"fields (including the optional specCriteria acceptance/FR/SC arrays) before the next dispatch.");return result}catch{return null}}function validateCoderReviewerAcceptanceField(promptText){let lines=promptText.split(/\r?\n/),headerRe=/^ACCEPTANCE:[ \t]*(.*)$/i,nextFieldRe=/^[A-Z][A-Z0-9_]*:/;for(let i=0;i<lines.length;i++){let match=headerRe.exec(lines[i]);if(!match)continue;if(match[1].trim().length>0)return{valid:!0};for(let j=i+1;j<lines.length;j++){if(nextFieldRe.test(lines[j]))break;if(lines[j].trim().length>0)return{valid:!0}}return{valid:!1,reason:"acceptance_field_empty"}}return{valid:!1,reason:"acceptance_field_missing"}}function extractSpecRequirementBodyById(specText,id){if(!id||id.trim().length===0)return null;let escapedId=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lines=specText.split(/\r?\n/),headerRe=new RegExp(`^\\s*[-*]?\\s*\\*\\*\\s*${escapedId}\\b`),headerIdx=-1;for(let i=0;i<lines.length;i++)if(headerRe.test(lines[i])){headerIdx=i;break}if(headerIdx===-1)return null;let headerLine=lines[headerIdx],openIdx=headerLine.indexOf("**"),closeIdx=openIdx===-1?-1:headerLine.indexOf("**",openIdx+2);if(closeIdx===-1)return null;let body=headerLine.slice(closeIdx+2);for(let i=headerIdx+1;i<lines.length;i++){let line=lines[i];if(line.trim().length===0)break;if(/^#/.test(line))break;if(/^\s*[-*]\s/.test(line))break;if(/^\s*[-*]?\s*\*\*\s*(?:FR|SC)-/.test(line))break;body+=` ${line}`}return body}function normalizeAcceptanceText(s){return s.normalize("NFC").replace(/`/g,"").replace(/\*\*/g,"").replace(/\*/g,"").replace(/^[ \t]*[-*][ \t]+/gm,"").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[—–]/g,"-").replace(/-{2,}/g,"-").replace(/Â?§/g," section ").replace(/\s+/g," ").trim().toLowerCase()}function describeCoverageMiss(params){let{normalizedExpected,normalizedAcceptance}=params,divergenceOffset=0,maxScan=Math.min(normalizedExpected.length,COVERAGE_DIAG_MAX_SCAN);while(divergenceOffset<maxScan&&normalizedAcceptance.includes(normalizedExpected.slice(0,divergenceOffset+1)))divergenceOffset++;let raw=`${params.rawExpectedBody}
755
+ ${params.rawAcceptanceText}`,corruptionHint;if(/�/.test(raw))corruptionHint="the text contains U+FFFD (the Unicode replacement char), a sign spec.md was decoded with the wrong encoding — re-save spec.md as UTF-8";else if(/\?{2,}/.test(raw))corruptionHint="the text contains a '??' run — a non-UTF-8 save can turn characters like § into ?? on disk; open .swarm/spec.md and re-type the affected character, then re-save as UTF-8";else if(/Ã.|â€|Â[^\s]/.test(raw))corruptionHint="the text contains a Latin-1 mojibake byte sequence (e.g. §, é) — re-save spec.md as UTF-8";if(divergenceOffset<COVERAGE_DIAG_MIN_PREFIX)return{expectedSnippet:normalizedExpected.slice(0,COVERAGE_DIAG_SNIPPET_CAP),foundSnippet:"",divergenceOffset:0,completelyMissing:!0,...corruptionHint?{corruptionHint}:{}};let expectedSnippet=normalizedExpected.slice(divergenceOffset,divergenceOffset+COVERAGE_DIAG_SNIPPET_CAP),matchedPrefix=normalizedExpected.slice(0,divergenceOffset),foundIdx=matchedPrefix.length>0?normalizedAcceptance.indexOf(matchedPrefix):-1,foundPos=foundIdx>=0?foundIdx+matchedPrefix.length:0,foundSnippet=normalizedAcceptance.slice(foundPos,foundPos+COVERAGE_DIAG_SNIPPET_CAP);return{expectedSnippet,foundSnippet,divergenceOffset,...corruptionHint?{corruptionHint}:{}}}function buildAcceptanceCoverageMismatchError(params){let{targetAgent,coverageTaskId,coverageResult}=params,diag=coverageResult.diagnostic,diagLines=[];if(diag){if(diag.completelyMissing)diagLines.push(` no meaningful prefix of the requirement text was found in ACCEPTANCE (matched prefix under ${COVERAGE_DIAG_MIN_PREFIX} chars is treated as coincidental)`),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(' ACCEPTANCE has here: "[Requirement text completely missing from prompt]"');else diagLines.push(` first divergence at normalized offset ${diag.divergenceOffset}`+(diag.divergenceOffset===0?" (no aligned prefix found)":"")),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(` ACCEPTANCE has here: "${diag.foundSnippet}"`);if(diag.corruptionHint)diagLines.push(` ENCODING WARNING: ${diag.corruptionHint}`)}let rawExpectedBody=coverageResult.expectedBody??"",truncated=rawExpectedBody.length>ACCEPTANCE_EXPECTED_BODY_CAP,expectedBodyBlock=truncated?`${rawExpectedBody.slice(0,ACCEPTANCE_EXPECTED_BODY_CAP)}
756
+ …[truncated — read the remainder from .swarm/spec.md under ${coverageResult.missingId}]`:rawExpectedBody;return Error(`ACCEPTANCE_FIELD_COVERAGE_MISMATCH: the ${targetAgent} delegation for task ${coverageTaskId} was blocked because its ACCEPTANCE field does not cover the requirement text for ${coverageResult.missingId} from .swarm/spec.md (compared after Unicode/whitespace normalization, not raw bytes).
757
+ ${diagLines.join(`
758
+ `)}
759
+ Replace your ACCEPTANCE text for ${coverageResult.missingId} with the exact requirement text below, PRESERVING ITS LINE BREAKS, then re-dispatch (body capped at ${ACCEPTANCE_EXPECTED_BODY_CAP} chars${truncated?", truncated below":""}):
760
+ \`\`\`
761
+ ${expectedBodyBlock}
762
+ \`\`\`
763
+ (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt for how ACCEPTANCE is derived; if the ENCODING WARNING above is present, repair .swarm/spec.md first, then re-dispatch.) Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, ~/.cache/opencode) `+"— the fix is in your dispatch content, not in plugin internals. If this same error repeats after 2 fix "+"attempts, STOP and present the blocker to the user.")}function checkAcceptanceCoversFrRefs(params){let normalizedAcceptance=normalizeAcceptanceText(params.acceptanceText);for(let id of params.frRefs){let body=extractSpecRequirementBodyById(params.specText,id);if(body===null)continue;let normalizedBody=normalizeAcceptanceText(body);if(normalizedBody.length===0)continue;if(!normalizedAcceptance.includes(normalizedBody))return{covered:!1,missingId:id,diagnostic:describeCoverageMiss({rawExpectedBody:body,rawAcceptanceText:params.acceptanceText,normalizedExpected:normalizedBody,normalizedAcceptance}),expectedBody:body}}return{covered:!0}}function injectSpecRequirementsIntoAcceptance(params){let headerRe=/^ACCEPTANCE:[ \t]*(.*)$/i,field,lines,headerIdx=-1;for(let candidate of ACCEPTANCE_ARGS_FIELDS){let value=params.args[candidate];if(typeof value!=="string"||!/ACCEPTANCE:/i.test(value))continue;let candidateLines=value.split(/\r?\n/),idx=candidateLines.findIndex((line)=>headerRe.test(line));if(idx>=0){field=candidate,lines=candidateLines,headerIdx=idx;break}}if(!field||!lines||headerIdx<0)return null;let normalizedAcceptance=normalizeAcceptanceText(lines.join(`
764
+ `)),uniqueFrRefs=[...new Set(params.frRefs)],injectedIds=[],injectionBlocks=[];for(let id of uniqueFrRefs){let body=extractSpecRequirementBodyById(params.specText,id);if(body===null)continue;if(normalizedAcceptance.includes(normalizeAcceptanceText(body)))continue;injectedIds.push(id);let trimmedBody=body.trim();injectionBlocks.push(`${id}: ${trimmedBody}`)}if(injectedIds.length===0)return null;return lines.splice(headerIdx+1,0,injectionBlocks.join(`
765
+ `)),params.args[field]=lines.join(`
766
+ `),log("[delegation-gate] injected verbatim requirement text into ACCEPTANCE",{field,injected_ids:injectedIds.join(",")}),{field,injectedIds}}function extractTaskLine(text){let match=text.match(/TASK:\s*(.+?)(?:\n|$)/i);return match?match[1].trim():null}function extractPlanTaskId(text){let taskListMatch=text.match(/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ]/m);if(taskListMatch)return taskListMatch[1];let taskLineMatch=text.match(/TASK:\s*(?:.+?\s)?(\d+\.\d+(?:\.\d+)*)(?:\s|$|:)/i);if(taskLineMatch)return taskLineMatch[1];return null}function outputText(output){if(typeof output==="string")return output;if(typeof output==="number"||typeof output==="boolean")return String(output);if(Array.isArray(output))return output.map(outputText).filter(Boolean).join(`
756
767
  `);if(output&&typeof output==="object"){let record2=output,preferred=["output","text","content","message","result"],parts=[];for(let key of preferred)if(key in record2)parts.push(outputText(record2[key]));if(parts.length>0)return parts.filter(Boolean).join(`
757
768
  `);try{return JSON.stringify(output)}catch{return""}}return""}function extractPlanCriticVerdict(output){let text=outputText(output);if(!text)return null;let primary=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED)\b/im.exec(text);if(primary)return primary[1].toUpperCase();let heading=/^(#{1,6})\s*Verdict\s*$/im.exec(text);if(heading&&heading.index!==void 0){let nextLines=text.slice(heading.index+heading[0].length).split(`
758
769
  `).slice(0,3).join(`
@@ -762,16 +773,9 @@ ${params.rawAcceptanceText}`,corruptionHint;if(/�/.test(raw))corruptionHint="t
762
773
  `,"utf-8")}catch(err){warn(`[delegation-gate] plan_critic_gate_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{planId,recordedAt,...sanitizedReason?{reason:sanitizedReason}:{},userConfirmed}}function isTaskCompletedForParallelGuidance(task){let status=task.status??"pending";return status==="completed"||status==="closed"}function getPlanTaskDeclaredFiles(plan,taskId){if(!plan||!taskId)return null;for(let phase of plan.phases){let task=phase.tasks.find((candidate)=>candidate.id===taskId);if(task)return[...task.files_touched]}return null}function resolveDelegatedPlanTaskId(args2,knownPlanTaskIds){let rawTaskId=args2.task_id??args2.taskId;if(typeof rawTaskId==="string"){let trimmed=rawTaskId.trim();if(trimmed.length<=20&&isStrictTaskId2(trimmed))return trimmed}let candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineMatches=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g)){let candidate=m[1];if(!isStrictTaskId2(candidate))continue;if(knownPlanTaskIds&&!knownPlanTaskIds.has(candidate))continue;taskLineMatches.add(candidate)}}if(taskLineMatches.size===1)return taskLineMatches.values().next().value;if(taskLineMatches.size>1)return null;let seen=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g)){let candidate=m[1];if(isStrictTaskId2(candidate)){if(knownPlanTaskIds&&!knownPlanTaskIds.has(candidate))continue;seen.add(candidate)}}}if(seen.size===1)return seen.values().next().value;return null}function describeCoderScopeFailure(args2,planTaskIds){let known=[...planTaskIds].sort().join(", ")||"(none)",rawTaskId=args2.task_id??args2.taskId,explicitFieldShape=typeof rawTaskId==="string"&&rawTaskId.trim().length>0?`"${rawTaskId.trim().slice(0,40)}" (non-plan-shaped; treated as runtime session id and ignored — falling through to text extraction)`:"absent",candidateTextFields=[args2.prompt,args2.description,args2.task,args2.input],taskLineCandidates=new Set,taskLineDetected=!1;for(let field of candidateTextFields){if(typeof field!=="string")continue;let taskLine=extractTaskLine(field);if(!taskLine)continue;taskLineDetected=!0;for(let m of taskLine.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(planTaskIds.has(m[1]))taskLineCandidates.add(m[1])}let textCandidates=new Set;for(let field of candidateTextFields){if(typeof field!=="string")continue;for(let m of field.matchAll(/\b(\d+\.\d+(?:\.\d+)*)\b/g))if(planTaskIds.has(m[1]))textCandidates.add(m[1])}if(taskLineCandidates.size>1)return`multiple candidate task ids found in TASK: line: [${[...taskLineCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${known}.`;if(textCandidates.size>1)return`multiple candidate task ids found in prompt text: [${[...textCandidates].sort().join(", ")}]; provide exactly one unambiguous TASK: <id> line. Known plan task ids: ${known}.`;return`no plan task id could be resolved. Include a TASK: <N.M> line or plan-task-shaped task_id arg. Explicit task_id field: ${explicitFieldShape}. TASK: line detected: ${taskLineDetected?"yes":"no"}. Known plan task ids: ${known}.`}function stripSingleTrailingAnnotationSuffix(value){let suffixMatch=value.match(/(?:\s+\([^()]*\))+$/);if(!suffixMatch)return value;let suffix=suffixMatch[0];if((suffix.match(/\([^()]*\)/g)??[]).length!==1)return null;return value.slice(0,-suffix.length).trimEnd()||null}function normalizeFileDirectiveValue(rawValue){let value=rawValue.trim();if(!value)return null;let quote=value[0];if(quote==='"'||quote==="'"){let closingQuoteIndex=value.indexOf(quote,1);if(closingQuoteIndex===-1)return null;let filePath=value.slice(1,closingQuoteIndex);if(!filePath)return null;let suffix=value.slice(closingQuoteIndex+1);if(suffix.length>0&&!/^\s+\([^()]*\)\s*$/.test(suffix))return null;return filePath}let normalized=stripSingleTrailingAnnotationSuffix(value);if(!normalized||/[,;|]/.test(normalized))return null;return normalized}function extractTaskFileDirectives(args2,mode){let files=new Set,present=!1;for(let field of[args2.prompt,args2.description,args2.task,args2.input]){if(typeof field!=="string")continue;for(let line of field.split(/\r?\n/)){if(!/^\s*FILE\s*:/i.test(line))continue;present=!0;let value=normalizeFileDirectiveValue(line.replace(/^\s*FILE\s*:\s*/i,""));if(!value){if(mode==="observe")continue;return{present:!0,files:null}}files.add(value)}}return{present,files:present&&files.size>0?[...files]:null}}function parsePerTaskVerdicts(outputText2){let result=new Map,reviewedPattern=/^\[REVIEWED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(APPROVED|REJECTED|CONCERNS)\s*\|/im,testedPattern=/^\[TESTED\]\s*\|\s*(?:task-)?(\d+\.\d+(?:\.\d+)*)\s*\|\s*(PASS|FAIL|SKIPPED)\s*\|/im;for(let line of outputText2.split(`
763
774
  `)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId2(taskId))result.set(taskId,verdict);continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId2(taskId))result.set(taskId,verdict)}}return result}async function findTaskAwaitingCompletion(directory,requestedTaskId){if(!directory)return null;let plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{return null}if(!plan)return null;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),tasks=plan.phases.flatMap((phase)=>phase.tasks),orderedTasks=requestedTaskId?[...tasks.filter((task)=>task.id===requestedTaskId),...tasks.filter((task)=>task.id!==requestedTaskId)]:tasks;for(let task of orderedTasks){let taskId=task.id,evidence2=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence2),councilEvidence=evidence2?.gates.council,awaitsQaCompletion=workflow.authoritative&&workflow.state==="tests_run",awaitsCouncilCompletion=workflow.authoritative&&workflow.state==="pre_check_passed"&&councilEvidence?.verdict==="APPROVE";if(!awaitsQaCompletion&&!awaitsCouncilCompletion)continue;let planStatus=task.status??"pending";if(planStatus==="completed"||planStatus==="closed"||planStatus==="blocked")continue;return taskId}return null}function completionGateViolationMessage(taskAwaitingCompletion){return`TASK_COMPLETION_GATE_VIOLATION: Task ${taskAwaitingCompletion} reached tests_run but is not marked completed in plan.json/plan.md. Call update_task_status with task_id="${taskAwaitingCompletion}" and status="completed". Read-only inspection remains available; a proven-disjoint task may continue; if plan.json is ledger-stale, retry save_plan with reconcile_ledger_projection=true and otherwise-unchanged plan content.`}function readCoderRetryEscalations(directory,taskId,retryEpoch){let actions=new Set;try{let raw=fs48.readFileSync(validateSwarmPath(directory,"events.jsonl"),"utf-8");for(let line of raw.split(`
764
775
  `)){if(!line.trim())continue;try{let event=JSON.parse(line);if(event.type==="coder_retry_circuit_breaker"&&event.taskId===taskId&&event.retryEpoch===retryEpoch&&(event.action==="sounding_board_consultation"||event.action==="simplification"||event.action==="user_escalation"))actions.add(event.action)}catch{}}}catch(error49){if(error49.code!=="ENOENT")throw error49}return actions}async function emitCoderRetryEscalation(directory,input){let eventsPath=validateSwarmPath(directory,"events.jsonl"),lock=await tryAcquireLock(directory,"events.jsonl","workflow-retry-escalation",`coder-retry:${input.taskId}:${input.generation}:${input.action}`);if(!lock.acquired)throw Error("TASK_RETRY_AUDIT_LOCKED");try{if(readCoderRetryEscalations(directory,input.taskId,input.retryEpoch).has(input.action))return;await fs48.promises.mkdir(path78.dirname(eventsPath),{recursive:!0}),await fs48.promises.appendFile(eventsPath,`${JSON.stringify({type:"coder_retry_circuit_breaker",timestamp:new Date().toISOString(),taskId:input.taskId,generation:input.generation,retryEpoch:input.retryEpoch,rejectionCount:input.rejectionCount,rejectionHistory:input.rejectionHistory,phase:Number(input.taskId.split(".")[0])||0,action:input.action})}
765
- `,"utf-8")}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch);if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs48.existsSync(path78.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path78.resolve(directory),planPath=path78.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path78.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path78.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs48.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory){let rawTaskId=args2?.task_id;if(typeof rawTaskId==="string"&&rawTaskId.length<=20&&isStrictTaskId2(rawTaskId.trim()))return rawTaskId.trim();if(args2)try{let plan=await loadPlanJsonOnly(directory);if(plan){let planTaskIds=new Set(plan.phases.flatMap((p)=>p.tasks.map((t)=>t.id))),promptTaskId=resolveDelegatedPlanTaskId(args2,planTaskIds);if(promptTaskId)return promptTaskId}}catch{}return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function createDelegationGateHook(config2,directory){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED")return;throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files]},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals60.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:captureWorkspaceSnapshot(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}})},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let normalized=normalizeToolName(input.tool),args2=output.args;if(normalized!=="Task"&&normalized!=="task"||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if((normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),completionArgs=output.args;if(completionArgs){let completionPlanTaskIds;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanTaskIds=new Set(plan2.phases.flatMap((p)=>p.tasks.map((t)=>t.id)))}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanTaskIds);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(normalized!=="Task"&&normalized!=="task")return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer")try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[];if(changedFiles.length>0){let routing=await routeReviewForChanges(directory,changedFiles);if(shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch{}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=[args2.prompt,args2.description,args2.task,args2.input,args2.message].filter((value)=>typeof value==="string").join(`
766
- `),acceptanceCheck=validateCoderReviewerAcceptanceField(acceptancePromptText);if(!acceptanceCheck.valid){let detail=acceptanceCheck.reason==="acceptance_field_empty"?"its ACCEPTANCE field is present but empty/whitespace-only":"it has no ACCEPTANCE field";throw Error(`ACCEPTANCE_FIELD_REQUIRED: the ${targetAgent} delegation was blocked because ${detail}. `+"Every coder/reviewer dispatch MUST carry a non-empty ACCEPTANCE: line in its prompt — the verbatim "+"FR-###/SC-### requirement text from .swarm/spec.md when the task maps to one or more spec requirements, or a one-line task-derived statement of what DONE looks like otherwise (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt and .swarm/spec.md). Add an ACCEPTANCE: line to the delegation prompt and re-dispatch. Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, "+"~/.cache/opencode) — the fix is in your dispatch content, not in plugin internals. If this same error "+"repeats after 2 fix attempts, STOP and present the blocker to the user.")}let coverageResult,coverageTaskId=null;try{let coveragePlan=await _internals60.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskIds=new Set(coveragePlan.phases.flatMap((phase)=>phase.tasks.map((t)=>t.id)));if(coverageTaskId=resolveDelegatedPlanTaskId(args2,coveragePlanTaskIds),coverageTaskId){let coverageTask=coveragePlan.phases.flatMap((phase)=>phase.tasks).find((t)=>t.id===coverageTaskId),frRefs=coverageTask?.fr_refs;if(coverageTask&&Array.isArray(frRefs)&&frRefs.length>0){let specText=await fs48.promises.readFile(path78.join(directory,".swarm","spec.md"),"utf8");coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:acceptancePromptText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1){let diag=coverageResult.diagnostic,diagLines=[];if(diag){if(diagLines.push(` first divergence at normalized offset ${diag.divergenceOffset}`+(diag.divergenceOffset===0?" (no aligned prefix found)":"")),diagLines.push(` spec requires here: "${diag.expectedSnippet}"`),diagLines.push(` ACCEPTANCE has here: "${diag.foundSnippet}"`),diag.corruptionHint)diagLines.push(` ENCODING WARNING: ${diag.corruptionHint}`)}let rawExpectedBody=coverageResult.expectedBody??"",truncated=rawExpectedBody.length>ACCEPTANCE_EXPECTED_BODY_CAP,expectedBodyBlock=truncated?`${rawExpectedBody.slice(0,ACCEPTANCE_EXPECTED_BODY_CAP)}
767
- …[truncated — read the remainder from .swarm/spec.md under ${coverageResult.missingId}]`:rawExpectedBody;throw Error(`ACCEPTANCE_FIELD_COVERAGE_MISMATCH: the ${targetAgent} delegation for task ${coverageTaskId} was blocked because its ACCEPTANCE field does not cover the requirement text for ${coverageResult.missingId} from .swarm/spec.md (compared after Unicode/whitespace normalization, not raw bytes).
768
- ${diagLines.join(`
769
- `)}
770
- Replace your ACCEPTANCE text for ${coverageResult.missingId} with the exact requirement text below, PRESERVING ITS LINE BREAKS, then re-dispatch (body capped at ${ACCEPTANCE_EXPECTED_BODY_CAP} chars${truncated?", truncated below":""}):
771
- \`\`\`
772
- ${expectedBodyBlock}
773
- \`\`\`
774
- (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt for how ACCEPTANCE is derived; if the ENCODING WARNING above is present, repair .swarm/spec.md first, then re-dispatch.) Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, ~/.cache/opencode) `+"— the fix is in your dispatch content, not in plugin internals. If this same error repeats after 2 fix "+"attempts, STOP and present the blocker to the user.")}}if(TASK_GATE_AGENTS.has(targetAgent)){let stageBSession=ensureAgentSession(input.sessionID),resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
776
+ `,"utf-8")}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch);if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs48.existsSync(path78.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path78.resolve(directory),planPath=path78.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path78.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path78.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs48.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory){let rawTaskId=args2?.task_id;if(typeof rawTaskId==="string"&&rawTaskId.length<=20&&isStrictTaskId2(rawTaskId.trim()))return rawTaskId.trim();if(args2)try{let plan=await loadPlanJsonOnly(directory);if(plan){let planTaskIds=new Set(plan.phases.flatMap((p)=>p.tasks.map((t)=>t.id))),promptTaskId=resolveDelegatedPlanTaskId(args2,planTaskIds);if(promptTaskId)return promptTaskId}}catch{}return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function createDelegationGateHook(config2,directory){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED")return;throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files]},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals60.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:captureWorkspaceSnapshot(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}})},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let normalized=normalizeToolName(input.tool),args2=output.args;if(normalized!=="Task"&&normalized!=="task"||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if((normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),completionArgs=output.args;if(completionArgs){let completionPlanTaskIds;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanTaskIds=new Set(plan2.phases.flatMap((p)=>p.tasks.map((t)=>t.id)))}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanTaskIds);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(normalized!=="Task"&&normalized!=="task")return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer")try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[];if(changedFiles.length>0){let routing=await routeReviewForChanges(directory,changedFiles);if(shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch{}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
777
+ `),acceptanceCheck=validateCoderReviewerAcceptanceField(acceptancePromptText);if(!acceptanceCheck.valid){let detail=acceptanceCheck.reason==="acceptance_field_empty"?"its ACCEPTANCE field is present but empty/whitespace-only":"it has no ACCEPTANCE field";throw Error(`ACCEPTANCE_FIELD_REQUIRED: the ${targetAgent} delegation was blocked because ${detail}. `+"Every coder/reviewer dispatch MUST carry a non-empty ACCEPTANCE: line in its prompt — the mapped FR-###/SC-### ids "+"(for a single-task dispatch the delegation gate injects their verbatim requirement text from .swarm/spec.md automatically; phase/final-council multi-task reviewer dispatches are NOT auto-injected and must paste the verbatim text yourself) when the task maps to one or more spec requirements, or a one-line task-derived statement of what DONE looks like otherwise (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt and .swarm/spec.md). Add an ACCEPTANCE: line to the delegation prompt and re-dispatch. Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, "+"~/.cache/opencode) — the fix is in your dispatch content, not in plugin internals. If this same error "+"repeats after 2 fix attempts, STOP and present the blocker to the user.")}let coverageResult,coverageTaskId=null;try{let coveragePlan=await _internals60.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskIds=new Set(coveragePlan.phases.flatMap((phase)=>phase.tasks.map((t)=>t.id)));if(coverageTaskId=resolveDelegatedPlanTaskId(args2,coveragePlanTaskIds),coverageTaskId){let coverageTask=coveragePlan.phases.flatMap((phase)=>phase.tasks).find((t)=>t.id===coverageTaskId),frRefs=coverageTask?.fr_refs;if(coverageTask&&Array.isArray(frRefs)&&frRefs.length>0){let specText=await fs48.promises.readFile(path78.join(directory,".swarm","spec.md"),"utf8");injectSpecRequirementsIntoAcceptance({args:args2,frRefs,specText});let effectiveAcceptanceText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
778
+ `);coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:effectiveAcceptanceText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1)throw buildAcceptanceCoverageMismatchError({targetAgent,coverageTaskId,coverageResult})}if(TASK_GATE_AGENTS.has(targetAgent)){let stageBSession=ensureAgentSession(input.sessionID),resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
775
779
  `);for(let match of dispatchText.matchAll(/(?:task-)?(\d+\.\d+(?:\.\d+)*)/gi))if(match[1]&&knownIds.has(match[1]))candidateTaskIds.add(match[1])}let generations=new Map,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config2.council)){if(!stageBSession.taskCouncilWorkflowGeneration)stageBSession.taskCouncilWorkflowGeneration=new Map;if(!stageBSession.taskCouncilWorkflowGeneration.has(taskId))stageBSession.taskCouncilWorkflowGeneration.set(taskId,workflow.generation)}if(targetAgent!=="reviewer"&&targetAgent!=="test_engineer"){generations.set(taskId,workflow.generation);continue}if(workflow.authoritative&&(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run")){generations.set(taskId,workflow.generation);continue}if(taskId===resolvedTaskId)throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}`)}rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId);return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),resolvedPreflightTaskId=await resolveEvidenceTaskId(args2,session,directory),preflightPlan=await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidence=preflightTaskId?await readTaskEvidence2(directory,preflightTaskId):null,preflightWorkflow=getTaskWorkflowSnapshot2(preflightEvidence);if(preflightTaskId){if(await enforceCoderRetryEscalation({directory,taskId:preflightTaskId,generation:preflightWorkflow.generation,retryEpoch:preflightWorkflow.retryEpoch,retryCount:preflightWorkflow.retryCount,retryHistory:preflightWorkflow.retryHistory,criticSatisfied:preflightEvidence?.gates.critic_sounding_board!=null}),preflightWorkflow.state==="coder_delegated"){if(!(hasActiveTurboMode(input.sessionID)&&!preflightTaskId.startsWith("3.")))throw Error(`STAGE_A_REQUIRED: Task ${preflightTaskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}}let preparedScope;try{preparedScope=await prepareCoderScope(directory,input,args2)}catch(error49){if(preflightTaskId){let failed=await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId:`coder-preflight:${input.callID}`}),failedWorkflow=getTaskWorkflowSnapshot2(failed);if(failedWorkflow.retryCount>=3)await emitCoderRetryEscalation(directory,{taskId:preflightTaskId,generation:failedWorkflow.generation,retryEpoch:failedWorkflow.retryEpoch,rejectionCount:failedWorkflow.retryCount,rejectionHistory:failedWorkflow.retryHistory,action:"sounding_board_consultation"})}throw error49}let{plan,taskId:incomingCoderTaskId}=preparedScope,coderEvidence=incomingCoderTaskId?await readTaskEvidence2(directory,incomingCoderTaskId):null,coderWorkflow=getTaskWorkflowSnapshot2(coderEvidence),coderDispatchGeneration=coderWorkflow.generation;if(incomingCoderTaskId){if(incomingCoderTaskId!==preflightTaskId)await enforceCoderRetryEscalation({directory,taskId:incomingCoderTaskId,generation:coderWorkflow.generation,retryEpoch:coderWorkflow.retryEpoch,retryCount:coderWorkflow.retryCount,retryHistory:coderWorkflow.retryHistory,criticSatisfied:coderEvidence?.gates.critic_sounding_board!=null})}let reserveBackgroundCoderIfNeeded=async(maxConcurrent2)=>{if(!backgroundSubagentsEnabled||!isBackgroundTrue(args2.background))return;let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state])=>state==="coder_delegated").map(([taskId])=>taskId),claim=await _internals60.reserveBackgroundCoderSlotForDispatch(directory,{parentSessionId:input.sessionID,planTaskId:incomingCoderTaskId||null,callID:input.callID,maxConcurrent:maxConcurrent2,occupiedTaskIds});if(!claim.ok){let detail=claim.detail?` ${claim.detail}`:"",code=claim.reason==="capacity"?"PARALLEL_SLOTS_EXHAUSTED":claim.reason==="duplicate_task"||claim.reason==="duplicate_call"?"BACKGROUND_CODER_TASK_RESERVED":"BACKGROUND_CODER_RESERVATION_UNCERTAIN";throw Error(`${code}: background coder admission was blocked (${claim.reason}).${detail}`)}backgroundCoderReservationByCallID.set(input.callID,claim.reservation)};if(!plan){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}return}let profile=plan?.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=scopeVerdictAllowsParallel(directory,plan),standardWorktreeIsolationActive=parallelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),parallelModeActive=standardWorktreeIsolationActive&&scopeAllowsParallel,criticPolicy=resolvePlanCriticPolicyForExecution(directory,plan,session.qaGateSessionOverrides??{});if(log(`[delegation-gate] critic_pre_plan policy task=${incomingCoderTaskId??"unknown"} required=${criticPolicy.required} source=${criticPolicy.source}`),criticPolicy.required)await assertPlanCriticApprovedForExecution(directory,plan);let{declaredFiles:incomingCoderDeclaredFiles,binding:correlatedBinding}=preparedScope;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let taskId=task.id,durableWorkflow=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId)),state=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state),updateTaskWorkflowCache(session,taskId,durableWorkflow),state!=="coder_delegated")continue;let freshnessThreshold=session.sessionRehydratedAt>0?session.sessionRehydratedAt:session.lastPhaseCompleteTimestamp??0,hasCurrentSessionCoderDelegation=(swarmState.delegationChains.get(input.sessionID)??[]).some((d)=>stripKnownSwarmPrefix(d.to)==="coder"&&d.timestamp>freshnessThreshold);if(!durableWorkflow.authoritative&&!hasCurrentSessionCoderDelegation){session.taskWorkflowStates.set(taskId,"idle"),warn(`[delegation-gate] Reset stale coder_delegated state for task ${taskId} — `+"no coder delegation found in current session.");continue}if(hasActiveTurboMode(input.sessionID)){if(!taskId.startsWith("3."))continue}if(parallelModeActive&&incomingCoderTaskId&&taskId!==incomingCoderTaskId)continue;throw Error(`STAGE_A_REQUIRED: Task ${taskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}if(parallelModeActive){let coderDelegatedCount=0;for(let s of session.taskWorkflowStates.values())if(s==="coder_delegated")coderDelegatedCount++;if(coderDelegatedCount>=effectiveMaxConcurrent)throw Error(`PARALLEL_SLOTS_EXHAUSTED: ${coderDelegatedCount} coder task(s) are awaiting review (max_concurrent_tasks=${effectiveMaxConcurrent}). Dispatch reviewer/test_engineer for an in-flight coder task before starting another coder.`)}if(standardWorktreeSerializationSessions.has(input.sessionID)){if(checkStandardWorktreeSerializationRelease(input.sessionID,resolveWorktreeIsolationConfig(config2)),standardWorktreeSerializationSessions.has(input.sessionID))throw Error("STANDARD_WORKTREE_ISOLATION_SERIALIZED: prior standard worktree isolation setup failed in this session; wait for the active coder task to finish before dispatching another coder.")}await reserveBackgroundCoderIfNeeded(parallelModeActive?effectiveMaxConcurrent:1);try{if(!parallelModeActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background);return}let resolvedTaskId=incomingCoderTaskId,laneScope=correlatedBinding.files;await precreateStandardWorktreeSession({config:config2,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,description:typeof args2.description==="string"?args2.description:void 0,outputArgs:args2,scope:laneScope&&laneScope.length>0&&resolvedTaskId?{taskId:resolvedTaskId,files:laneScope}:void 0});let standardDispatch=standardWorktreeByCallID.get(input.callID);if(standardDispatch){if(resolvedTaskId)try{let childSessionId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!childSessionId||childSessionId===input.sessionID)throw Error("SCOPE_CHILD_IDENTITY_MISSING: worktree dispatch did not return a distinct child session id");await savePlan(standardDispatch.handle.worktreePath,plan,{preserveCompletedStatuses:!1});let childBinding=deriveChildScopeBinding(correlatedBinding,{childDirectory:standardDispatch.handle.worktreePath,childSessionId,parentCallId:input.callID});await publishScopeBinding(input.callID,standardDispatch.handle.worktreePath,childBinding);let childSession=ensureAgentSession(childSessionId,"coder",standardDispatch.handle.worktreePath);childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files]}catch(error49){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config2).worktree_dir),error49}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding)}await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background,standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:incomingCoderTaskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}},messagesTransform:async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastUserMessageIndex=-1;for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user"){lastUserMessageIndex=i;break}if(lastUserMessageIndex===-1)return;let lastUserMessage=messages[lastUserMessageIndex];if(!lastUserMessage?.parts)return;let agent=lastUserMessage.info?.agent;if(agent==="")return;let strippedAgent=agent?stripKnownSwarmPrefix(agent):void 0;if(strippedAgent&&strippedAgent!=="architect")return;let textPartIndex=lastUserMessage.parts.findIndex((p)=>p?.type==="text"&&p.text!==void 0);if(textPartIndex===-1)return;let textPart=lastUserMessage.parts[textPartIndex],text=textPart.text??"",taskDisclosureSessionID=lastUserMessage.info?.sessionID;if(taskDisclosureSessionID){let currentTaskIdForWindow=ensureAgentSession(taskDisclosureSessionID).currentTaskId;if(currentTaskIdForWindow){let taskLineRegex=/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ].*/gm,taskLines=[];taskLineRegex.lastIndex=0;let regexMatch=taskLineRegex.exec(text);while(regexMatch!==null)taskLines.push({line:regexMatch[0],taskId:regexMatch[1],index:regexMatch.index}),regexMatch=taskLineRegex.exec(text);if(taskLines.length>5){let currentIdx=taskLines.findIndex((t)=>t.taskId===currentTaskIdForWindow),windowStart=Math.max(0,currentIdx-2),windowEnd=Math.min(taskLines.length-1,currentIdx+3),visibleTasks=taskLines.slice(windowStart,windowEnd+1),hiddenBefore=windowStart,hiddenAfter=taskLines.length-1-windowEnd,totalTasks=taskLines.length,visibleCount=visibleTasks.length,firstTaskIndex=taskLines[0].index,lastTask=taskLines[taskLines.length-1],lastTaskEnd=lastTask.index+lastTask.line.length,before=text.slice(0,firstTaskIndex),after=text.slice(lastTaskEnd),visibleLines=visibleTasks.map((t)=>t.line).join(`
776
780
  `),trimComment=`[Task window: showing ${visibleCount} of ${totalTasks} tasks]`,trimmedMiddle=(hiddenBefore>0?`[...${hiddenBefore} tasks hidden...]
777
781
  `:"")+visibleLines+(hiddenAfter>0?`
@@ -781,7 +785,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
781
785
  ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else guidance=parallelGuidance??"[NEXT] Begin the first plan task and run gates sequentially.";let systemMsgIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),insertIdx=systemMsgIdx>=0?systemMsgIdx+1:0,guidanceMessage={info:{role:"system"},parts:[{type:"text",text:guidance}]};messages.splice(insertIdx,0,guidanceMessage)}}let warnings=[];if(text.length>delegationMaxChars)warnings.push(`Delegation exceeds recommended size (${text.length} chars, limit ${delegationMaxChars}). Consider splitting into smaller tasks.`);if(isCoderDelegation){let fileMatches=text.match(/^FILE:/gm);if(fileMatches&&fileMatches.length>1)warnings.push(`Multiple FILE: directives detected (${fileMatches.length}). Each coder task should target ONE file.`)}if(isCoderDelegation){let taskMatches=text.match(/^TASK:/gm);if(taskMatches&&taskMatches.length>1)warnings.push(`Multiple TASK: sections detected (${taskMatches.length}). Send ONE task per coder call.`)}if(isCoderDelegation){let batchingPattern=/\b(?:and also|then also|additionally|as well as|along with|while you'?re at it)[.,]?\b/gi,batchingMatches=text.match(batchingPattern);if(batchingMatches&&batchingMatches.length>0)warnings.push(`Batching language detected (${batchingMatches.join(", ")}). Break compound objectives into separate coder calls.`)}if(isCoderDelegation){let taskLine=extractTaskLine(text);if(taskLine){if(/\s+and\s+(update|add|remove|modify|refactor|implement|create|delete|fix|change|build|deploy|write|test|move|rename|extend|extract|convert|migrate|upgrade|replace)\b/i.test(taskLine))warnings.push('TASK line contains "and" connecting separate actions')}}if(isCoderDelegation&&sessionID){let delegationChain=swarmState.delegationChains.get(sessionID);if(delegationChain&&delegationChain.length>=2){let coderIndices=[];for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){if(coderIndices.unshift(i),coderIndices.length===2)break}if(coderIndices.length===2){let prevCoderIndex=coderIndices[0],betweenCoders=delegationChain.slice(prevCoderIndex+1),hasReviewer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="reviewer"),hasTestEngineer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="test_engineer"),session=ensureAgentSession(sessionID),priorTaskStuckAtCoder=priorCoderTaskId!==null&&getTaskState(session,priorCoderTaskId)==="coder_delegated";if(!hasReviewer||!hasTestEngineer||priorTaskStuckAtCoder){if(session.qaSkipCount>=1){telemetry.qaSkipViolation(_input.sessionID,session.agentName,session.qaSkipCount+1);let skippedTasks=session.qaSkipTaskIds.join(", ");throw Error(`\uD83D\uDED1 QA GATE ENFORCEMENT: ${session.qaSkipCount+1} consecutive coder delegations without reviewer/test_engineer. Skipped tasks: [${skippedTasks}]. DELEGATE to reviewer and test_engineer NOW before any further coder work.`)}session.qaSkipCount++,session.qaSkipTaskIds.push(currentTaskId??"unknown"),warnings.push("⚠️ PROTOCOL VIOLATION: Previous coder task completed, but QA gate was skipped. "+"You MUST delegate to reviewer (code review) and test_engineer (test execution) before starting a new coder task. Review RULES 7-8 in your system prompt.")}}}}if(warnings.length===0)return;let warningText=`⚠️ BATCH DETECTED: Your coder delegation appears to contain multiple tasks.
782
786
  Rule 3: ONE task per coder call. Split this into separate delegations.
783
787
  ${warnings.map((w)=>`Detected signal: ${w}`).join(`
784
- `)}`,batchWarnSystemIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),batchWarnInsertIdx=batchWarnSystemIdx>=0?batchWarnSystemIdx+1:0,batchWarnMessage={info:{role:"system"},parts:[{type:"text",text:warningText}]};messages.splice(batchWarnInsertIdx,0,batchWarnMessage)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=normalized==="Task"||normalized==="task";if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(normalized==="Task"||normalized==="task"){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals51.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot:buildPromptSnapshot2,findByCorrelationId:findByCorrelationId2}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshot:captureWorkspaceSnapshot2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:captureWorkspaceSnapshot2(directory,{prHeadSha,scope}),taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot2(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId2(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals60.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals60.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals60.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable)_internals51.removeWorktreeProvisioningOwner(directory,input.callID);if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals51.preserveDirtyWorktreeForCallId(input.callID,reason,directory),await _internals51.removeWorktree(standardDispatch.handle.worktreePath,directory),await _internals51.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;if(!councilActive){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],perTaskVerdicts=parsePerTaskVerdicts(outputText(_output)),hasPerTaskAttribution=perTaskVerdicts.size>0,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(hasPerTaskAttribution&&!perTaskVerdicts.has(taskId))continue;if(!hasPerTaskAttribution&&gateDispatchPrimaryTaskByCallID.get(input.callID)!==taskId)continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdict=perTaskVerdicts.get(taskId);if(!(targetAgent==="reviewer"?verdict==="APPROVED":verdict==="PASS")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}}}if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder")throw pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`),err}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"&&coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID)}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,ACCEPTANCE_EXPECTED_BODY_CAP=2000,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),_internals60;var init_delegation_gate=__esm(()=>{init_zod();init_workspace_snapshot();init_agent_names();init_schema();init_qa_gate_profile();init_policy();init_gate_evidence_classification();init_file_locks();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now2=Date.now()){for(let[key,expiresAt]of this.expiresAtByKey)if(expiresAt<=now2)this.delete(key)}set(key,value){this.sweepExpired(),this.delete(key),super.set(key,value),this.expiresAtByKey.set(key,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key){return this.sweepExpired(),super.get(key)}has(key){return this.sweepExpired(),super.has(key)}delete(key){return this.expiresAtByKey.delete(key),super.delete(key)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals60={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,forceRecordPlanCriticApproval,get provisionWorktree(){return _internals51.provisionWorktree},set provisionWorktree(v){_internals51.provisionWorktree=v},get removeWorktree(){return _internals51.removeWorktree},set removeWorktree(v){_internals51.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals51.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals51.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals51.postMergeCleanup},set postMergeCleanup(v){_internals51.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals51.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals51.preserveBackgroundWorktreeOwnershipForCallId=v}}});async function handleApprovePlanCriticCommand(directory,args2,sessionID){let reason=(args2??[]).join(" ").trim().slice(0,500);if(!reason)return`Error: a reason is required.
788
+ `)}`,batchWarnSystemIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),batchWarnInsertIdx=batchWarnSystemIdx>=0?batchWarnSystemIdx+1:0,batchWarnMessage={info:{role:"system"},parts:[{type:"text",text:warningText}]};messages.splice(batchWarnInsertIdx,0,batchWarnMessage)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=normalized==="Task"||normalized==="task";if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(normalized==="Task"||normalized==="task"){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals51.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot:buildPromptSnapshot2,findByCorrelationId:findByCorrelationId2}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshot:captureWorkspaceSnapshot2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:captureWorkspaceSnapshot2(directory,{prHeadSha,scope}),taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot2(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId2(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals60.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals60.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals60.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable)_internals51.removeWorktreeProvisioningOwner(directory,input.callID);if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals51.preserveDirtyWorktreeForCallId(input.callID,reason,directory),await _internals51.removeWorktree(standardDispatch.handle.worktreePath,directory),await _internals51.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;if(!councilActive){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],perTaskVerdicts=parsePerTaskVerdicts(outputText(_output)),hasPerTaskAttribution=perTaskVerdicts.size>0,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(hasPerTaskAttribution&&!perTaskVerdicts.has(taskId))continue;if(!hasPerTaskAttribution&&gateDispatchPrimaryTaskByCallID.get(input.callID)!==taskId)continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdict=perTaskVerdicts.get(taskId);if(!(targetAgent==="reviewer"?verdict==="APPROVED":verdict==="PASS")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}}}if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder")throw pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`),err}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"&&coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID)}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),_internals60;var init_delegation_gate=__esm(()=>{init_zod();init_workspace_snapshot();init_agent_names();init_schema();init_qa_gate_profile();init_policy();init_gate_evidence_classification();init_file_locks();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now2=Date.now()){for(let[key,expiresAt]of this.expiresAtByKey)if(expiresAt<=now2)this.delete(key)}set(key,value){this.sweepExpired(),this.delete(key),super.set(key,value),this.expiresAtByKey.set(key,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key){return this.sweepExpired(),super.get(key)}has(key){return this.sweepExpired(),super.has(key)}delete(key){return this.expiresAtByKey.delete(key),super.delete(key)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals60={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,forceRecordPlanCriticApproval,get provisionWorktree(){return _internals51.provisionWorktree},set provisionWorktree(v){_internals51.provisionWorktree=v},get removeWorktree(){return _internals51.removeWorktree},set removeWorktree(v){_internals51.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals51.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals51.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals51.postMergeCleanup},set postMergeCleanup(v){_internals51.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals51.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals51.preserveBackgroundWorktreeOwnershipForCallId=v}}});async function handleApprovePlanCriticCommand(directory,args2,sessionID){let reason=(args2??[]).join(" ").trim().slice(0,500);if(!reason)return`Error: a reason is required.
785
789
 
786
790
  ${USAGE2}`;if(!sessionID?.trim())return`Error: approve-plan-critic requires an active sessionID.
787
791
 
@@ -2381,7 +2385,7 @@ automatically — advisory and never blocking.
2381
2385
  4. Act on the verdict: address REJECT/CONCERNS findings before completing the phase.
2382
2386
 
2383
2387
  Do NOT dispatch the supervisor yourself as a reviewer of code — it is summary-only.
2384
- \`write_architecture_supervisor_evidence\` persists only; it does not run the supervisor.`}function buildCouncilWorkflow(council){if(council?.enabled!==!0)return"";return"## COUNCIL WORKFLOW\n\nANTI-CONFUSION: Do NOT confuse the three council modes:\n(1) `council_mode` — per-task full council replacing Stage B.\n(2) `phase_council` — phase-level holistic review at `phase_complete`.\n(3) `final_council` — project-level final review after all phases.\nNone of these use the General Council (3-agent advisory). The General Council is an early workflow option gated by `council.general.enabled`, not a QA gate.\n\n## A. PER-TASK COUNCIL (when `council_mode` is ON)\n\nWhen `council_mode` is enabled in the QA gate profile, Stage B (reviewer + test_engineer) is **replaced** by the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task. Stage A (`pre_check_batch`) still runs as the pre-review gate.\n\n### PREREQUISITES\n- `declare_council_criteria` must be called for each task before council dispatch.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (task-scoped)\nAfter Stage A passes for a task, in a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`, and `explorer` as parallel Agent tasks. Each member receives task-scoped context:\n- `critic` — task diff + task spec + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — task semantic diff summary + blast radius across changed files\n- `sme` — task domain context + knowledge base entries relevant to the task\n- `test_engineer` — changed test files for the task + coverage delta + known mutation gaps\n- `explorer` — task diff + original task intent + prior slop findings\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (same text as the coder delegation for this task). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_council_verdicts (the per-task tool, NOT submit_phase_council_verdicts)\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_council_verdicts` with the collected verdicts. The per-task council\nverdict replaces the Stage B gate — APPROVE advances the task, REJECT blocks it.\n\n#### STEP 4 — ACT on the verdict\n- **APPROVE**: Task passes. Proceed to the next task.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Re-dispatch the required\n members and re-convene after fixes. The server advances the round; normally omit\n `roundNumber` rather than self-authoring it. This is tool-enforced.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Task passes — surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block task advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If the response has `maxRoundsExhausted: true` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — per-task council bypass violations\n- ✗ Calling `submit_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Falling back to Stage B (reviewer + test_engineer only) when `council_mode` is ON — the full council replaces Stage B.\n- ✗ Skipping `declare_council_criteria` before dispatching council members.\n- ✗ Using `submit_phase_council_verdicts` for per-task verdicts — use `submit_council_verdicts`.\n\n## B. PHASE COUNCIL (when `phase_council` is ON)\n\nCRITICAL: `submit_phase_council_verdicts` does NOT run council members.\nIt synthesizes verdicts that you must collect BEFORE calling it.\n\nWhen `phase_council` is enabled in the QA gate profile, a phase-level council review is required before calling `phase_complete`. This is additive to whichever per-task mechanism is active — Stage B (reviewer + test_engineer) runs per task by default, or the full 5-member per-task council if `council_mode` is ON.\n\n### WHEN TO RUN PHASE COUNCIL\nAfter ALL tasks in the current phase have been marked `completed` and their\nper-task gates have passed, and BEFORE calling `phase_complete`, convene the\nphase council for a Phase Dossier Assembly — a holistic review of cross-cutting concerns,\nbehavioral cohesion, and the full body of work completed in the phase.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (phase-scoped)\nIn a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`,\nand `explorer` as parallel Agent tasks. Each member receives phase-scoped context:\n- `critic` — full diff for the phase + all task specs + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — phase-wide semantic diff summary + blast radius across all changed files\n- `sme` — phase domain context + knowledge base entries relevant to the phase\n- `test_engineer` — all changed test files for the phase + coverage delta + known mutation gaps\n- `explorer` — full phase diff + original task intents + prior slop findings across all tasks\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions introduced anywhere in the phase)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (phase-scoped: concatenate the verbatim FR/SC text for every task in this phase when fr_refs is non-empty, otherwise a one-line phase-derived DONE restatement). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_phase_council_verdicts\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_phase_council_verdicts` with:\n- `phaseNumber`: the phase number just completed (integer, e.g. `1`)\n- `swarmId`: the swarm identifier (e.g. `\"mega\"`)\n- `phaseSummary`: a 2–4 sentence plain-language summary of what the phase accomplished\n- `verdicts`: the array of collected `CouncilMemberVerdict` objects\n- `roundNumber`: normally omit; it is only an optional expectation checked\n against the server-owned current round\n\nThis writes `.swarm/evidence/{phase}/phase-council.json`, which Gate 5 in\n`phase_complete` will read and validate.\n\n#### STEP 4 — READ the response\nInspect `membersAbsent`. If non-empty, dispatch the missing members and re-collect.\nInspect `overallVerdict`.\n\nIf `success: false` and `reason: 'insufficient_quorum'`:\ndispatch ALL absent members in a single parallel batch, wait for all verdicts,\nand re-call `submit_phase_council_verdicts`.\n\n#### STEP 5 — ACT on the verdict, then call phase_complete\n- **APPROVE**: Call `phase_complete`. Gate 5 will pass.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note to the team before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Re-dispatch the required\n members and re-convene after fixes. The server advances the round; normally omit\n `roundNumber` rather than self-authoring it. This is tool-enforced.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Call `phase_complete` and surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the phase council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If the response has `maxRoundsExhausted: true` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — phase council bypass violations\n- ✗ Calling `submit_phase_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Skipping per-task gates because phase council will catch issues — per-task gates are mandatory regardless.\n- ✗ Calling `phase_complete` before council evidence has been written (Gate 5 will block you).\n- ✗ Treating a prior phase's council verdict as valid for a new phase.\n- ✗ Self-authoring or incrementing `roundNumber`; the server owns round progression.\n- ✗ Reusing prior-round member responses instead of re-dispatching members.\n- ✗ Using `submit_council_verdicts` for phase verdicts — use `submit_phase_council_verdicts`.\n\n### ROUND 2 DELIBERATION\nIf round 1 produces REJECT or CONCERNS requiring re-work, every prior-round\ndissenter must be re-dispatched for round 2 focused on the areas they flagged.\nRound 2 must produce NEW agent responses — never reuse round 1 verdicts.\n\n### Retry protocol\nOn re-submission after REJECT/CONCERNS: council members receive (a) the previous\nsynthesis findings plus (b) the diff of what changed since the last round.\nMembers verify prior findings are resolved without re-reviewing unchanged code.\nThe architect resolves any `unresolvedConflicts` in `unifiedFeedbackMd` BEFORE\nsending it to the coder — the coder never sees contradictory instructions."}function buildYourToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return`Task (delegation), ${[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().join(", ")}.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2388
+ \`write_architecture_supervisor_evidence\` persists only; it does not run the supervisor.`}function buildCouncilWorkflow(council){if(council?.enabled!==!0)return"";return"## COUNCIL WORKFLOW\n\nANTI-CONFUSION: Do NOT confuse the three council modes:\n(1) `council_mode` — per-task full council replacing Stage B.\n(2) `phase_council` — phase-level holistic review at `phase_complete`.\n(3) `final_council` — project-level final review after all phases.\nNone of these use the General Council (3-agent advisory). The General Council is an early workflow option gated by `council.general.enabled`, not a QA gate.\n\n## A. PER-TASK COUNCIL (when `council_mode` is ON)\n\nWhen `council_mode` is enabled in the QA gate profile, Stage B (reviewer + test_engineer) is **replaced** by the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task. Stage A (`pre_check_batch`) still runs as the pre-review gate.\n\n### PREREQUISITES\n- `declare_council_criteria` must be called for each task before council dispatch.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (task-scoped)\nAfter Stage A passes for a task, in a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`, and `explorer` as parallel Agent tasks. Each member receives task-scoped context:\n- `critic` — task diff + task spec + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — task semantic diff summary + blast radius across changed files\n- `sme` — task domain context + knowledge base entries relevant to the task\n- `test_engineer` — changed test files for the task + coverage delta + known mutation gaps\n- `explorer` — task diff + original task intent + prior slop findings\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (same text as the coder delegation for this task). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_council_verdicts (the per-task tool, NOT submit_phase_council_verdicts)\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_council_verdicts` with the collected verdicts. The per-task council\nverdict replaces the Stage B gate — APPROVE advances the task, REJECT blocks it.\n\n#### STEP 4 — ACT on the verdict\n- **APPROVE**: Task passes. Proceed to the next task.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Re-dispatch the required\n members and re-convene after fixes. The server advances the round; normally omit\n `roundNumber` rather than self-authoring it. This is tool-enforced.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Task passes — surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block task advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If the response has `maxRoundsExhausted: true` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — per-task council bypass violations\n- ✗ Calling `submit_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Falling back to Stage B (reviewer + test_engineer only) when `council_mode` is ON — the full council replaces Stage B.\n- ✗ Skipping `declare_council_criteria` before dispatching council members.\n- ✗ Using `submit_phase_council_verdicts` for per-task verdicts — use `submit_council_verdicts`.\n\n## B. PHASE COUNCIL (when `phase_council` is ON)\n\nCRITICAL: `submit_phase_council_verdicts` does NOT run council members.\nIt synthesizes verdicts that you must collect BEFORE calling it.\n\nWhen `phase_council` is enabled in the QA gate profile, a phase-level council review is required before calling `phase_complete`. This is additive to whichever per-task mechanism is active — Stage B (reviewer + test_engineer) runs per task by default, or the full 5-member per-task council if `council_mode` is ON.\n\n### WHEN TO RUN PHASE COUNCIL\nAfter ALL tasks in the current phase have been marked `completed` and their\nper-task gates have passed, and BEFORE calling `phase_complete`, convene the\nphase council for a Phase Dossier Assembly — a holistic review of cross-cutting concerns,\nbehavioral cohesion, and the full body of work completed in the phase.\n\n### MANDATORY SEQUENCE — never skip or reorder\n\n#### STEP 1 — DISPATCH all 5 council members in parallel (phase-scoped)\nIn a SINGLE message, dispatch `critic`, `reviewer`, `sme`, `test_engineer`,\nand `explorer` as parallel Agent tasks. Each member receives phase-scoped context:\n- `critic` — full diff for the phase + all task specs + approved-plan baseline (via `get_approved_plan`) + spec-intent drift analysis\n- `reviewer` — phase-wide semantic diff summary + blast radius across all changed files\n- `sme` — phase domain context + knowledge base entries relevant to the phase\n- `test_engineer` — all changed test files for the phase + coverage delta + known mutation gaps\n- `explorer` — full phase diff + original task intents + prior slop findings across all tasks\n (hunts for lazy implementations, hallucinated APIs, cargo-cult patterns,\n spec drift, lazy abstractions introduced anywhere in the phase)\n→ REQUIRED: the `reviewer` member dispatch MUST include a literal `ACCEPTANCE:` line per ACCEPTANCE FIELD RESOLUTION above (phase-scoped: concatenate the verbatim FR/SC text for every task in this phase when fr_refs is non-empty — the delegation gate does NOT auto-inject for multi-task phase/council dispatches, so paste the bodies yourself — otherwise a one-line phase-derived DONE restatement). A missing line is BLOCKED by ACCEPTANCE_FIELD_REQUIRED before that member runs. The other four members are not gated by this rule.\n\nWait for ALL dispatched agents to return their verdict objects before proceeding.\n\n#### STEP 2 — COLLECT verdicts\nRead each agent's response and extract their `CouncilMemberVerdict` object.\nEach member must return: `agent`, `verdict` (APPROVE|CONCERNS|REJECT),\n`confidence` (0.0–1.0), `findings[]`, `criteriaAssessed[]`, `criteriaUnmet[]`,\n`durationMs`.\n\nDo NOT fabricate, infer, or substitute a verdict. If an agent did not return\na valid verdict object, re-dispatch that agent.\n\n#### STEP 3 — CALL submit_phase_council_verdicts\nONLY after collecting real verdicts from all dispatched agents, call\n`submit_phase_council_verdicts` with:\n- `phaseNumber`: the phase number just completed (integer, e.g. `1`)\n- `swarmId`: the swarm identifier (e.g. `\"mega\"`)\n- `phaseSummary`: a 2–4 sentence plain-language summary of what the phase accomplished\n- `verdicts`: the array of collected `CouncilMemberVerdict` objects\n- `roundNumber`: normally omit; it is only an optional expectation checked\n against the server-owned current round\n\nThis writes `.swarm/evidence/{phase}/phase-council.json`, which Gate 5 in\n`phase_complete` will read and validate.\n\n#### STEP 4 — READ the response\nInspect `membersAbsent`. If non-empty, dispatch the missing members and re-collect.\nInspect `overallVerdict`.\n\nIf `success: false` and `reason: 'insufficient_quorum'`:\ndispatch ALL absent members in a single parallel batch, wait for all verdicts,\nand re-call `submit_phase_council_verdicts`.\n\n#### STEP 5 — ACT on the verdict, then call phase_complete\n- **APPROVE**: Call `phase_complete`. Gate 5 will pass.\n If `advisoryFindingsCount > 0`, deliver `unifiedFeedbackMd` as a single\n non-blocking advisory note to the team before proceeding.\n- **CONCERNS with `success: false` + `reason: 'blocking_concerns_unresolved'`**:\n The tool blocked because HIGH/CRITICAL findings from CONCERNS members were\n promoted to `requiredFixes`. No evidence was written. Send `unifiedFeedbackMd`\n to the coder — every `requiredFix` must be resolved. Re-dispatch the required\n members and re-convene after fixes. The server advances the round; normally omit\n `roundNumber` rather than self-authoring it. This is tool-enforced.\n- **CONCERNS with `success: true`**: Only MEDIUM/LOW advisory findings remain.\n Call `phase_complete` and surface `unifiedFeedbackMd` as a non-blocking note.\n- **REJECT**: Block advancement. Send `unifiedFeedbackMd` to the coder\n with the BLOCKING flag. The coder must resolve all `requiredFixes` before\n the phase council is re-convened. Maximum `council.maxRounds` rounds (default 3).\n If the response has `maxRoundsExhausted: true` and verdict is still REJECT, surface\n `unifiedFeedbackMd` to the user and HALT — do NOT auto-advance.\n\n### ANTI-PATTERNS — phase council bypass violations\n- ✗ Calling `submit_phase_council_verdicts` without first dispatching all 5 members.\n- ✗ Passing verdicts inferred or fabricated rather than received from dispatched agents.\n- ✗ Claiming \"Council APPROVED\" when `membersAbsent` is non-empty.\n- ✗ Skipping per-task gates because phase council will catch issues — per-task gates are mandatory regardless.\n- ✗ Calling `phase_complete` before council evidence has been written (Gate 5 will block you).\n- ✗ Treating a prior phase's council verdict as valid for a new phase.\n- ✗ Self-authoring or incrementing `roundNumber`; the server owns round progression.\n- ✗ Reusing prior-round member responses instead of re-dispatching members.\n- ✗ Using `submit_council_verdicts` for phase verdicts — use `submit_phase_council_verdicts`.\n\n### ROUND 2 DELIBERATION\nIf round 1 produces REJECT or CONCERNS requiring re-work, every prior-round\ndissenter must be re-dispatched for round 2 focused on the areas they flagged.\nRound 2 must produce NEW agent responses — never reuse round 1 verdicts.\n\n### Retry protocol\nOn re-submission after REJECT/CONCERNS: council members receive (a) the previous\nsynthesis findings plus (b) the diff of what changed since the last round.\nMembers verify prior findings are resolved without re-reviewing unchanged code.\nThe architect resolves any `unresolvedConflicts` in `unifiedFeedbackMd` BEFORE\nsending it to the coder — the coder never sees contradictory instructions."}function buildYourToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return`Task (delegation), ${[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().join(", ")}.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2385
2389
  `)}function createArchitectAgent(model,customPrompt,customAppendPrompt,adversarialTesting,council,uiReview,memoryEnabled=!1,architecturalSupervision,designDocsEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1,planningProfileResolution=resolvePlanningProfile({directory:"",config:{execution_mode:"strict"}})){let prompt=ARCHITECT_PROMPT;prompt=resolvePrompt(prompt,customPrompt,customAppendPrompt);let planningProfileDirective=renderPlanningProfileDirective(planningProfileResolution,"repository_default");if(prompt?.includes("{{PLANNING_PROFILE_DIRECTIVE}}"))prompt=prompt.replace(/\{\{PLANNING_PROFILE_DIRECTIVE\}\}/g,planningProfileDirective);else prompt=`${prompt??""}
2386
2390
 
2387
2391
  ${planningProfileDirective}`;prompt=prompt?.replace("{{YOUR_TOOLS}}",buildYourToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{AVAILABLE_TOOLS}}",buildAvailableToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{SLASH_COMMANDS}}",buildSlashCommandsList());let councilBlock=buildCouncilWorkflow(council),hasPlaceholder=prompt?.includes("{{COUNCIL_WORKFLOW}}")===!0;if(councilBlock==="")prompt=prompt?.replace(/\n\n\{\{COUNCIL_WORKFLOW\}\}\n\n/g,`
@@ -2748,7 +2752,7 @@ Before delegating to {{AGENT_PREFIX}}reviewer: call check_gate_status for the cu
2748
2752
 
2749
2753
  ACCEPTANCE FIELD RESOLUTION — REQUIRED on every {{AGENT_PREFIX}}coder and {{AGENT_PREFIX}}reviewer Task dispatch. A dispatch with no ACCEPTANCE: line is BLOCKED by the delegation gate before the agent runs (ACCEPTANCE_FIELD_REQUIRED). Resolve it as:
2750
2754
  1. Read the current task's \`fr_refs\` from the plan.
2751
- 2. If \`fr_refs\` is non-empty: look up EVERY listed FR-###/SC-### id in the current \`.swarm/spec.md\` and copy each one's full requirement text into ACCEPTANCE VERBATIMbyte-for-byte, no summarizing or paraphrasing, and concatenate all of them when a task maps to more than one.
2755
+ 2. If \`fr_refs\` is non-empty: list every mapped FR-###/SC-### id on the ACCEPTANCE line (e.g. \`ACCEPTANCE: FR-007, FR-012\`). The delegation gate automatically injects each id's full verbatim requirement text from the current \`.swarm/spec.md\` into the dispatch before the downstream agent runs you do NOT need to copy the requirement bodies yourself (pasting them yourself is also fine and changes nothing). Never replace an id with a summary or paraphrase.
2752
2756
  3. When the task has no spec mapping: if \`fr_refs\` is empty or absent, populate ACCEPTANCE with a task-derived one-line restatement of what DONE looks like instead (the same pattern as \`acceptanceCriteria\` above).
2753
2757
  ACCEPTANCE must never be empty — lacking a spec mapping is normal and is not a reason to omit it.
2754
2758
  NOTE: the plan-task \`acceptance\` field is a different thing. Writing acceptance on the plan task does NOT satisfy this rule. The delegation prompt needs its own literal \`ACCEPTANCE:\` line.
@@ -3496,7 +3500,7 @@ FILE: [target file]
3496
3500
  INPUT: [requirements/context]
3497
3501
  OUTPUT: [expected deliverable]
3498
3502
  CONSTRAINT: [what NOT to do]
3499
- ACCEPTANCE: [verbatim FR/SC requirement text this task must satisfy, copied byte-for-byte from spec.md when the task maps to one or more FR-###/SC-### items — never a paraphrase or summary. When the task maps to no spec requirement, this is a task-derived, one-line restatement of what DONE looks like instead. This field is never empty.]
3503
+ ACCEPTANCE: [the mapped FR-###/SC-### ids this task must satisfy (e.g. FR-007) — the delegation gate injects their verbatim requirement text from spec.md automatically; the injected text is authoritative and never a paraphrase. When the task maps to no spec requirement, this is a task-derived, one-line restatement of what DONE looks like instead. This field is never empty.]
3500
3504
  SKILLS: [optional — either "none", repo-relative file: references (preferred), or inline skill content pasted by architect]
3501
3505
 
3502
3506
  ## STRICT WRITE-SCOPE CONTRACT (MANDATORY)
@@ -5172,7 +5176,7 @@ DIFF: [changed files/functions, or "infer from FILE" if omitted]
5172
5176
  AFFECTS: [callers/consumers/dependents to inspect, or "infer from diff"]
5173
5177
  CHECK: [list of dimensions to evaluate]
5174
5178
  GATES: [pre-completed gate results (lint, SAST, secretscan, etc.), or "none" if unavailable]
5175
- ACCEPTANCE: [verbatim FR/SC requirement text this diff must satisfy, copied byte-for-byte from spec.md when the task maps to one or more FR-###/SC-### items — never a paraphrase or summary. When the task maps to no spec requirement, this is a task-derived, one-line restatement of what DONE looks like instead. This field is never empty.]
5179
+ ACCEPTANCE: [the mapped FR-###/SC-### ids this diff must satisfy (e.g. FR-007) — the delegation gate injects their verbatim requirement text from spec.md automatically; the injected text is authoritative and never a paraphrase. When the task maps to no spec requirement, this is a task-derived, one-line restatement of what DONE looks like instead. This field is never empty.]
5176
5180
  SKILLS: [optional — either "none", repo-relative file: references (preferred), or inline skill content pasted by architect]
5177
5181
  SKILLS_USED_BY_CODER: [list of skill paths that were passed to the coder for this task, or "none" if no skills were used]
5178
5182