opencode-swarm 7.188.6 → 7.188.7

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 (69) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{auto-checkpoint-q2xwy0hz.js → auto-checkpoint-1z9d2jrk.js} +4 -4
  4. package/dist/cli/{checkpoint-9cbytsxe.js → checkpoint-f8165pv4.js} +8 -8
  5. package/dist/cli/{coder-settlement-a74xcmtn.js → coder-settlement-gaby6spt.js} +3 -3
  6. package/dist/cli/{config-doctor-jec44ph0.js → config-doctor-4wgw6nak.js} +7 -7
  7. package/dist/cli/{core-yvx60mhw.js → core-y89texpp.js} +1 -1
  8. package/dist/cli/{curator-drift-t95vqagz.js → curator-drift-rpwrx355.js} +5 -5
  9. package/dist/cli/{curator-llm-factory-znjp0g9d.js → curator-llm-factory-1qbcj7vs.js} +25 -25
  10. package/dist/cli/{curator-wr25srz6.js → curator-tkz65fvw.js} +25 -25
  11. package/dist/cli/{doctor-knowledge-receipt-phase-id-hxyxqqya.js → doctor-knowledge-receipt-phase-id-11q7en6t.js} +4 -4
  12. package/dist/cli/{evidence-summary-service-pzr0aw1h.js → evidence-summary-service-hn7vdm45.js} +9 -9
  13. package/dist/cli/{gate-evidence-0dwbqya4.js → gate-evidence-sxh3r64f.js} +2 -2
  14. package/dist/cli/{guardrail-explain-etssbwma.js → guardrail-explain-e0wbeyk1.js} +26 -26
  15. package/dist/cli/{guardrail-log-055340sb.js → guardrail-log-gzrj46h0.js} +3 -3
  16. package/dist/cli/{guardrail-reset-zdnshfqh.js → guardrail-reset-7z62s1j5.js} +25 -25
  17. package/dist/cli/{hive-promoter-nphztsfb.js → hive-promoter-88d95wk8.js} +25 -25
  18. package/dist/cli/{index-fce5drxa.js → index-03ad14qc.js} +2 -2
  19. package/dist/cli/{index-1pfga0cy.js → index-0j5ggeem.js} +1 -1
  20. package/dist/cli/{index-6yb7fhah.js → index-2vtrjm19.js} +27 -27
  21. package/dist/cli/{index-0bf26e0h.js → index-2wctq2hn.js} +1 -1
  22. package/dist/cli/{index-99h4ez5x.js → index-5102w44y.js} +2 -2
  23. package/dist/cli/{index-16f28gya.js → index-61kszszd.js} +2 -2
  24. package/dist/cli/{index-g1avjt26.js → index-7eajwwfg.js} +1 -1
  25. package/dist/cli/{index-jy33tgeb.js → index-7k9hdn0b.js} +1 -1
  26. package/dist/cli/{index-71b12k03.js → index-7zyktm9f.js} +5 -5
  27. package/dist/cli/{index-0gdyd1mx.js → index-8sqyx5rh.js} +1 -1
  28. package/dist/cli/{index-6p6m98bb.js → index-9tes309n.js} +1 -1
  29. package/dist/cli/{index-aq962xjf.js → index-a4s5yrdd.js} +3 -3
  30. package/dist/cli/{index-yn5r962a.js → index-c016phsk.js} +4 -4
  31. package/dist/cli/{index-hshx5znv.js → index-c937rpbm.js} +3 -3
  32. package/dist/cli/{index-35ythzj4.js → index-eh0sg1pz.js} +3 -3
  33. package/dist/cli/{index-qkhssaay.js → index-emh69vk9.js} +61 -61
  34. package/dist/cli/{index-akg9rdt1.js → index-ffmw6af9.js} +25 -25
  35. package/dist/cli/{index-9c2t70wh.js → index-g39cmzpj.js} +599 -3
  36. package/dist/cli/{index-1r5k2b4v.js → index-ghjg1rxe.js} +1 -1
  37. package/dist/cli/{index-mv2ptr24.js → index-kap459mr.js} +2 -2
  38. package/dist/cli/{index-xhgq58e1.js → index-m9g7s9ee.js} +1 -1
  39. package/dist/cli/{index-s0r30djy.js → index-pnfd3s7s.js} +1 -1
  40. package/dist/cli/{index-jp7qd7r4.js → index-rw0c6qtt.js} +3 -3
  41. package/dist/cli/{index-15836xvt.js → index-snwj9ptc.js} +1 -1
  42. package/dist/cli/{index-sqkz9hyj.js → index-xj3k6x1h.js} +1 -1
  43. package/dist/cli/{index-1cz2j033.js → index-xsdphmet.js} +6 -6
  44. package/dist/cli/{index-9bdz8cbx.js → index-y3sk68m5.js} +1 -1
  45. package/dist/cli/{index-06c2j365.js → index-y8z9x87e.js} +1 -1
  46. package/dist/cli/{index-2sc36smx.js → index-yj1cwps4.js} +1 -1
  47. package/dist/cli/{index-46zge5zc.js → index-ytms8x1h.js} +2 -2
  48. package/dist/cli/index.js +26 -26
  49. package/dist/cli/{knowledge-escalator-h4wqey95.js → knowledge-escalator-ejfb2e7c.js} +7 -7
  50. package/dist/cli/{knowledge-events-jdj0kg0x.js → knowledge-events-3fzfehwy.js} +5 -5
  51. package/dist/cli/{knowledge-store-9pkka657.js → knowledge-store-swxk4tr6.js} +1 -1
  52. package/dist/cli/{knowledge-validator-2hh4838s.js → knowledge-validator-0a1at9gm.js} +2 -2
  53. package/dist/cli/{mcp-dr2qg42d.js → mcp-0ah7s1j0.js} +1 -1
  54. package/dist/cli/{model-preflight-t6megn5m.js → model-preflight-nfvapzyj.js} +25 -25
  55. package/dist/cli/{pending-delegations-96j63y3v.js → pending-delegations-hynywgkj.js} +2 -2
  56. package/dist/cli/{pr-subscriptions-qrc475pd.js → pr-subscriptions-k86p5qcn.js} +1 -1
  57. package/dist/cli/{pr-workflow-gate-1hf06vw7.js → pr-workflow-gate-3ett6hjh.js} +25 -25
  58. package/dist/cli/{scan-cursor-wfa7239s.js → scan-cursor-9961dhv1.js} +2 -2
  59. package/dist/cli/{schema-v3z4wgje.js → schema-s5zbnzmv.js} +1 -1
  60. package/dist/cli/{scope-persistence-k2zq1h9h.js → scope-persistence-2w562h83.js} +5 -5
  61. package/dist/cli/{server-qk8e60ah.js → server-vrk0k61v.js} +25 -25
  62. package/dist/cli/{skill-generator-q6jzjcer.js → skill-generator-bfcjzp20.js} +8 -8
  63. package/dist/cli/{snapshot-coordination-init-h8cqcmve.js → snapshot-coordination-init-8ykpp5m6.js} +25 -25
  64. package/dist/cli/{speckit-checkoff-mh45c204.js → speckit-checkoff-3x52vw64.js} +3 -3
  65. package/dist/cli/{worktree-collision-ownership-hm5y77hr.js → worktree-collision-ownership-kjw1pqfc.js} +2 -2
  66. package/dist/cli/{worktree-isolation-tdst4qs1.js → worktree-isolation-xdgm4ekx.js} +25 -25
  67. package/dist/config/consumers.d.ts +35 -0
  68. package/dist/index.js +5 -5
  69. 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.188.6",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",node:">=22.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/swarm-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/swarm-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","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && 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","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.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:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.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","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@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.3.6"},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"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});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, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",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"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",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, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",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; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",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:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",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"]},scope_validate:{description:"validate shell writes against an inline file scope",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, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), 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 and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). 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","test_engineer"],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, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). 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_receipt_status:{description:"receipt status",agents:["architect"]},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_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",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; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){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,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} 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(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} 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,OPENCODE_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,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_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.188.7",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",node:">=22.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/swarm-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/swarm-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","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && 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","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.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:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.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","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@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.3.6"},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"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});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, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},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), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",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"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",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, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",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; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",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:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",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"]},scope_validate:{description:"validate shell writes against an inline file scope",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, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), 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 and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). 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","test_engineer"],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, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). 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_receipt_status:{description:"receipt status",agents:["architect"]},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_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",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; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){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,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} 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(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} 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,OPENCODE_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,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_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
 
@@ -1259,10 +1259,10 @@ ${expectedBodyBlock}
1259
1259
  `).slice(0,3).join(`
1260
1260
  `),headingMatch=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/im.exec(nextLines);if(headingMatch)return headingMatch[1].toUpperCase()}let lines=text.split(`
1261
1261
  `),tailStart=Math.max(0,lines.length-6),inFence=!1;for(let i=0;i<lines.length;i++){if(/^\s*(?:`{3,})/.test(lines[i]))inFence=!inFence;if(i<tailStart)continue;if(inFence)continue;let line=lines[i];if(line.includes("|"))continue;let bare=/^\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*$/i.exec(line);if(bare)return bare[1].toUpperCase()}return null}function taskLooksLikePlanCritic(args2){let text=[args2.prompt,args2.task,args2.description,args2.message,args2.input].filter((value)=>typeof value==="string").join(`
1262
- `).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error93){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error93 instanceof Error?error93.message:String(error93)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve50)=>setTimeout(resolve50,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path97.join(directory,".swarm","plan.json");if(fs60.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}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}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path97.join(directory,".swarm","plan.json");if(fs60.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error93}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}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}async function hasExplicitEmptyPlanScope(directory,taskId){let planPath=path97.join(directory,".swarm","plan.json"),handle;try{handle=await fs60.promises.open(planPath,"r");let stat9=await handle.stat();if(!stat9.isFile()||stat9.size>MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES)return!1;let bytes=Buffer.alloc(stat9.size),offset=0;while(offset<bytes.length){let result=await handle.read(bytes,offset,bytes.length-offset,offset);if(result.bytesRead===0)return!1;offset+=result.bytesRead}let parsed=JSON.parse(bytes.toString("utf8"));if(!Array.isArray(parsed.phases))return!1;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")continue;let tasks=phase.tasks;if(!Array.isArray(tasks))continue;for(let task of tasks){if(!task||typeof task!=="object")continue;let record3=task;if(record3.id===taskId&&Object.hasOwn(record3,"files_touched")&&Array.isArray(record3.files_touched)&&record3.files_touched.length===0)return!0}}}catch{return!1}finally{await handle?.close().catch(()=>{return})}return!1}async function settleRejectedEmptyPlanScope(directory,input,taskId,expectedGeneration){let baseline=await captureWorkspaceSnapshotAsync(directory);if(baseline.gitHead===null||!Array.isArray(baseline.changedFiles)||baseline.changedFiles.length!==0)return null;let transitionId=`coder-preflight:${input.callID}`;try{await beginCoderSettlement({directory,taskId,transitionId,actor:input.sessionID,expectedGeneration,context:{baseline,declaredFiles:[],workflowGeneration:expectedGeneration}});let observedFiles=await changedFilesSinceSnapshotAsync(directory,baseline);if(observedFiles===null)throw Error("CODER_SETTLEMENT_BASELINE_UNAVAILABLE: empty-scope preflight could not prove a clean post-baseline workspace.");return await settleCoderDispatch({directory,taskId,transitionId,accepted:!1,testEngineerExempt:!1,observedFiles})}catch(error93){try{await abortCoderSettlement({directory,taskId,transitionId,reason:`empty-scope preflight settlement failed: ${error93 instanceof Error?error93.message:String(error93)}`})}catch(abortError){criticalWarn(`[delegation-gate] failed to abort empty-scope preflight settlement for ${taskId}: ${abortError instanceof Error?abortError.message:String(abortError)}`)}throw error93}}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(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(knownPlanTaskIds?.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(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;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: ${knownSummary}.`;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: ${knownSummary}.`;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: ${knownSummary}.`}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 verdicts=new Map,errors5=[],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(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors5.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors5.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors5}}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,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.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){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{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},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error93}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error93}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 isExplicitTaskEvidenceAgent(targetAgent){return EXPLICIT_TASK_EVIDENCE_AGENTS.has(stripKnownSwarmPrefix(targetAgent))}function evidenceTaskResolutionOptions(targetAgent,allowSessionFallback){if(isExplicitTaskEvidenceAgent(targetAgent))return{policy:"attribution",allowSessionFallback:!1};if(allowSessionFallback===!1)return{allowSessionFallback:!1};return}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&&fs60.existsSync(path97.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)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}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 currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. 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 state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))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 collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);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,{plan}).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=path97.resolve(directory),planPath=path97.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path97.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path97.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs60.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((issue3)=>issue3.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,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let policy=options.policy??"plan",planContextOptions=policy==="attribution"&&planTaskIdContext?.status==="over_limit"?{}:planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{},resolutionOptions={policy,...planContextOptions,standaloneTaskMarkerOnly:policy==="attribution"},resolution=resolveTaskId(args2,resolutionOptions);if(resolution.status==="resolved"){let resolvedTaskId=resolution.taskId;if(policy==="attribution"&&!isStrictTaskId(resolvedTaskId)){let markerOnlyArgs={...args2};for(let field of EXPLICIT_TASK_ID_FIELDS)delete markerOnlyArgs[field];let markerResolution=resolveTaskId(markerOnlyArgs,resolutionOptions);if(markerResolution.status!=="resolved"||!isStrictTaskId(markerResolution.taskId))return null;resolvedTaskId=markerResolution.taskId}if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolvedTaskId)))return null;return resolvedTaskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;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 sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function warnStageBSettlementDropped(session,params){let{taskId,agent,reasonClass,drops}=params,restartNote=reasonClass==="unbound"?" The dispatch-generation binding is process-local and was lost — a plugin reload or host restart between dispatch and settlement is the usual cause; no durable binding was found for this dispatch, so it cannot be reconstructed.":"",dedupeToken=`[stageb-settlement-drop:${reasonClass}:${taskId}]`,safeCallID=sanitizeDenialText(params.callID),safeDetail=sanitizeDenialText(params.detail),message=reasonClass==="rejection_persist_failed"?`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}. The rejection verdict was not persisted (fail-closed); the task stays at its current state. Remedy: inspect .swarm/ evidence storage for this task and retry the rejection transition (the verdict need not be re-earned).`:`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}.${restartNote} The clean verdict was not recorded (fail-closed); the task stays at its current state. Remedy: re-dispatch the ${agent} gate for task ${taskId}.`;pushAdvisory(session,message,{dedupeKey:dedupeToken});let tasks=drops.get(reasonClass)??[];tasks.push(taskId),drops.set(reasonClass,tasks)}function flushStageBSettlementDropWarnings(drops){for(let[reasonClass,taskIds]of drops){if(taskIds.length===0)continue;let listed=taskIds.slice(0,10).join(", "),overflow=taskIds.length>10?` (+${taskIds.length-10} more)`:"";criticalWarn(`[delegation-gate] Stage B settlement dropped for task(s) ${listed}${overflow}: ${STAGE_B_SETTLEMENT_DROP_REASONS[reasonClass]}. See session advisories for per-task remedies.`)}drops.clear()}function createDelegationGateHook(config3,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config3.hooks?.delegation_gate!==!1,delegationMaxChars=config3.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config3.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},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 bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession();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],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);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,sessionID,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);let durableStart=Date.now(),persisted=_internals84.recordStageBDispatchBindings(directory,{sessionID:sessionID??"",callID,bindings:[...generations.entries()].map(([taskId,generation])=>({taskId,generation}))}),durableElapsed=Date.now()-durableStart;if(!persisted)criticalWarn(`[delegation-gate] Stage B durable binding write FAILED for call ${callID} — restart recovery for this dispatch is unavailable until re-dispatch (non-fatal; in-memory fencing remains active)`);else if(durableElapsed>50)log(`[delegation-gate] Stage B durable binding write for call ${callID}: persisted=true elapsedMs=${durableElapsed}`)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals84.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=async(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:await captureWorkspaceSnapshotAsync(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}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record3)=>{let callID=record3.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),deleteStageBDispatchBindings(directory,record3.parentSessionId,callID),stageBRouteSlotByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let args2=output.args;if(!isTaskToolId(input.tool)||!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(isTaskToolId(input.tool)&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if(isTaskToolId(input.tool)&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config3.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config3,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(criticModel)}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error93}}}else{let overrideEntry=resolveEffectiveAgentOverride(config3,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config3,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);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,void 0,directory),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,void 0,directory),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(error93){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),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(!isTaskToolId(input.tool))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"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);if(!routeDispatchStarted){warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`);return}let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
1262
+ `).toLowerCase();if(!text)return!1;return PLAN_CRITIC_TASK_SIGNALS.some((signal)=>text.includes(signal))}async function isPlanCriticApproved(directory){try{let plan=await loadPlanJsonOnly(directory);if(!plan)return!1;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)return!1;if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")return!1;if(approved.payloadHash!==computePlanStructureHash(plan))return!1;return!0}catch{return!1}}async function assertPlanCriticApprovedForExecution(directory,plan){if(!plan)return;let planId=derivePlanId(plan),approved=await loadLastPlanCriticApprovedSnapshot(directory,planId);if(!approved)throw Error("PLAN_CRITIC_GATE_VIOLATION: Cannot delegate to coder before plan critic approval. Delegate to critic in MODE: CRITIC-GATE and require VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded "+"(format/signal mismatch — issue #2012), call approve_plan_critic with a reason, "+"or run /swarm approve-plan-critic <reason>, to record a manual approval.");if(approved.approval?.verdict!=="APPROVED"||approved.approval?.source!=="plan_critic_gate")throw Error("PLAN_CRITIC_GATE_VIOLATION: Latest approved-plan snapshot does not contain plan critic VERDICT: APPROVED evidence. Re-run MODE: CRITIC-GATE and wait for explicit approval before coder execution. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic or run /swarm approve-plan-critic.");if(approved.payloadHash!==computePlanStructureHash(plan))throw Error("PLAN_CRITIC_GATE_VIOLATION: Current plan differs from the last critic-approved snapshot. Re-run MODE: CRITIC-GATE after plan changes before delegating to coder. If re-review is not possible, call approve_plan_critic or run /swarm approve-plan-critic to record a fresh manual approval for the current plan.")}function resolvePlanCriticPolicyForExecution(directory,plan,sessionOverrides={}){try{let profile=getProfileForIdentity(directory,{swarm:plan.swarm,title:plan.title});if(!profile)return{required:DEFAULT_QA_GATES.critic_pre_plan,source:"default_missing_profile"};return{required:getEffectiveGates(profile,sessionOverrides).critic_pre_plan,source:sessionOverrides.critic_pre_plan===!0&&profile.gates.critic_pre_plan===!1?"session_ratchet":"persisted_profile"}}catch(error93){return warn(`[delegation-gate] failed to resolve critic_pre_plan profile; enforcing the gate: ${error93 instanceof Error?error93.message:String(error93)}`),{required:!0,source:"corrupt_profile_conservative"}}}async function recordPlanCriticApprovalSnapshotIfApplicable(directory,input,args2,output){if((typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type):null)!=="critic")return;if(!taskLooksLikePlanCritic(args2))return;if(extractPlanCriticVerdict(output)!=="APPROVED")return;let plan=await loadPlanJsonOnly(directory);if(!plan)for(let attempt=0;attempt<2&&!plan;attempt++)await new Promise((resolve50)=>setTimeout(resolve50,150)),plan=await loadPlanJsonOnly(directory);if(!plan){warn("[delegation-gate] plan critic APPROVED verdict could not be recorded: plan.json not readable after retry. The critic_pre_plan gate will block coder delegation until a snapshot exists. Call approve_plan_critic (or /swarm approve-plan-critic) with a reason to record a manual approval if the critic genuinely approved.");return}await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",session_id:input.sessionID,call_id:input.callID,approved_at:new Date().toISOString()},payloadHashOverride:computePlanStructureHash(plan)})}async function forceRecordPlanCriticApproval(directory,sessionID,options={}){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("NOT_AUTHORIZED: approve_plan_critic requires an active architect session. The plan-critic gate escape hatch is an architect-only escalation; a coder/reviewer cannot self-unblock. Run /swarm approve-plan-critic from an architect context, or ask the user to run it.");let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path97.join(directory,".swarm","plan.json");if(fs60.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a plan-critic approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a plan-critic "+"approval for a non-existent plan. Save a plan first.")}let planId=derivePlanId(plan),recordedAt=new Date().toISOString(),sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,userConfirmed=options.userConfirmed===!0;await takeSnapshotEvent(directory,plan,{source:"critic_approved",approvalMetadata:{verdict:"APPROVED",source:"plan_critic_gate",method:"manual_override",reason:sanitizedReason,user_confirmed:userConfirmed,session_id:sessionID,approved_at:recordedAt},payloadHashOverride:computePlanStructureHash(plan)});try{appendCoreEventSync(directory,{type:"plan_critic_gate_manual_approval",timestamp:recordedAt,sessionID,plan_id:planId,user_confirmed:userConfirmed,...sanitizedReason?{reason:sanitizedReason}:{}})}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}}async function forceRecordRetrySoundingBoardApproval(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("APPROVE_RETRY_SOUNDING_BOARD_ARCHITECT_REQUIRED: approve_retry_sounding_board requires an active architect session. The coder retry circuit-breaker escape hatch is architect-only; a coder/reviewer cannot self-unblock.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('APPROVE_RETRY_UNKNOWN_TASK: approve_retry_sounding_board requires the exact plan task id (e.g. "2.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path97.join(directory,".swarm","plan.json");if(fs60.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recording a retry sounding-board approval.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot record a retry "+"sounding-board approval without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))).has(taskId))throw Error(`APPROVE_RETRY_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to record evidence for a foreign task id.`);let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence);if(!evidence||!workflow.authoritative)throw Error(`APPROVE_RETRY_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no retry state to recover.`);let prior;try{prior=readCoderRetryEscalations(directory,taskId,workflow.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("APPROVE_RETRY_AUDIT_INDEX_UNREADABLE: the retry audit authority index is unreadable, so the prior sounding_board_consultation cannot be verified. Repair the events store (see /swarm doctor) and retry.");throw error93}if(!prior.has("sounding_board_consultation"))throw Error(`APPROVE_RETRY_CONSULTATION_REQUIRED: task ${taskId} has no durable sounding_board_consultation escalation for retry epoch ${workflow.retryEpoch}. `+"Dispatch critic_sounding_board first — this tool records an obtained APPROVED verdict, it cannot substitute for the consultation.");let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?options.reason.trim().slice(0,500):void 0,recordedAt=new Date().toISOString(),transitionId=`retry-sb-manual:${sessionID}:epoch${workflow.retryEpoch}`;await recordGateEvidence2(directory,taskId,"critic_sounding_board",sessionID,!1,{transitionId,expectedGeneration:workflow.generation});let auditEventRecorded=!0;try{appendCoreEventSync(directory,{type:"coder_retry_circuit_breaker",timestamp:recordedAt,taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,rejectionCount:workflow.retryCount,rejectionHistory:[...workflow.retryHistory],phase:Number(taskId.split(".")[0])||0,action:"sounding_board_manual_approval",...sanitizedReason?{reason:sanitizedReason}:{}},{dedupeOnAuthorityKey:!0})}catch(err){auditEventRecorded=!1,warn(`[delegation-gate] sounding_board_manual_approval audit event write failed: ${err instanceof Error?err.message:String(err)}`)}return{taskId,generation:workflow.generation,retryEpoch:workflow.retryEpoch,recordedAt,auditEventRecorded}}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}async function hasExplicitEmptyPlanScope(directory,taskId){let planPath=path97.join(directory,".swarm","plan.json"),handle;try{handle=await fs60.promises.open(planPath,"r");let stat9=await handle.stat();if(!stat9.isFile()||stat9.size>MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES)return!1;let bytes=Buffer.alloc(stat9.size),offset=0;while(offset<bytes.length){let result=await handle.read(bytes,offset,bytes.length-offset,offset);if(result.bytesRead===0)return!1;offset+=result.bytesRead}let parsed=JSON.parse(bytes.toString("utf8"));if(!Array.isArray(parsed.phases))return!1;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")continue;let tasks=phase.tasks;if(!Array.isArray(tasks))continue;for(let task of tasks){if(!task||typeof task!=="object")continue;let record3=task;if(record3.id===taskId&&Object.hasOwn(record3,"files_touched")&&Array.isArray(record3.files_touched)&&record3.files_touched.length===0)return!0}}}catch{return!1}finally{await handle?.close().catch(()=>{return})}return!1}async function settleRejectedEmptyPlanScope(directory,input,taskId,expectedGeneration){let baseline=await captureWorkspaceSnapshotAsync(directory);if(baseline.gitHead===null||!Array.isArray(baseline.changedFiles)||baseline.changedFiles.length!==0)return null;let transitionId=`coder-preflight:${input.callID}`;try{await beginCoderSettlement({directory,taskId,transitionId,actor:input.sessionID,expectedGeneration,context:{baseline,declaredFiles:[],workflowGeneration:expectedGeneration}});let observedFiles=await changedFilesSinceSnapshotAsync(directory,baseline);if(observedFiles===null)throw Error("CODER_SETTLEMENT_BASELINE_UNAVAILABLE: empty-scope preflight could not prove a clean post-baseline workspace.");return await settleCoderDispatch({directory,taskId,transitionId,accepted:!1,testEngineerExempt:!1,observedFiles})}catch(error93){try{await abortCoderSettlement({directory,taskId,transitionId,reason:`empty-scope preflight settlement failed: ${error93 instanceof Error?error93.message:String(error93)}`})}catch(abortError){criticalWarn(`[delegation-gate] failed to abort empty-scope preflight settlement for ${taskId}: ${abortError instanceof Error?abortError.message:String(abortError)}`)}throw error93}}function describeCoderScopeFailure(args2,planTaskIdContext){if(planTaskIdContext.status==="over_limit")return`loaded plan task context exceeds the shared bounded limit (${TASK_ID_RESOLUTION_LIMITS.maxKnownIds} task ids); task-id resolution fails closed instead of guessing. Provide an explicit structured scope declaration or narrow the plan context before delegating.`;let resolution=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(planTaskIdContext)}),knownPlanTaskIds=planTaskIdContext.status==="available"?planTaskIdContext.taskIds:void 0,knownSummary=knownPlanTaskIds?[...knownPlanTaskIds].sort().join(", ")||"(none)":"(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(knownPlanTaskIds?.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(knownPlanTaskIds?.has(m[1]))textCandidates.add(m[1])}if(resolution.status==="invalid"&&typeof rawTaskId==="string"&&isStrictTaskId(rawTaskId.trim()))return`explicit task_id "${rawTaskId.trim().slice(0,40)}" is plan-shaped but does not resolve safely against the loaded plan, so resolution fails closed before prompt fallback. Known plan task ids: ${knownSummary}.`;if(resolution.status==="over_limit")return`task-id resolution exceeded a bounded input limit (${resolution.input}); provide exactly one concise TASK: <N.M> line or a valid explicit plan task_id. Known plan task ids: ${knownSummary}.`;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: ${knownSummary}.`;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: ${knownSummary}.`;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: ${knownSummary}.`}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 verdicts=new Map,errors5=[],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(/\r?\n/)){let trimmed=line.trim(),match=reviewedPattern.exec(trimmed);if(match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="REVIEWED")errors5.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs REVIEWED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"REVIEWED"})}continue}if(match=testedPattern.exec(trimmed),match){let taskId=match[1],verdict=match[2];if(isStrictTaskId(taskId)){let existing=verdicts.get(taskId);if(existing){if(existing.verdict!==verdict||existing.kind!=="TESTED")errors5.push(`STAGE_B_VERDICT_CONFLICT: task ${taskId} has conflicting verdicts: ${existing.kind}/${existing.verdict} vs TESTED/${verdict}`)}else verdicts.set(taskId,{verdict,kind:"TESTED"})}}}return{verdicts,errors:errors5}}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,evidence=await readTaskEvidence2(directory,taskId),workflow=getTaskWorkflowSnapshot2(evidence),councilEvidence=evidence?.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){return getCoderRetryEscalationActions(directory,taskId,retryEpoch)}async function emitCoderRetryEscalation(directory,input){try{appendCoreEventSync(directory,{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},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_RETRY_AUDIT_LOCKED");throw error93}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior;try{prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch)}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_RETRY_AUDIT_INDEX_UNREADABLE");throw error93}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 isExplicitTaskEvidenceAgent(targetAgent){return EXPLICIT_TASK_EVIDENCE_AGENTS.has(stripKnownSwarmPrefix(targetAgent))}function evidenceTaskResolutionOptions(targetAgent,allowSessionFallback){if(isExplicitTaskEvidenceAgent(targetAgent))return{policy:"attribution",allowSessionFallback:!1};if(allowSessionFallback===!1)return{allowSessionFallback:!1};return}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&&fs60.existsSync(path97.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)try{if(isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0}catch{return!1}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 currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan),fallbackReason=null;if(pendingTaskIds.length<2)fallbackReason="fewer than two pending tasks in the active phase — nothing to parallelize";else try{let verdict=computeParallelVerdict(directory,pendingTaskIds,{plan});if(verdict.verdict==="all_disjoint");else if(verdict.verdict==="unknown_scopes"){let shown=verdict.unknownScopeTasks.slice(0,6).join(", "),more=verdict.unknownScopeTasks.length>6?` (and ${verdict.unknownScopeTasks.length-6} more)`:"";fallbackReason=`no live declared scope for task${verdict.unknownScopeTasks.length===1?"":"s"}: ${shown}${more} — call declare_scope for each pending task, then retry`}else{let conflictPair=verdict.pairs.find((pair)=>pair.verdict==="conflict"),evidence=(conflictPair?.evidence??[]).slice(0,3).join("; ");fallbackReason=`declared scopes overlap: tasks ${conflictPair?.a??"?"} and ${conflictPair?.b??"?"} conflict (${evidence||"shared paths"})`}}catch{fallbackReason="verdict computation failed (fail-safe serial per v8 contract)"}if(fallbackReason!==null)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; SERIAL fallback active (v8 automatic safety) — exact reason: ${fallbackReason}. 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 state2=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state2))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 collectPendingTaskIdsForActivePhase(plan){let currentPhaseId=resolveActivePhaseId(plan),currentPhase=plan.phases.find((phase)=>phase.id===currentPhaseId);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,{plan}).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=path97.resolve(directory),planPath=path97.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path97.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path97.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs60.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((issue3)=>issue3.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,options={}){let plan=null,planTaskIdContext;try{if(plan=await loadPlanJsonOnly(directory),plan)planTaskIdContext=collectPlanTaskIdContextFromPhases(plan.phases)}catch{}if(args2)try{let policy=options.policy??"plan",planContextOptions=policy==="attribution"&&planTaskIdContext?.status==="over_limit"?{}:planTaskIdContext?toTaskIdPlanContextOptions(planTaskIdContext):{},resolutionOptions={policy,...planContextOptions,standaloneTaskMarkerOnly:policy==="attribution"},resolution=resolveTaskId(args2,resolutionOptions);if(resolution.status==="resolved"){let resolvedTaskId=resolution.taskId;if(policy==="attribution"&&!isStrictTaskId(resolvedTaskId)){let markerOnlyArgs={...args2};for(let field of EXPLICIT_TASK_ID_FIELDS)delete markerOnlyArgs[field];let markerResolution=resolveTaskId(markerOnlyArgs,resolutionOptions);if(markerResolution.status!=="resolved"||!isStrictTaskId(markerResolution.taskId))return null;resolvedTaskId=markerResolution.taskId}if(planTaskIdContext?.status==="over_limit"&&!plan?.phases.some((phase)=>phase?.tasks?.some((task)=>task?.id===resolvedTaskId)))return null;return resolvedTaskId}if(resolution.status==="invalid"||resolution.status==="ambiguous"||resolution.status==="over_limit")return null}catch{}if(options.allowSessionFallback===!1)return null;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 sanitizeDenialText(value){return value.replace(/[\x00-\x1f\x7f]+/g," ")}function isRepairableStageBView(existingView,durableEligibleState){return existingView===void 0||existingView==="rework_required"||compareTaskWorkflowStateRank(durableEligibleState,existingView)>0}function warnStageBSettlementDropped(session,params){let{taskId,agent,reasonClass,drops}=params,restartNote=reasonClass==="unbound"?" The dispatch-generation binding is process-local and was lost — a plugin reload or host restart between dispatch and settlement is the usual cause; no durable binding was found for this dispatch, so it cannot be reconstructed.":"",dedupeToken=`[stageb-settlement-drop:${reasonClass}:${taskId}]`,safeCallID=sanitizeDenialText(params.callID),safeDetail=sanitizeDenialText(params.detail),message=reasonClass==="rejection_persist_failed"?`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}. The rejection verdict was not persisted (fail-closed); the task stays at its current state. Remedy: inspect .swarm/ evidence storage for this task and retry the rejection transition (the verdict need not be re-earned).`:`${dedupeToken} STAGE B SETTLEMENT DROPPED: ${agent} task ${taskId} from call ${safeCallID}: ${safeDetail}.${restartNote} The clean verdict was not recorded (fail-closed); the task stays at its current state. Remedy: re-dispatch the ${agent} gate for task ${taskId}.`;pushAdvisory(session,message,{dedupeKey:dedupeToken});let tasks=drops.get(reasonClass)??[];tasks.push(taskId),drops.set(reasonClass,tasks)}function flushStageBSettlementDropWarnings(drops){for(let[reasonClass,taskIds]of drops){if(taskIds.length===0)continue;let listed=taskIds.slice(0,10).join(", "),overflow=taskIds.length>10?` (+${taskIds.length-10} more)`:"";criticalWarn(`[delegation-gate] Stage B settlement dropped for task(s) ${listed}${overflow}: ${STAGE_B_SETTLEMENT_DROP_REASONS[reasonClass]}. See session advisories for per-task remedies.`)}drops.clear()}function createDelegationGateHook(config3,directory,registeredAgents){initDurableStatusPath(directory);let enabled=config3.hooks?.delegation_gate!==!1,delegationMaxChars=config3.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config3.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,reviewRouteByTaskKey=new Map,stageBRouteSlotByCallID=new Map,reviewRouteTaskKey=(sessionId,taskId)=>`${sessionId}\x00${taskId}`,MAX_REVIEW_ROUTE_RECORDS=128,rememberReviewRoute=(key2,route)=>{reviewRouteByTaskKey.delete(key2),reviewRouteByTaskKey.set(key2,route);while(reviewRouteByTaskKey.size>MAX_REVIEW_ROUTE_RECORDS){let oldest=reviewRouteByTaskKey.keys().next().value;if(!oldest)break;reviewRouteByTaskKey.delete(oldest)}},clearReviewRouteStateForSession=(sessionId)=>{let prefix=`${sessionId}\x00`;for(let key2 of reviewRouteByTaskKey.keys())if(key2.startsWith(prefix))reviewRouteByTaskKey.delete(key2)},bindReviewRouteSlots=(callID,sessionId,role,taskIds)=>{let bindings=new Map,session=swarmState.agentSessions.get(sessionId);for(let taskId of taskIds){let route=reviewRouteByTaskKey.get(reviewRouteTaskKey(sessionId,taskId));if(!route||route.kind!=="review_route_receipt")continue;let identities=role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities;if(slots.length===0||identities.length!==slots.length)continue;let prior=stageBRouteSlotByCallID.get(callID)?.get(taskId),settled=session?getStageBRouteEvidence(session,taskId).find((entry)=>entry.role===role&&entry.sessionId===sessionId&&entry.taskId===taskId&&entry.callId===callID&&entry.generation===stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)):void 0,existing=prior??settled,occupiedSlots=new Set;for(let entry of session?getStageBRouteEvidence(session,taskId):[])if(entry.role===role&&entry.slotId)occupiedSlots.add(entry.slotId);for(let[otherCallId,otherBindings]of stageBRouteSlotByCallID){if(otherCallId===callID)continue;let other=otherBindings.get(taskId);if(other?.role===role&&other.sessionId===sessionId&&other.taskId===taskId&&other.slotId)occupiedSlots.add(other.slotId)}let slotIndex=existing?slots.indexOf(existing.slotId??""):slots.findIndex((slotId2)=>!occupiedSlots.has(slotId2));if(slotIndex<0||slotIndex>=slots.length)continue;let slotId=slots[slotIndex];bindings.set(taskId,{role,identity:identities[slotIndex],sessionId,taskId,slotId,callId:callID,...existing?.childSessionId?{childSessionId:existing.childSessionId}:{},generation:stageBDispatchGenerationsByCallID.get(callID)?.get(taskId)})}if(bindings.size>0)stageBRouteSlotByCallID.set(callID,bindings)},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 bindRouteChildSession=()=>{let routeBindings=stageBRouteSlotByCallID.get(input.callID);if(!routeBindings)return;for(let binding of routeBindings.values())binding.childSessionId=input.childSessionID},result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED"){bindRouteChildSession();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],bindRouteChildSession()},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;clearReviewRouteStateForSession(sessionID);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,sessionID,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);let durableStart=Date.now(),persisted=_internals84.recordStageBDispatchBindings(directory,{sessionID:sessionID??"",callID,bindings:[...generations.entries()].map(([taskId,generation])=>({taskId,generation}))}),durableElapsed=Date.now()-durableStart;if(!persisted)criticalWarn(`[delegation-gate] Stage B durable binding write FAILED for call ${callID} — restart recovery for this dispatch is unavailable until re-dispatch (non-fatal; in-memory fencing remains active)`);else if(durableElapsed>50)log(`[delegation-gate] Stage B durable binding write for call ${callID}: persisted=true elapsedMs=${durableElapsed}`)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals84.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=async(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:await captureWorkspaceSnapshotAsync(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}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record3)=>{let callID=record3.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),deleteStageBDispatchBindings(directory,record3.parentSessionId,callID),stageBRouteSlotByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let args2=output.args;if(!isTaskToolId(input.tool)||!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(isTaskToolId(input.tool)&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if(isTaskToolId(input.tool)&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let exactPreflightAgent=preflightArgs.subagent_type,preflightAgent=stripKnownSwarmPrefix(exactPreflightAgent),registeredMode=registeredAgents?Object.entries(registeredAgents).find(([name])=>name.toLowerCase()===exactPreflightAgent.trim().toLowerCase())?.[1]:void 0,isCriticDispatch=preflightAgent.startsWith("critic"),isRegistryMatchedDispatch=registeredMode!==void 0,isPrimaryDispatch=registeredMode?.mode==="primary";if((isCriticDispatch||isRegistryMatchedDispatch)&&!isPrimaryDispatch){let denialError;if(isCriticDispatch){let legacyCriticModel=config3.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default,criticModel=registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent)??resolveRegisteredAgentModel(config3,exactPreflightAgent)??legacyCriticModel:legacyCriticModel;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),denialError=`PLAN_CRITIC_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(criticModel)}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix the effective model configuration for "${sanitizeDenialText(exactPreflightAgent)}" in opencode-swarm.json (including any matching swarm override or inherited critic model), then re-run MODE: CRITIC-GATE.`}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error93}}}else{let overrideEntry=resolveEffectiveAgentOverride(config3,exactPreflightAgent),finalModel=overrideEntry&&typeof overrideEntry.model==="string"&&overrideEntry.model.trim()===""?"":(registeredAgents?resolveRuntimeAgentModel(config3,registeredAgents,exactPreflightAgent):void 0)??resolveRegisteredAgentModel(config3,exactPreflightAgent);if(finalModel===void 0||finalModel.trim()==="")telemetry.modelUnresolved(preflightAgent,"(no final selection)","swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_MISSING_SELECTION: the ${sanitizeDenialText(exactPreflightAgent)} agent is registered but has no final model selection (blank model override or a stale swarm registry entry) — dispatching it cannot succeed. `+"Fix agents.<role>.model in opencode-swarm.json (the matching swarm override wins over the top-level entry) or correct the swarm configuration, then retry.";else try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(finalModel,swarmState.opencodeClient)==="unresolved")telemetry.modelUnresolved(preflightAgent,finalModel,"swarm-agent dispatch preflight"),denialError=`SWARM_AGENT_MODEL_UNRESOLVED: the ${sanitizeDenialText(exactPreflightAgent)} agent's effective model "${sanitizeDenialText(finalModel)}" does not resolve against the provider catalog — dispatching this role will fail permanently ("Model not found"/"Forbidden"). `+"Fix the effective model configuration in opencode-swarm.json (the matching swarm override wins over top-level agents.<role>.model). fallback_models entries only serve transient runtime failures; configure a resolvable primary model for this role."}catch{}}if(denialError!==void 0){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),Error(denialError)}}}let completionArgs=output.args;if(completionArgs){let completionPlanContext;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanContext=collectPlanTaskIdContextFromPhases(plan2.phases)}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanContext?toTaskIdPlanContextOptions(completionPlanContext):void 0);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,void 0,directory),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,void 0,directory),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(error93){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID,void 0,directory),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(!isTaskToolId(input.tool))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"||targetAgent==="test_engineer"){let routedTaskId=null,routeDispatchStarted=!1;try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let activePrReviewBinding=await readPrReviewReentryBindingContext(directory,input.sessionID),reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory,activePrReviewBinding?{allowSessionFallback:!1}:void 0),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[],routeTaskId=reviewTaskId??`unresolved-${input.callID}`;routedTaskId=routeTaskId,markStageBRouteRequired(reviewSession,routeTaskId);let pendingRoute=buildReviewRoutePending({sessionId:input.sessionID,taskId:routeTaskId});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:pendingRoute}),routeDispatchStarted=!0,rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),pendingRoute),changedFiles.length===0){let routerError=buildReviewRouteRouterError({code:"NO_CHANGED_FILES",sessionId:input.sessionID,taskId:routeTaskId});await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routerError)}else{let routing=await routeReviewForChanges(directory,changedFiles),routeReceipt=buildReviewRouteReceipt({sessionId:input.sessionID,taskId:routeTaskId,complexity:routing.depth,semanticRisk:routing.reason,requiredReviewers:Array.from({length:routing.reviewerCount},(_,index)=>`${routeTaskId}:reviewer:${index+1}`),requiredTestEngineers:Array.from({length:routing.testEngineerCount},(_,index)=>`${routeTaskId}:test_engineer:${index+1}`)});if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routeReceipt}),rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routeTaskId),routeReceipt),shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);if(!routeDispatchStarted){warn(`[delegation-gate] review route dispatch could not establish its pending receipt: ${detail}`);return}let routerError=buildReviewRouteRouterError({code:/unavailable|timed out|timeout|not found/i.test(detail)?"ROUTER_UNAVAILABLE":"ROUTER_FAILED",sessionId:input.sessionID,taskId:routedTaskId??`unresolved-${input.callID}`,detail});try{if(await persistReviewRouteReceipt({projectRoot:directory,receipt:routerError}),routedTaskId)rememberReviewRoute(reviewRouteTaskKey(input.sessionID,routedTaskId),routerError)}catch(persistError){warn(`[delegation-gate] review route receipt was not recorded: ${detail}; router-error persistence failed: ${persistError instanceof Error?persistError.message:String(persistError)}`)}}}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
1263
1263
  `),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 _internals84.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskContext=collectPlanTaskIdContextFromPhases(coveragePlan.phases);if(coverageTaskId=resolveDelegatedPlanTaskId(args2,toTaskIdPlanContextOptions(coveragePlanTaskContext)),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 fs60.promises.readFile(path97.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(`
1264
1264
  `);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 isPrReviewReentryAgent=targetAgent==="reviewer"||targetAgent==="test_engineer";if(isPrReviewReentryAgent&&swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);let stageBSession=ensureAgentSession(input.sessionID,void 0,directory),activePrReviewBinding=isPrReviewReentryAgent?await readPrReviewReentryBindingContext(directory,input.sessionID):null,resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory,evidenceTaskResolutionOptions(targetAgent,activePrReviewBinding?!1:void 0)),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan&&!isExplicitTaskEvidenceAgent(targetAgent)){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(`
1265
- `);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));if(activePrReviewBinding&&!resolvedTaskId&&isPrReviewReentryAgent){if(stageBSession.taskWorkflowStates.size>0||dispatchPlan)throw Error(`TASK_WORKFLOW_TASK_ID_REQUIRED: cannot dispatch ${targetAgent} for PR-review re-entry without an explicit task_id or task identifier in the prompt while a plan or task workflow state exists. Bind the re-entry to the exact task before dispatching; refusing to guess from session or plan state protects parallel tasks from cross-attribution.`);let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(await readPrReviewReentryBindingContext(directory,input.sessionID))throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} without a task workflow because its one-use PR-review re-entry authorization was already consumed or is unavailable. Issue a fresh authorization immediately before the direct Task dispatch.`)}for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config3.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){let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}let stageARemediation=workflow.state==="rework_required"?"Remediation: if the Stage B verdict did not require a code change, call recover_rework_task for task "+taskId+" (architect-only, audited; requires green secretscan AND sast_scan evidence newer than the verdict — normally from a fresh pre_check_batch run; unavailable when SAST is disabled), then re-dispatch. "+"Otherwise delegate the coder to repair the code, re-run pre_check_batch, and re-dispatch once stage_a_passed has fired.":`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`;throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+stageARemediation+(targetAgent==="reviewer"||targetAgent==="test_engineer"?" For PR-review re-entry outside the task workflow, issue a one-use authorization with authorize_pr_review_reentry immediately before the Task dispatch.":""))}}rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID,void 0,directory);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,readTaskEvidenceState:readTaskEvidenceState2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),requestedScopeTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"",classifiedFeedbackScope=isStrictTaskId(requestedScopeTaskId)?await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,requestedScopeTaskId):null,resolvedPreflightTaskId=classifiedFeedbackScope?null:await resolveEvidenceTaskId(args2,session,directory),preflightPlan=classifiedFeedbackScope?null:await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidenceState=preflightTaskId?await readTaskEvidenceState2(directory,preflightTaskId):null;if(preflightEvidenceState?.kind==="unparseable"){let errorName=preflightEvidenceState.error instanceof Error?preflightEvidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${preflightTaskId} evidence at ${preflightEvidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}let preflightEvidence=preflightEvidenceState?.kind==="ok"?preflightEvidenceState.evidence: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(error93){if(preflightTaskId){let transitionId=`coder-preflight:${input.callID}`,explicitEmptyPlanScope=error93 instanceof Error&&error93.message.includes("coder delegation has no complete, valid, non-empty scope.")&&!extractTaskFileDirectives(args2).present&&await hasExplicitEmptyPlanScope(directory,preflightTaskId),settled=null;if(explicitEmptyPlanScope&&preflightWorkflow.generation===0)try{settled=await settleRejectedEmptyPlanScope(directory,input,preflightTaskId,preflightWorkflow.generation)}catch(settlementError){criticalWarn(`[delegation-gate] empty-scope preflight settlement failed for ${preflightTaskId}: ${settlementError instanceof Error?settlementError.message:String(settlementError)}`)}let failedWorkflow=getTaskWorkflowSnapshot2(settled?.evidence??await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId}));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 error93}let{taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let 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;try{await _internals84.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error93){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state2])=>state2==="coder_delegated").map(([taskId])=>taskId),claim=await _internals84.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(preparedScope.kind==="pr_feedback"){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}return}let plan=preparedScope.plan,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,evidenceState=await readTaskEvidenceState2(directory,taskId);if(evidenceState.kind==="unparseable"){if(incomingCoderTaskId&&taskId===incomingCoderTaskId){let errorName=evidenceState.error instanceof Error?evidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}warn(`[delegation-gate] Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build — treating as idle for this dispatch. Repair it before the task's next delegation.`)}let durableWorkflow=getTaskWorkflowSnapshot2(evidenceState.kind==="ok"?evidenceState.evidence:null),state2=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state2),updateTaskWorkflowCache(session,taskId,durableWorkflow),state2!=="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(config3)),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))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await 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:config3,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,reservationId:backgroundCoderReservationByCallID.get(input.callID)?.reservationId??buildBackgroundCoderReservationId({parentSessionId:input.sessionID,planTaskId:resolvedTaskId,callID:input.callID}),generation:coderDispatchGeneration,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(error93){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config3).worktree_dir),error93}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{appendCoreEventSync(directory,{type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}catch(eventError){log(`[delegation-gate] worktree_isolation_degraded event write failed: ${eventError instanceof Error?eventError.message:String(eventError)}`)}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,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner)}:void 0)}catch(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}},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,void 0,directory).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(`
1265
+ `);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));if(activePrReviewBinding&&!resolvedTaskId&&isPrReviewReentryAgent){if(stageBSession.taskWorkflowStates.size>0||dispatchPlan)throw Error(`TASK_WORKFLOW_TASK_ID_REQUIRED: cannot dispatch ${targetAgent} for PR-review re-entry without an explicit task_id or task identifier in the prompt while a plan or task workflow state exists. Bind the re-entry to the exact task before dispatching; refusing to guess from session or plan state protects parallel tasks from cross-attribution.`);let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,null),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED",standalonePrReviewReentry:!0}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(await readPrReviewReentryBindingContext(directory,input.sessionID))throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} without a task workflow because its one-use PR-review re-entry authorization was already consumed or is unavailable. Issue a fresh authorization immediately before the direct Task dispatch.`)}for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config3.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")){if(generations.set(taskId,workflow.generation),isRepairableStageBView(stageBSession.taskWorkflowStates.get(taskId),workflow.state))stageBSession.taskWorkflowStates.set(taskId,workflow.state),updateTaskWorkflowCache(stageBSession,taskId,workflow);continue}if(taskId===resolvedTaskId){let{reserveActivePrReviewReentryAuthorization}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));if(await reserveActivePrReviewReentryAuthorization(directory,input.sessionID,{role:targetAgent==="test_engineer"?"test_engineer":"reviewer",callID:input.callID})){rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}let stageARemediation=workflow.state==="rework_required"?"Remediation: if the Stage B verdict did not require a code change, call recover_rework_task for task "+taskId+" (architect-only, audited; requires green secretscan AND sast_scan evidence newer than the verdict — normally from a fresh pre_check_batch run; unavailable when SAST is disabled), then re-dispatch. "+"Otherwise delegate the coder to repair the code, re-run pre_check_batch, and re-dispatch once stage_a_passed has fired.":`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`;throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+stageARemediation+(targetAgent==="reviewer"||targetAgent==="test_engineer"?" For PR-review re-entry outside the task workflow, issue a one-use authorization with authorize_pr_review_reentry immediately before the Task dispatch.":""))}}rememberStageBDispatchGenerations(input.callID,input.sessionID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"}),bindReviewRouteSlots(input.callID,input.sessionID,targetAgent,generations.keys());return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID,void 0,directory);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,readTaskEvidenceState:readTaskEvidenceState2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),requestedScopeTaskId=typeof args2.task_id==="string"?args2.task_id.trim():typeof args2.taskId==="string"?args2.taskId.trim():"",classifiedFeedbackScope=isStrictTaskId(requestedScopeTaskId)?await resolvePrFeedbackScopeDeclaration(directory,input.sessionID,requestedScopeTaskId):null,resolvedPreflightTaskId=classifiedFeedbackScope?null:await resolveEvidenceTaskId(args2,session,directory),preflightPlan=classifiedFeedbackScope?null:await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidenceState=preflightTaskId?await readTaskEvidenceState2(directory,preflightTaskId):null;if(preflightEvidenceState?.kind==="unparseable"){let errorName=preflightEvidenceState.error instanceof Error?preflightEvidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${preflightTaskId} evidence at ${preflightEvidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}let preflightEvidence=preflightEvidenceState?.kind==="ok"?preflightEvidenceState.evidence: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(error93){if(preflightTaskId){let transitionId=`coder-preflight:${input.callID}`,explicitEmptyPlanScope=error93 instanceof Error&&error93.message.includes("coder delegation has no complete, valid, non-empty scope.")&&!extractTaskFileDirectives(args2).present&&await hasExplicitEmptyPlanScope(directory,preflightTaskId),settled=null;if(explicitEmptyPlanScope&&preflightWorkflow.generation===0)try{settled=await settleRejectedEmptyPlanScope(directory,input,preflightTaskId,preflightWorkflow.generation)}catch(settlementError){criticalWarn(`[delegation-gate] empty-scope preflight settlement failed for ${preflightTaskId}: ${settlementError instanceof Error?settlementError.message:String(settlementError)}`)}let failedWorkflow=getTaskWorkflowSnapshot2(settled?.evidence??await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId}));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 error93}let{taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let 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;try{await _internals84.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error93){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state2])=>state2==="coder_delegated").map(([taskId])=>taskId),claim=await _internals84.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(preparedScope.kind==="pr_feedback"){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}return}let plan=preparedScope.plan,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,evidenceState=await readTaskEvidenceState2(directory,taskId);if(evidenceState.kind==="unparseable"){if(incomingCoderTaskId&&taskId===incomingCoderTaskId){let errorName=evidenceState.error instanceof Error?evidenceState.error.name:"UnknownError";throw Error(`TASK_EVIDENCE_UNREADABLE: Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build (${errorName}); refusing to treat it as idle. Repair or remove the evidence file (repair_gate_evidence) before dispatching.`)}warn(`[delegation-gate] Task ${taskId} evidence at ${evidenceState.evidencePath} is corrupt or from an incompatible build — treating as idle for this dispatch. Repair it before the task's next delegation.`)}let durableWorkflow=getTaskWorkflowSnapshot2(evidenceState.kind==="ok"?evidenceState.evidence:null),state2=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state2),updateTaskWorkflowCache(session,taskId,durableWorkflow),state2!=="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(config3)),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))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await 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:config3,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,reservationId:backgroundCoderReservationByCallID.get(input.callID)?.reservationId??buildBackgroundCoderReservationId({parentSessionId:input.sessionID,planTaskId:resolvedTaskId,callID:input.callID}),generation:coderDispatchGeneration,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(error93){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config3).worktree_dir),error93}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))await rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{appendCoreEventSync(directory,{type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}catch(eventError){log(`[delegation-gate] worktree_isolation_degraded event write failed: ${eventError instanceof Error?eventError.message:String(eventError)}`)}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,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner)}:void 0)}catch(error93){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error93}},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,void 0,directory).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(`
1266
1266
  `),trimComment=`[Task window: showing ${visibleCount} of ${totalTasks} tasks]`,trimmedMiddle=(hiddenBefore>0?`[...${hiddenBefore} tasks hidden...]
1267
1267
  `:"")+visibleLines+(hiddenAfter>0?`
1268
1268
  [...${hiddenAfter} tasks hidden...]`:"");textPart.text=`${before}${trimmedMiddle}
@@ -1271,7 +1271,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
1271
1271
  ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else guidance=parallelGuidance??"[NEXT] Begin the first plan task and run gates sequentially.";let carrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),insertIdx=carrierIdx>=0?carrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",guidance,insertIdx)}}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,void 0,directory),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.
1272
1272
  Rule 3: ONE task per coder call. Split this into separate delegations.
1273
1273
  ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1274
- `)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);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,void 0,directory),councilActive=await isCouncilGateActive(directory,config3.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(isTaskTool2){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 _internals83.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,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=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},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),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,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?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,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals84.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 _internals84.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 _internals84.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))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){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals83.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.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,await changedFilesSinceSnapshotAsync(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,config3,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge);coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged",observedFiles:observedForMerge,settlementFailed:unattributedEmptyScopeMutation})).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,void 0,directory);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 _internals83.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals83.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals83.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,void 0,directory);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;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);let stageBSettlementDrops=new Map;do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state2))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state2,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===taskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)launchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B binding for ${taskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"unbound",detail:"ignoring unbound Stage B settlement",drops:stageBSettlementDrops});continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${state2} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){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)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"rejection_persist_failed",detail:`rejection could not be persisted: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops})}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config3.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:`route receipt blocked: ${routeDecision.reason??"unknown reason"}`,drops:stageBSettlementDrops});continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_capacity",detail:"route evidence capacity exceeded",drops:stageBSettlementDrops});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}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"evidence_rejected",detail:`gate evidence recording rejected the settlement: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops});continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(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(routeComplete&&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)}`)}}}while(!1);flushStageBSettlementDropWarnings(stageBSettlementDrops)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].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){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===evidenceTaskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)gateLaunchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B gate binding for ${evidenceTaskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}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)??await changedFilesSinceSnapshotAsync(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)):[],unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(taskChangeContext?.declaredFiles,rawObservedFiles),context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&(observedFiles.length>0||unattributedEmptyScopeMutation),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||unattributedEmptyScopeMutation,observedFiles:rawObservedFiles})).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"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(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),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="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,abortDeniedSettlementForCall:async(callID,sessionID)=>{if(stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),sessionID)deleteStageBDispatchBindings(directory,sessionID,callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error93){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}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,MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES=4194304,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_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),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals84,STAGE_B_SETTLEMENT_DROP_REASONS;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_stage_b_dispatch_binding_store();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_system_guidance_carrier();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(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,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(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}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"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals84={recordStageBDispatchBindings,readStageBDispatchBindings,deleteStageBDispatchBindings,resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals83.provisionWorktree},set provisionWorktree(v){_internals83.provisionWorktree=v},get removeWorktree(){return _internals83.removeWorktree},set removeWorktree(v){_internals83.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals83.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals83.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals83.postMergeCleanup},set postMergeCleanup(v){_internals83.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals83.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals83.preserveBackgroundWorktreeOwnershipForCallId=v}};STAGE_B_SETTLEMENT_DROP_REASONS={unbound:"unbound launch generation (the dispatch-generation binding is process-local and was lost)",route_blocked:"review route receipt enforcement blocked the settlement",route_capacity:"route evidence capacity exceeded",evidence_rejected:"gate evidence recording rejected the settlement (generation fencing)",rejection_persist_failed:"the rejection verdict could not be persisted"}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
1274
+ `)}`,batchWarnCarrierIdx=messages.findIndex((m)=>m&&isGuidanceCarrier(m)),batchWarnInsertIdx=batchWarnCarrierIdx>=0?batchWarnCarrierIdx+1:0;insertGuidanceCarrier(messages,"delegation",warningText,batchWarnInsertIdx)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=isTaskToolId(input.tool);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,void 0,directory),councilActive=await isCouncilGateActive(directory,config3.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(isTaskTool2){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 _internals83.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,findByCorrelationIdDetailed}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshotAsync:captureWorkspaceSnapshotAsync2}=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},normalizedSubagentType=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(normalizedSubagentType)),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,fallbackWorkspace=taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:await captureWorkspaceSnapshotAsync2(directory,{prHeadSha,scope}),pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:fallbackWorkspace,taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(normalizedSubagentType)?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,provisioningOwner:exactProvisioningOwnerForBackgroundDescriptor(standardDispatch.provisioningOwner),reservationId:standardDispatch.reservationId,generation:standardDispatch.generation}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwnerRead=findByCorrelationIdDetailed(directory,subagentSessionId);if(existingOwnerRead.status==="uncertain")throw Error(`delegation store unreadable after ${existingOwnerRead.attempts} attempts (${existingOwnerRead.reason}); cannot verify the existing owner for background correlation ${subagentSessionId}`);let existingOwner=existingOwnerRead.value,pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals84.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 _internals84.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 _internals84.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))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){let provisioningOwner=standardDispatch?.provisioningOwner??(standardDispatch?.reservationId!==void 0&&standardDispatch?.generation!==void 0?{reservationId:standardDispatch.reservationId,generation:standardDispatch.generation,branchName:standardDispatch.handle.branchName}:void 0);_internals83.removeWorktreeProvisioningOwner(directory,input.callID,provisioningOwner)}if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.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,await changedFilesSinceSnapshotAsync(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,config3,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async(merged)=>{let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge);coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge),landedUnstaged:merged.strategy==="squash-unstaged",observedFiles:observedForMerge,settlementFailed:unattributedEmptyScopeMutation})).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,void 0,directory);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 _internals83.preserveDirtyWorktreeForCallId(input.callID,reason,directory),closeProjectDb(standardDispatch.handle.worktreePath);let removal=await _internals83.removeWorktree(standardDispatch.handle.worktreePath,directory).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)recordDeadLaneReclaim(directory,{lanePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,reason:removalError}),pushAdvisory(ensureAgentSession(standardDispatch.parentSessionID,void 0,directory),`WORKTREE_LANE_STRANDED: lane ${standardDispatch.handle.worktreePath} could not be removed (${removalError}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`);await _internals83.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,void 0,directory);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;let standalonePrReviewReentry=stageBDispatchContextByCallID.get(input.callID)?.standalonePrReviewReentry===!0;if(!councilActive&&!standalonePrReviewReentry){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);let stageBSettlementDrops=new Map;do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state2]of session.taskWorkflowStates){if(!attributionResult.verdicts.has(taskId))continue;let effectiveState=state2;if(!stageBEligibleStates.includes(state2)){if(stageBDispatchContextByCallID.get(input.callID)?.taskIds?.has(taskId)){let durableSnapshot=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId));if(durableSnapshot.authoritative&&stageBEligibleStates.includes(durableSnapshot.state)&&isRepairableStageBView(state2,durableSnapshot.state))session.taskWorkflowStates.set(taskId,durableSnapshot.state),updateTaskWorkflowCache(session,taskId,durableSnapshot),effectiveState=durableSnapshot.state,log(`[delegation-gate] resynced Stage B settlement view for ${taskId} from durable evidence (in-memory said ${state2})`)}if(!stageBEligibleStates.includes(effectiveState))continue}let eligibleState=effectiveState,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===taskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)launchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B binding for ${taskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"unbound",detail:"ignoring unbound Stage B settlement",drops:stageBSettlementDrops});continue}let verdictEntry=attributionResult.verdicts.get(taskId),dispatchCtxForVerdict=stageBDispatchContextByCallID.get(input.callID);if(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"&&verdictEntry?.verdict==="SKIPPED"){warn(`[delegation-gate] Stage B test gate SKIPPED (tests not run) for task ${taskId} from call ${input.callID} — leaving state ${effectiveState} for test-gate re-dispatch; reviewer proof preserved`);continue}if(!(dispatchCtxForVerdict?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){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)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"rejection_persist_failed",detail:`rejection could not be persisted: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops})}continue}let routeBinding=stageBRouteSlotByCallID.get(input.callID)?.get(taskId),legacyUnrouted=!isStageBRouteRequired(session,taskId)&&!routeBinding&&(()=>{try{return isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),existingRouteEvidence=getStageBRouteEvidence(session,taskId),prospectiveRouteEvidence=routeBinding?[...existingRouteEvidence.filter((entry)=>entry.role!==routeBinding.role||entry.sessionId!==routeBinding.sessionId||entry.taskId!==routeBinding.taskId||entry.callId!==routeBinding.callId||entry.childSessionId!==routeBinding.childSessionId||entry.generation!==routeBinding.generation),routeBinding]:getStageBRouteEvidence(session,taskId),routeEnforcementEnabled=config3.review_routing?.enforce_receipts??!0,routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:routeEnforcementEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:routeBinding?{role:routeBinding.role,identity:routeBinding.identity,callId:routeBinding.callId,childSessionId:routeBinding.childSessionId,generation:routeBinding.generation}:void 0});if(!routeDecision.canAdvance){warn(`[delegation-gate] Stage B route receipt blocked ${taskId}: ${routeDecision.reason??"unknown reason"}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_blocked",detail:`route receipt blocked: ${routeDecision.reason??"unknown reason"}`,drops:stageBSettlementDrops});continue}let routeCompleteDecision=routeEnforcementEnabled&&routeBinding?enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:input.sessionID,taskId,receipts:prospectiveRouteEvidence,enforcementEnabled:!0,requireEvidenceBindings:!0,requireCompleteEvidence:!0}):void 0,routeComplete=routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:routeDecision.canAdvance,routeEvidenceRollback=routeBinding?reserveStageBRouteEvidence(session,taskId,routeBinding):null;if(routeBinding&&!routeEvidenceRollback){warn(`[delegation-gate] Stage B route evidence capacity exceeded for ${taskId}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"route_capacity",detail:"route evidence capacity exceeded",drops:stageBSettlementDrops});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}`,routeBinding,routeComplete:routeEnforcementEnabled&&routeBinding?routeCompleteDecision?.canAdvance??!1:void 0})}catch(err){routeEvidenceRollback?.(),warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`),warnStageBSettlementDropped(session,{taskId,agent:targetAgent,callID:input.callID,reasonClass:"evidence_rejected",detail:`gate evidence recording rejected the settlement: ${err instanceof Error?err.message:String(err)}`,drops:stageBSettlementDrops});continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(routeComplete&&(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(routeComplete&&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)}`)}}}while(!1);flushStageBSettlementDropWarnings(stageBSettlementDrops)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},targetAgentForEvidence=stripKnownSwarmPrefix(subagentType),evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory,evidenceTaskResolutionOptions(targetAgentForEvidence));if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID);if(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"].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){let reconstructed=_internals84.readStageBDispatchBindings(directory,input.sessionID,input.callID)?.bindings.find((b)=>b.taskId===evidenceTaskId)?.generation;if(reconstructed!==void 0&&Number.isInteger(reconstructed)&&reconstructed>=0)gateLaunchGeneration=reconstructed,log(`[delegation-gate] reconstructed Stage B gate binding for ${evidenceTaskId} from durable store (call ${input.callID}, generation ${reconstructed}) — fencing proceeds as in-process`)}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)??await changedFilesSinceSnapshotAsync(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)):[],unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(taskChangeContext?.declaredFiles,rawObservedFiles),context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&(observedFiles.length>0||unattributedEmptyScopeMutation),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||unattributedEmptyScopeMutation,observedFiles:rawObservedFiles})).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"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(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),deleteStageBDispatchBindings(directory,input.sessionID??"",input.callID),stageBRouteSlotByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state2]of session.taskWorkflowStates)if(state2==="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,abortDeniedSettlementForCall:async(callID,sessionID)=>{if(stageBRouteSlotByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),sessionID)deleteStageBDispatchBindings(directory,sessionID,callID);let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error93){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}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,MAX_RAW_PLAN_SCOPE_INSPECTION_BYTES=4194304,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,EXPLICIT_TASK_EVIDENCE_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),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals84,STAGE_B_SETTLEMENT_DROP_REASONS;var init_delegation_gate=__esm(()=>{init_zod();init_pending_delegations();init_stage_b_dispatch_binding_store();init_workspace_snapshot();init_agent_model();init_agent_names();init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_core_events();init_task_gate_requirements();init_policy();init_gate_evidence();init_gate_evidence_classification();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_routing_enforcement();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_plan_task_id_context();init_task_id_resolver();init_task_id_resolver();init_project_db();init_coder_settlement();init_task_repair();init_task_terminal();init_dead_lane_reclaim();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_system_guidance_carrier();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(now=Date.now()){for(let[key2,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key2)}set(key2,value){this.sweepExpired(),this.delete(key2),super.set(key2,value),this.expiresAtByKey.set(key2,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(key2){return this.sweepExpired(),super.get(key2)}has(key2){return this.sweepExpired(),super.has(key2)}delete(key2){return this.expiresAtByKey.delete(key2),super.delete(key2)}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"]),EXPLICIT_TASK_EVIDENCE_AGENTS=new Set(["critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor"]);_internals84={recordStageBDispatchBindings,readStageBDispatchBindings,deleteStageBDispatchBindings,resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,extractPlanTaskId,forceRecordPlanCriticApproval,beforePrFeedbackScopeConsume:void 0,get provisionWorktree(){return _internals83.provisionWorktree},set provisionWorktree(v){_internals83.provisionWorktree=v},get removeWorktree(){return _internals83.removeWorktree},set removeWorktree(v){_internals83.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals83.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals83.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals83.postMergeCleanup},set postMergeCleanup(v){_internals83.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals83.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals83.preserveBackgroundWorktreeOwnershipForCallId=v}};STAGE_B_SETTLEMENT_DROP_REASONS={unbound:"unbound launch generation (the dispatch-generation binding is process-local and was lost)",route_blocked:"review route receipt enforcement blocked the settlement",route_capacity:"route evidence capacity exceeded",evidence_rejected:"gate evidence recording rejected the settlement (generation fencing)",rejection_persist_failed:"the rejection verdict could not be persisted"}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state2){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state2);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state2=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state2?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state2||state2.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state2.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
1275
1275
  `)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function trajectoryStepGeneration(){return stepCounterGeneration}function bumpStepCounterGeneration(){stepCounterGeneration+=1}function evictOldestStepSessionIfNeeded(key2){if(sessionStepCounters.has(key2))return;while(sessionStepCounters.size>=MAX_TRACKED_STEP_SESSIONS){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId,directory){let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let step=(sessionStepCounters.get(key2)??0)+1;return sessionStepCounters.set(key2,step),step}function seedTrajectoryStepCounter(sessionId,directory,step){if(!Number.isFinite(step)||step<=0)return;let key2=compositeSessionKey(directory,sessionId);evictOldestStepSessionIfNeeded(key2);let current=sessionStepCounters.get(key2)??0;if(step>current)sessionStepCounters.set(key2,Math.floor(step))}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0){let suffix=sessionKeySuffix(sessionId),removed=!1;for(let key2 of sessionStepCounters.keys())if(key2.endsWith(suffix))sessionStepCounters.delete(key2),removed=!0;if(removed)bumpStepCounterGeneration()}else if(sessionStepCounters.size>0)sessionStepCounters.clear(),bumpStepCounterGeneration()}var MAX_TRACKED_STEP_SESSIONS=500,sessionStepCounters,stepCounterGeneration=0;var init_trajectory_step_state=__esm(()=>{init_canonical_root();sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key2,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key2);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature){let next={key:key2,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current)return!1;if(expectedGeneration!==void 0&&current.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key2)}function peekScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key2=entryKey(scope),current=scopedModelOverrides.get(key2);if(!current||current.signature!==chain.signature)return;return current.updatedAt=now,scopedModelOverrides.delete(key2),scopedModelOverrides.set(key2,current),selectionFromEntry(current,chain)}function clearScopedModelSelectionsForSession(sessionID,opts){let normalizedSessionID=normalizeText2(sessionID),primaryScopes=opts?.primaryScopes??!0;for(let[key2,entry]of scopedModelOverrides){if(!key2.startsWith(`${normalizedSessionID}␟`))continue;if(!primaryScopes){if((key2.split("␟")[1]??"")==="")continue}scopedModelOverrides.delete(entry.key)}}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key2=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key2);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key2),routesByParentCall.set(key2,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key2)}function pruneRoutes(now){for(let[key2,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key2=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key2);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function sessionFallbackScope(input){return{sessionID:normalizeText3(input.sessionID),invocationID:PRIMARY_SESSION_INVOCATION_ID,swarmID:normalizeText3(input.swarmID)||void 0,role:normalizeText3(input.role)}}function advanceSessionFallbackSelection(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(scope,chain,now),advanced=advanceScopedModelSelection(scope,chain,selection.generation,now);return{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,modelString:advanced.selection.modelString,scope}}function resolveSessionChatModelOverride(input){let now=input.now??Date.now(),scope=sessionFallbackScope(input),chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]);if(chain.fallbacks.length===0)return{status:"missing"};let selection=peekScopedModelSelection(scope,chain,now);if(selection===void 0)return{status:"missing"};if(selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex}}function recordSessionChatAgent(sessionID,agentName){let session=normalizeText3(sessionID),agent=normalizeText3(agentName);if(!session||!agent)return;while(sessionChatAgentBySession.size>=MAX_SESSION_CHAT_AGENTS){let oldest=sessionChatAgentBySession.keys().next().value;if(typeof oldest!=="string")break;sessionChatAgentBySession.delete(oldest)}sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent)}function resolveSessionChatAgent(sessionID){let session=normalizeText3(sessionID);if(!session)return;let agent=sessionChatAgentBySession.get(session);if(agent===void 0)return;return sessionChatAgentBySession.delete(session),sessionChatAgentBySession.set(session,agent),agent}function clearPendingTaskModelRoutesForSession(sessionID,mode="session"){let normalizedSessionID=normalizeText3(sessionID);for(let[key2,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key2),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}if(clearScopedModelSelectionsForSession(normalizedSessionID,{primaryScopes:mode==="session"}),mode==="session")sessionChatAgentBySession.delete(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),sessionChatAgentBySession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,MAX_SESSION_CHAT_AGENTS=256,sessionChatAgentBySession,routesByParentCall,routeKeyByChildSession,PRIMARY_SESSION_INVOCATION_ID="";var init_task_model_routing=__esm(()=>{init_model_override_state();sessionChatAgentBySession=new Map,routesByParentCall=new Map,routeKeyByChildSession=new Map});function evictOldest(map3,cap){while(map3.size>=cap){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}function hydrationProjectKey(directory){let memoKey=canonicalRootKeyLexical(directory),memoized=directoryKeyMemo.get(memoKey);if(memoized!==void 0)return memoized;let key2=canonicalProjectKey(directory);if(!directoryKeyMemo.has(memoKey))evictOldest(directoryKeyMemo,MAX_DIRECTORY_KEY_MEMO);return directoryKeyMemo.set(memoKey,key2),key2}function beginHydrationScope(directory){let projectKey=hydrationProjectKey(directory),current=projectHydrationAuthorities.get(projectKey),generation=(current?.generation??0)+1;if(!current)evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let authorityEpoch=current?.authorityEpoch??nextHydrationAuthorityEpoch();return projectHydrationAuthorities.set(projectKey,{generation,authorityEpoch}),{projectKey,generation,authorityEpoch}}function currentHydrationGeneration(projectKey){return projectHydrationAuthorities.get(projectKey)?.generation??0}function captureCurrentHydrationAuthority(projectKey){let current=projectHydrationAuthorities.get(projectKey);if(current)return{projectKey,...current};let authorityEpoch=nextHydrationAuthorityEpoch();evictOldest(projectHydrationAuthorities,MAX_TRACKED_PROJECTS);let record3={generation:0,authorityEpoch};return projectHydrationAuthorities.set(projectKey,record3),{projectKey,...record3}}function nextHydrationAuthorityEpoch(){if(hydrationAuthorityEpoch>=Number.MAX_SAFE_INTEGER)throw Error("hydration authority epoch exhausted");return hydrationAuthorityEpoch+=1,hydrationAuthorityEpoch}function isHydrationAuthorityCurrent(authority){let current=projectHydrationAuthorities.get(authority.projectKey);return current?.generation===authority.generation&&current.authorityEpoch===authority.authorityEpoch}function isHydrationScopeCurrent(scope){return isHydrationAuthorityCurrent(scope)}function nextSessionHydrationStamp(projectKey){return currentHydrationGeneration(projectKey)+1}function getRehydrationCache(projectKey){let entry=rehydrationCaches.get(projectKey),authority=projectHydrationAuthorities.get(projectKey);if(!entry||!authority||entry.authorityEpoch!==authority.authorityEpoch)return;return entry.cache}function setRehydrationCache(projectKey,cache2,authority){let cacheAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(cacheAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(cacheAuthority))return!1;if(!rehydrationCaches.has(projectKey))evictOldest(rehydrationCaches,MAX_TRACKED_PROJECTS);return rehydrationCaches.set(projectKey,{cache:cache2,authorityEpoch:cacheAuthority.authorityEpoch}),!0}function recordHydratedAggregateKeys(projectKey,keys,authority){let aggregateAuthority=authority??captureCurrentHydrationAuthority(projectKey);if(aggregateAuthority.projectKey!==projectKey||!isHydrationAuthorityCurrent(aggregateAuthority))return!1;if(!hydratedAggregateKeys.has(projectKey))evictOldest(hydratedAggregateKeys,MAX_TRACKED_PROJECTS);return hydratedAggregateKeys.set(projectKey,{keys:new Set(keys),authorityEpoch:aggregateAuthority.authorityEpoch}),!0}function hydratedAggregateKeysFor(projectKey,authority){let entry=hydratedAggregateKeys.get(projectKey),current=authority??projectHydrationAuthorities.get(projectKey);if(!entry||!current||entry.authorityEpoch!==current.authorityEpoch)return new Set;return entry.keys}function clearHydrationOwnershipState(){projectHydrationAuthorities.clear(),rehydrationCaches.clear(),hydratedAggregateKeys.clear(),directoryKeyMemo.clear()}var MAX_TRACKED_PROJECTS=32,MAX_DIRECTORY_KEY_MEMO=64,projectHydrationAuthorities,hydrationAuthorityEpoch=0,rehydrationCaches,hydratedAggregateKeys,directoryKeyMemo;var init_hydration_ownership=__esm(()=>{init_canonical_project();init_canonical_root();projectHydrationAuthorities=new Map,rehydrationCaches=new Map,hydratedAggregateKeys=new Map,directoryKeyMemo=new Map});import{existsSync as existsSync52,mkdirSync as mkdirSync32,readFileSync as readFileSync38,writeFileSync as writeFileSync21}from"node:fs";import*as path98 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path98.join(directory,".swarm"),sessionDir=path98.join(swarmDir,"session"),filePath=path98.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync32(sessionDir,{recursive:!0}),writeFileSync21(filePath,`${line}
1276
1276
  `,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=path98.join(directory,".swarm","session",SESSION_START_FILE);if(!existsSync52(filePath))return null;let lines=readFileSync38(filePath,"utf-8").split(`
1277
1277
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{randomUUID as randomUUID12}from"node:crypto";function parseRecordPayload(payload,label){let parsed=JSON.parse(payload);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`Invalid SQLite snapshot ${label} payload`);return parsed}function claimSnapshotSessionOwnership(sessionId,canTakeOver=!1){let existing=localSessionOwners.get(sessionId);if(existing){if(canTakeOver)existing.canTakeOver=!0;return existing.token}let token=randomUUID12();return localSessionOwners.set(sessionId,{token,canTakeOver}),token}function isSnapshotSessionOwnedLocally(sessionId){return localSessionOwners.has(sessionId)}function releaseSnapshotSessionOwnership(sessionId){localSessionOwners.delete(sessionId)}function clearSnapshotSessionOwnerships(){localSessionOwners.clear()}function nextGeneration(directory,namespace,entityKey){return(getCoordinationState(directory,namespace,entityKey)?.generation??0)+1}function writeSnapshotRows(directory,snapshot,options={}){withCoordinationTransaction(directory,()=>{transitionCoordinationState(directory,{namespace:META_NAMESPACE,entityKey:"project",generation:nextGeneration(directory,META_NAMESPACE,"project"),status:"active",payload:JSON.stringify({version:snapshot.version,writtenAt:snapshot.writtenAt,workflowSchema:snapshot.workflowSchema})});for(let[key2,aggregate]of Object.entries(snapshot.toolAggregates))transitionCoordinationState(directory,{namespace:TOOL_NAMESPACE,entityKey:key2,generation:nextGeneration(directory,TOOL_NAMESPACE,key2),status:"active",payload:JSON.stringify(aggregate)});for(let[sessionId,agentName]of Object.entries(snapshot.activeAgent)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,ACTIVE_AGENT_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:ACTIVE_AGENT_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,ACTIVE_AGENT_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(agentName)})}for(let[sessionId,chain]of Object.entries(snapshot.delegationChains)){if(options.onlyLocallyOwnedSessions&&!isSnapshotSessionOwnedLocally(sessionId))continue;if(getCoordinationState(directory,DELEGATION_CHAIN_NAMESPACE,sessionId)?.status==="deleted")continue;transitionCoordinationState(directory,{namespace:DELEGATION_CHAIN_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,DELEGATION_CHAIN_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(chain)})}for(let[sessionId,session]of Object.entries(snapshot.agentSessions)){let localOwner=localSessionOwners.get(sessionId),ownerToken=localOwner?.token;if(options.onlyLocallyOwnedSessions&&!localOwner)continue;let current=getCoordinationState(directory,SESSION_NAMESPACE,sessionId),currentOwner2,deleted=null;try{if(current?.status==="deleted")deleted=JSON.parse(current.payload);else if(current)currentOwner2=JSON.parse(current.payload).ownerToken}catch{continue}if(options.onlyLocallyOwnedSessions&&currentOwner2&&currentOwner2!==ownerToken&&!localOwner?.canTakeOver)continue;if(deleted&&(!ownerToken||deleted.reason!=="stale"||deleted.ownerToken!==ownerToken))continue;let payload={session,...ownerToken?{ownerToken}:{}};transitionCoordinationState(directory,{namespace:SESSION_NAMESPACE,entityKey:sessionId,generation:nextGeneration(directory,SESSION_NAMESPACE,sessionId),status:"active",payload:JSON.stringify(payload)})}})}function importSnapshotRowsOnce(directory,snapshot,sourceDigest,source="session/state.json"){return importCoordinationOnce(directory,{source,sourceDigest,rowCount:Object.keys(snapshot.agentSessions).length,emptyNamespace:META_NAMESPACE},()=>writeSnapshotRows(directory,snapshot))}function readSnapshotRows(directory){if(!projectDbExists(directory))return null;return withCoordinationTransaction(directory,()=>{let meta3=listCoordinationStates(directory,META_NAMESPACE,1)[0];if(!meta3)return null;_snapshotStoreInternals.afterSnapshotMetaRead();let parsedMeta=parseRecordPayload(meta3.payload,"metadata");if(parsedMeta.version!==1&&parsedMeta.version!==2&&parsedMeta.version!==3)throw Error("Unsupported SQLite snapshot version");if(!Number.isFinite(parsedMeta.writtenAt))throw Error("Invalid SQLite snapshot metadata writtenAt");if(parsedMeta.workflowSchema!==void 0&&typeof parsedMeta.workflowSchema!=="string")throw Error("Invalid SQLite snapshot metadata workflowSchema");let snapshot={version:parsedMeta.version,writtenAt:parsedMeta.writtenAt,...parsedMeta.workflowSchema!==void 0&&{workflowSchema:parsedMeta.workflowSchema},toolAggregates:{},activeAgent:{},delegationChains:{},agentSessions:{}};for(let row of listCoordinationStates(directory,TOOL_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS))snapshot.toolAggregates[row.entityKey]=parseRecordPayload(row.payload,"tool aggregate");for(let row of listCoordinationStates(directory,ACTIVE_AGENT_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let agentName=JSON.parse(row.payload);if(typeof agentName!=="string")throw Error("Invalid SQLite snapshot active-agent payload");snapshot.activeAgent[row.entityKey]=agentName}for(let row of listCoordinationStates(directory,DELEGATION_CHAIN_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let chain=JSON.parse(row.payload);if(!Array.isArray(chain))throw Error("Invalid SQLite snapshot delegation-chain payload");snapshot.delegationChains[row.entityKey]=chain}for(let row of listCoordinationStates(directory,SESSION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS)){if(row.status==="deleted")continue;let payload=parseRecordPayload(row.payload,"agent-session");if(!payload.session||typeof payload.session!=="object"||Array.isArray(payload.session)||payload.ownerToken!==void 0&&typeof payload.ownerToken!=="string")throw Error("Invalid SQLite snapshot agent-session payload");snapshot.agentSessions[row.entityKey]=payload.session}return snapshot})}function isSnapshotSessionAuthoritativelyStale(directory,sessionId,staleDurationMs,now=Date.now()){try{if(!projectDbExists(directory)||!sessionId)return!1;let row=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(!row||row.status==="deleted")return!0;let lastToolCallTime=parseRecordPayload(row.payload,"agent-session").session?.lastToolCallTime;if(typeof lastToolCallTime!=="number"||!Number.isFinite(lastToolCallTime))return!1;return now-lastToolCallTime>staleDurationMs}catch{return!1}}function clearSnapshotRows(directory){if(!projectDbExists(directory))return 0;let removed=0;return withCoordinationTransaction(directory,()=>{for(let namespace of SNAPSHOT_NAMESPACES)for(let row of listCoordinationStates(directory,namespace,MAX_COORDINATION_STATE_LIST_ROWS))if(deleteCoordinationState(directory,namespace,row.entityKey,row.revision))removed+=1;deleteCoordinationImports(directory,["session/state.json",SNAPSHOT_PROJECTION_SOURCE])}),removed}function deleteSnapshotSessionRows(directory,sessionId,reason="ended"){if(!projectDbExists(directory)||!sessionId)return 0;let removed=0;return withCoordinationTransaction(directory,()=>{let ownerToken=localSessionOwners.get(sessionId)?.token,sessionRow=getCoordinationState(directory,SESSION_NAMESPACE,sessionId);if(reason==="stale"&&!ownerToken)return;if(sessionRow&&sessionRow.status!=="deleted")try{let persistedOwner=JSON.parse(sessionRow.payload).ownerToken;if(persistedOwner&&persistedOwner!==ownerToken)return}catch{return}for(let namespace of[SESSION_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE]){let row=getCoordinationState(directory,namespace,sessionId);if(!row||row.status==="deleted")continue;if(transitionCoordinationState(directory,{namespace,entityKey:sessionId,expectedRevision:row.revision,generation:row.generation+1,status:"deleted",payload:JSON.stringify({reason,...ownerToken?{ownerToken}:{}})}).outcome==="applied")removed+=1}}),removed}var META_NAMESPACE="session.snapshot.meta",SESSION_NAMESPACE="session.snapshot.agent",TOOL_NAMESPACE="session.snapshot.tool",ACTIVE_AGENT_NAMESPACE="session.snapshot.active-agent",DELEGATION_CHAIN_NAMESPACE="session.snapshot.delegation-chain",SNAPSHOT_PROJECTION_SOURCE="session/state.sqlite-projection.json",SNAPSHOT_NAMESPACES,_snapshotStoreInternals,localSessionOwners;var init_snapshot_store=__esm(()=>{init_coordination_store();init_project_db();SNAPSHOT_NAMESPACES=[META_NAMESPACE,SESSION_NAMESPACE,TOOL_NAMESPACE,ACTIVE_AGENT_NAMESPACE,DELEGATION_CHAIN_NAMESPACE],_snapshotStoreInternals={afterSnapshotMetaRead:()=>{}},localSessionOwners=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve50)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve50(0);return}let count=0;for(let line of stdout.split(`
@@ -2660,7 +2660,7 @@ Flags:
2660
2660
  `))if(line.trim())n++;return n}catch{return 0}}function resolveUnactionablePathSafe(directory){try{return resolveUnactionablePath(directory)}catch{return null}}function resolveInsightCandidatesPathSafe(directory){try{return resolveInsightCandidatesPath(directory)}catch{return null}}async function countInsightCandidatesPendingDiagnostic(directory){try{if(projectDbExists(directory))return countPendingInsightCandidatesDb(directory);return await safeJsonlCount(resolveInsightCandidatesPathSafe(directory))}catch{return 0}}async function checkKnowledgeHealth(directory){let debug;try{debug=await computeKnowledgeDebug(directory)}catch{return{name:"Knowledge health",status:"⚠️",detail:"Could not compute knowledge diagnostics"}}let{status_breakdown:sb,learning:lr,cohort:co,hive:hv,curation:cu}=debug,cohortTag=co.linked?` | cohort[linked id=${co.link_id}${co.cohort_id?` cohort=${co.cohort_id}`:""}${co.identity_source?` via=${co.identity_source}`:""}${co.degraded?" DEGRADED":""}${co.local_orphaned?" local-orphan":""}${co.generation!==null?` gen=${co.generation}`:""}]`:" | cohort[local]",hiveTag=hv.entries_with_lineage>0||hv.override_promotions>0?` | hive[lineage=${hv.entries_with_lineage} overrides=${hv.override_promotions}]`:" | hive[local]",scanPart=cu.scan_completed?`scan[gen=${cu.scan_generation} complete]`:`scan[gen=${cu.scan_generation} remaining=${cu.scan_remaining_estimate}]`,fpPart=cu.config_fingerprint_match===null?"fp=n/a":cu.config_fingerprint_match?"fp=match":"fp=MISMATCH",provenanceTotal=cu.entries_with_provenance+cu.entries_unknown_owner,curationTag=` | curation[${scanPart} ${fpPart} provenance=${cu.entries_with_provenance}/${provenanceTotal} proposals=${cu.pending_proposals}]`,summary=`active=${sb.active} archived=${sb.archived} quarantined=${sb.quarantined} rejected=${sb.rejected} | events=${debug.event_count} (retrieved/7d=${debug.retrieval_events_7d}) | learning[enforce=${lr.enforced_directives} escalated=${lr.escalated_directives} synonyms=${lr.synonym_pairs} unactionable=${lr.unactionable_queue_depth} insights_pending=${lr.insight_candidates_pending}] | schema=${JSON.stringify(debug.schema_versions)}`+cohortTag+hiveTag+curationTag,warnings=[];if(co.linked&&co.degraded)warnings.push(`cohort identity is degraded (via ${co.identity_source}): shared store is machine-local, not portable across machines`);if(co.linked&&co.local_orphaned)warnings.push("local .swarm/knowledge.jsonl is orphaned by the link store (benign; resolver ignores it)");if(lr.unactionable_queue_depth>UNACTIONABLE_BACKLOG_WARN)warnings.push(`${lr.unactionable_queue_depth} lessons stuck in the unactionable queue (curator may not be draining)`);if(lr.insight_candidates_pending>INSIGHT_BACKLOG_WARN)warnings.push(`${lr.insight_candidates_pending} micro-reflection insight candidates pending (curator may not be folding them in)`);if(debug.corrupt_line_count>0)warnings.push(`${debug.corrupt_line_count} corrupt JSONL line(s) (raw=${debug.raw_entry_count} vs normalized=${debug.normalized_entry_count})`);if(debug.entries_missing_v2_counters>0)warnings.push(`${debug.entries_missing_v2_counters} entr(y/ies) missing v2 counters (normalized on read)`);if(debug.cache_status==="stale")warnings.push("stale plugin cache — run `bunx opencode-swarm update` (knowledge tools may be running old code)");if(hv.override_promotions>0){let sample=hv.override_entries[0],gates=sample?.override_failed_gates?.join(",")??"?";warnings.push(`${hv.override_promotions} hive entr(y/ies) promoted via --force override (failed gates: ${gates}${sample?.reason?`; reason: "${sample.reason.slice(0,60)}"`:""})`)}if(cu.config_fingerprint_match===!1)warnings.push("cohort config fingerprint mismatch: this worktree curates with different knowledge semantics than the cohort — align knowledge config across linked worktrees");if(cu.pending_proposals>0)warnings.push(`${cu.pending_proposals} pending curation proposal(s) awaiting confirmation (blocked destructive actions recorded in curation-proposals.jsonl)`);if(warnings.length>0)return{name:"Knowledge health",status:"⚠️",detail:`${summary} — ${warnings.join("; ")}`};return{name:"Knowledge health",status:"✅",detail:summary}}var version3,SEVEN_DAYS_MS2=604800000,UNACTIONABLE_BACKLOG_WARN=100,INSIGHT_BACKLOG_WARN=50;var init_knowledge_diagnostics=__esm(()=>{init_package();init_insight_candidate_store();init_project_db();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_curation_policy();init_memory_link();init_redaction();init_caps();init_jsonl_cap();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process8 from"node:child_process";import{existsSync as existsSync93,readdirSync as readdirSync26,readFileSync as readFileSync68,statSync as statSync58}from"node:fs";import*as path180 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";function checkSwarmDb(directory){let runtime=process.versions.bun===void 0?"node":"bun",runtimeVersion=process.versions.bun??process.versions.node??"unknown",snapshot=getSwarmDbHealthSnapshot(directory);switch(snapshot.kind){case"absent":return{name:"swarm.db",status:"✅",detail:`not created yet (driver: ${runtime} ${runtimeVersion})`};case"too_large":return{name:"swarm.db",status:"⚠️",detail:`${Math.round(snapshot.sizeBytes/1048576)} MiB exceeds the ${Math.round(SWARM_DB_QUICK_CHECK_MAX_BYTES2/1048576)} MiB inline quick_check cap — run an external integrity check (driver: ${runtime} ${runtimeVersion})`};case"error":return{name:"swarm.db",status:"❌",detail:`unavailable (${snapshot.category}): ${snapshot.message}`};case"open":{let markerNote=snapshot.staleMarker?", stale db-migration-failure.json marker present":"",detail=`quick_check ${snapshot.quickCheck}; ${snapshot.journalMode} mode, ${snapshot.pageCount} pages, ${snapshot.migrationFailures} recorded migration failure(s)${markerNote}; driver: ${runtime} ${runtimeVersion}`;if(snapshot.quickCheck!=="ok")return{name:"swarm.db",status:"❌",detail};if(snapshot.migrationFailures>0||snapshot.staleMarker)return{name:"swarm.db",status:"⚠️",detail};return{name:"swarm.db",status:"✅",detail}}}}function validateTaskDag(plan){let allTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)allTaskIds.add(task.id);let missingDeps=[];for(let phase of plan.phases)for(let task of phase.tasks)for(let dep of task.depends)if(!allTaskIds.has(dep))missingDeps.push(`${task.id} depends on missing ${dep}`);return{valid:missingDeps.length===0,missingDeps}}async function checkEvidenceCompleteness(directory,plan){let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length>0){let evidenceTaskIds=new Set(await listEvidenceTaskIds(directory)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(directory,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}if(missingEvidence.length===0)return{name:"Evidence",status:"✅",detail:`All ${completedTaskIds.length} completed tasks have evidence`};else return{name:"Evidence",status:"❌",detail:`${missingEvidence.length} completed task(s) missing evidence: ${missingEvidence.join(", ")}`}}return{name:"Evidence",status:"✅",detail:"No completed tasks yet"}}async function checkSwarmIdentity(plan){let activeSwarmId=process.env.OPENCODE_SWARM_ID;if(plan&&!activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:"Plan exists but OPENCODE_SWARM_ID not set in environment"};if(!plan&&!activeSwarmId)return{name:"Swarm Identity",status:"✅",detail:"No conflict detected"};if(!plan)return{name:"Swarm Identity",status:"✅",detail:`No plan, but OPENCODE_SWARM_ID is '${activeSwarmId}'`};if(plan&&plan.swarm!==activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:`Swarm identity mismatch: plan says '${plan.swarm}', active is '${activeSwarmId}'`};return{name:"Swarm Identity",status:"✅",detail:`Swarm identity consistent: '${plan.swarm}'`}}async function checkPhaseBoundaries(plan){if(!plan)return{name:"Phase Boundaries",status:"✅",detail:"No plan to validate"};let mismatches=[];for(let phase of plan.phases)for(let task of phase.tasks){let taskPhaseNum=parseInt(task.id.split(".")[0],10);if(Number.isNaN(taskPhaseNum))mismatches.push(`Task ${task.id} has invalid phase number`);else if(taskPhaseNum!==phase.id)mismatches.push(`Task ${task.id} found under Phase ${phase.id}`)}if(mismatches.length===0)return{name:"Phase Boundaries",status:"✅",detail:"All tasks correctly aligned to phases"};return{name:"Phase Boundaries",status:"❌",detail:mismatches.join("; ")}}async function checkOrphanedEvidence(directory,plan){if(!plan)return{name:"Orphaned Evidence",status:"✅",detail:"No plan to cross-reference"};let planTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)planTaskIds.add(task.id);try{let orphaned=(await listEvidenceTaskIds(directory)).filter((id)=>!planTaskIds.has(id)&&!/^retro-/.test(id));if(orphaned.length===0)return{name:"Orphaned Evidence",status:"✅",detail:"All evidence entries reference valid plan tasks"};return{name:"Orphaned Evidence",status:"❌",detail:`Evidence for [${orphaned.join(", ")}] not in plan`}}catch{return{name:"Orphaned Evidence",status:"❌",detail:"Could not read evidence directory"}}}async function checkPlanSync(directory,plan){if(!plan)return{name:"Plan Sync",status:"✅",detail:"No plan.json present"};try{let jsonTaskCount=0;for(let phase of plan.phases)jsonTaskCount+=phase.tasks.length;let planMdContent=await readSwarmFileAsync(directory,"plan.md");if(!planMdContent)return{name:"Plan Sync",status:"✅",detail:"plan.md not present"};let mdTaskCount=(planMdContent.match(/^- \[[ xX~]/gm)||[]).length;if(jsonTaskCount===mdTaskCount)return{name:"Plan Sync",status:"✅",detail:`plan.json and plan.md both have ${jsonTaskCount} tasks`};return{name:"Plan Sync",status:"❌",detail:`plan.json: ${jsonTaskCount} tasks, plan.md: ${mdTaskCount} — run /swarm sync-plan`}}catch{return{name:"Plan Sync",status:"❌",detail:"Could not compare plan files"}}}async function checkConfigBackups(directory){try{let backupCount=readdirSync26(directory).filter((f)=>/\.opencode-swarm\.yaml\.bak/.test(f)).length;if(backupCount<=5)return{name:"Config Backups",status:"✅",detail:`${backupCount} backup file(s) — within acceptable range`};if(backupCount<=19)return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — consider cleanup`};return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — cleanup required`}}catch{return{name:"Config Backups",status:"✅",detail:"Could not check backup files"}}}function isSpawnTimeoutLike(err){if(typeof err!=="object"||err===null)return!1;let e=err;return e.killed===!0||e.signal==="SIGKILL"||e.signal==="SIGTERM"||e.code==="ETIMEDOUT"}async function checkGitRepository(directory){try{if(!existsSync93(directory)||!statSync58(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};let gitExecutable=await resolveGitExecutableAsync();return _internals143.execFileSync(gitExecutable,["rev-parse","--git-dir"],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:GIT_REPOSITORY_CHECK_TIMEOUT_MS,killSignal:"SIGKILL",maxBuffer:GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),{name:"Git Repository",status:"✅",detail:"Git repository detected"}}catch(err){if(isSpawnTimeoutLike(err))return{name:"Git Repository",status:"⬜",detail:`git rev-parse did not answer within ${GIT_REPOSITORY_CHECK_TIMEOUT_MS} ms — git state unknown`};return{name:"Git Repository",status:"❌",detail:"Not a git repository — version control recommended"}}}async function checkSpecStaleness(directory,plan){let specContent=readEffectiveSpecSync(directory)?.content??null;if(!specContent)return{name:"Spec Staleness",status:"✅",detail:"No effective spec present"};if(!plan)return{name:"Spec Staleness",status:"✅",detail:"No plan to compare spec against"};let titleMatch=specContent.match(/^#\s+(.+)$/m);if(!titleMatch)return{name:"Spec Staleness",status:"✅",detail:"Spec title not detectable"};let specTitle=titleMatch[1].trim(),planTitle=plan.title.trim();if(specTitle.toLowerCase()===planTitle.toLowerCase())return{name:"Spec Staleness",status:"✅",detail:"Spec and plan titles are aligned"};return{name:"Spec Staleness",status:"❌",detail:`Spec/plan title mismatch: spec says '${specTitle}', plan says '${planTitle}'`}}async function checkConfigParseability(directory){let configPath=path180.join(directory,".opencode/opencode-swarm.json");if(!existsSync93(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync68(configPath,"utf-8");return JSON.parse(content),{name:"Config Parseability",status:"✅",detail:"Project config is valid JSON"}}catch(err){return{name:"Config Parseability",status:"❌",detail:`Project config at .opencode/opencode-swarm.json is not valid JSON: ${err instanceof Error?err.message:"Unknown error"}`}}}function resolveGrammarDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/services"),isCliBundle=normalized.endsWith("/cli");return isSource||isCliBundle?path180.join(thisDir,"..","lang","grammars"):path180.join(thisDir,"lang","grammars")}async function checkGrammarWasmFiles(){let grammarFiles=["tree-sitter-javascript.wasm","tree-sitter-typescript.wasm","tree-sitter-tsx.wasm","tree-sitter-python.wasm","tree-sitter-go.wasm","tree-sitter-rust.wasm","tree-sitter-cpp.wasm","tree-sitter-c-sharp.wasm","tree-sitter-css.wasm","tree-sitter-bash.wasm","tree-sitter-ruby.wasm","tree-sitter-php.wasm","tree-sitter-java.wasm","tree-sitter-kotlin.wasm","tree-sitter-swift.wasm","tree-sitter-dart.wasm","tree-sitter-powershell.wasm","tree-sitter-ini.wasm","tree-sitter-regex.wasm"],thisDir=path180.dirname(fileURLToPath5(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync93(path180.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync93(path180.join(grammarDir,file3)))missing.push(file3);if(missing.length===0)return{name:"Grammar WASM Files",status:"✅",detail:`Core runtime + all ${grammarFiles.length} grammar WASM files present`};return{name:"Grammar WASM Files",status:"❌",detail:`${missing.length} WASM file(s) missing: ${missing.join(", ")}`}}async function checkCheckpointManifest(directory){let manifestPath2=path180.join(directory,".swarm/checkpoints.json");if(!existsSync93(manifestPath2))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync68(manifestPath2,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json missing 'checkpoints' array"};let invalidCount=0;for(let cp2 of parsed.checkpoints)if(typeof cp2.label!=="string"||typeof cp2.sha!=="string"||typeof cp2.timestamp!=="string")invalidCount++;if(invalidCount>0)return{name:"Checkpoint Manifest",status:"❌",detail:`${invalidCount} checkpoint(s) have invalid structure (missing label/sha/timestamp)`};return{name:"Checkpoint Manifest",status:"✅",detail:`Checkpoint manifest valid — ${parsed.checkpoints.length} checkpoint(s)`}}catch(err){if(err instanceof SyntaxError)return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json is not valid JSON"};return{name:"Checkpoint Manifest",status:"❌",detail:"Could not read checkpoint manifest"}}}async function checkEventStreamIntegrity(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
2661
2661
  `).filter((line)=>line.trim()!==""),malformedCount=0;for(let line of lines)try{JSON.parse(line)}catch{malformedCount++}let coverageNote=window2.coverage==="truncated"?" (retained window — compacted history excluded)":"";if(malformedCount===0)return{name:"Event Stream",status:"✅",detail:`events.jsonl is valid — ${lines.length} event(s)${coverageNote}`};return{name:"Event Stream",status:"❌",detail:`events.jsonl has ${malformedCount} malformed line(s) — possible data corruption`}}catch{return{name:"Event Stream",status:"❌",detail:"Could not read events.jsonl"}}}async function checkSteeringDirectives(directory){if(getCoreEventCoverage(directory)==="empty")return{name:"Steering Directives",status:"✅",detail:"No events.jsonl — no steering directives to check"};try{let window2=readCoreEvents(directory),lines=window2.text.split(`
2662
2662
  `).filter((line)=>line.trim()!==""),directivesIssued=[],consumedIds=new Set;for(let line of lines)try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directivesIssued.push(parsed.directiveId);if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}let unconsumed=directivesIssued.filter((id)=>!consumedIds.has(id));if(unconsumed.length===0)return{name:"Steering Directives",status:"✅",detail:`All steering directives acknowledged (or none issued)${window2.coverage==="truncated"?" (within the retained event window)":""}`};return{name:"Steering Directives",status:"❌",detail:`${unconsumed.length} steering directive(s) not yet acknowledged`}}catch{return{name:"Steering Directives",status:"❌",detail:"Could not read events.jsonl"}}}async function checkLearningHealth(directory){try{let snapshot=await readLearningHealth(directory);if(snapshot.activeAlarms.length===0)return{name:"Learning health",status:"✅",detail:`No active alarms (${snapshot.totalTransitions} transitions recorded)`};let detail=snapshot.activeAlarms.map((alarm)=>{let ageMinutes=Math.floor(alarm.ageMs/60000);return`${alarm.severity} ${alarm.alarm} [${alarm.scopeClass} ${alarm.scopeRef}] age ${ageMinutes}m coverage ${alarm.coverageFacts}`}).join("; ");return{name:"Learning health",status:"⚠️",detail:`${snapshot.activeAlarms.length} active alarm(s): ${detail}`}}catch{return{name:"Learning health",status:"⬜",detail:"Learning-health artifact unreadable (fail-open)"}}}async function checkCurator(directory){try{if(!loadPluginConfig(directory).curator?.enabled)return{name:"Curator",status:"✅",detail:"Disabled (enable via curator.enabled)"};let summaryPath=path180.join(directory,".swarm/curator-summary.json");if(!existsSync93(summaryPath))return{name:"Curator",status:"✅",detail:"Enabled, no summary yet (waiting for first phase)"};try{let content=readFileSync68(summaryPath,"utf-8"),parsed=JSON.parse(content);if(typeof parsed.schema_version!=="number"||parsed.schema_version!==1)return{name:"Curator",status:"❌",detail:`curator-summary.json has invalid schema_version (expected 1, got ${JSON.stringify(parsed.schema_version)})`};let phaseInfo=parsed.last_phase_covered!==void 0?`phase ${parsed.last_phase_covered}`:"unknown phase",timeInfo=parsed.last_updated?`, updated ${parsed.last_updated}`:"";return{name:"Curator",status:"✅",detail:`Summary present — covering ${phaseInfo}${timeInfo}`}}catch(err){return{name:"Curator",status:"❌",detail:`curator-summary.json is corrupt or invalid: ${err instanceof Error?err.message:"Unknown error"}`}}}catch(err){return{name:"Curator",status:"❌",detail:`Could not check curator state: ${err instanceof Error?err.message:"Unknown error"}`}}}async function getSandboxStatus(sessionID){try{let capability=await _internals143.detectSandboxCapability(),mechanism=capability.mechanism??"none",legacyDimension=capability.status==="enabled"?"weak":"none",filesystem=capability.filesystem??legacyDimension,network=capability.network??legacyDimension,processBoundary=capability.process??legacyDimension,effective=capability.effective??legacyDimension,dimensions=`fs=${filesystem} network=${network} process=${processBoundary} effective=${effective}`,reasons=(capability.reasons??[]).join("; "),skipSummary=getSandboxSkipSummary(sessionID),skipDetail=skipSummary.count>0?` | observed skips=${skipSummary.count}: ${skipSummary.reasons.join("; ")}`:"",executor=await _internals143.getSandboxExecutor(),hasExecutor=executor!==null,downgradeReason=executor?.probeResult?.error??executor?.disabledReason??null,downgradeDetail=downgradeReason!==null&&downgradeReason!==void 0?` | downgrade reason: ${sanitizeDiagnosticText(downgradeReason,200)}`:"";if(hasExecutor){let executorStrength=executor?.strength,strength=executorStrength==="weak"||executorStrength==="advisory"?"advisory":capability.strength??executorStrength??"strong";if(effective!=="real"||strength==="advisory")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Partial boundary: ${reasons}${downgradeDetail}${skipDetail}`};return{name:"Sandbox",status:"✅",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Sandboxing requested dimensions: yes${skipDetail}`}}if(mechanism!=="none")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | ${dimensions} | Available: no | ${reasons}${skipDetail}`};return{name:"Sandbox",status:"⬜",detail:`Mechanism: ${mechanism.toLowerCase()} | Commands not sandboxed`}}catch(error93){return{name:"Sandbox",status:"⬜",detail:`Sandbox status unknown (${error93 instanceof Error?error93.message:"Unknown error"})`}}}async function checkResidueInventory(directory){try{let inventory=await inventorySwarmResidue(directory),s=inventory.summary;if(s.matched===0)return{name:"Atomic-write residue",status:"✅",detail:"No registered temp-grammar residue under .swarm/"};let oldestMin=Math.round(s.oldestAgeMs/60000);return{name:"Atomic-write residue",status:"⚠️",detail:`${s.matched} stale temp file(s) (${s.totalBytes} bytes, oldest ${oldestMin}m old): ${s.eligible} quarantine-eligible, ${s.ambiguous} preserved as recent/active/tracked/ambiguous`+(inventory.gitState==="unknown"?" (git tracked-state unknown — nothing auto-quarantined)":"")+". Run /swarm config doctor for the full inventory, /swarm config doctor --quarantine-residue to act."}}catch(err){return{name:"Atomic-write residue",status:"⬜",detail:`Inventory unavailable: ${err instanceof Error?err.message:String(err)}`}}}async function getDiagnoseData(directory,sessionID){let checks5=[],versionCache=readVersionCache(),versionDetail=version4,versionStatus="✅";if(versionCache?.npmLatest){let ageMs=Date.now()-versionCache.checkedAt,ageMin=Math.max(0,Math.round(ageMs/60000));if(compareVersions(versionCache.npmLatest,version4)>0)versionStatus="⚠️",versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago) `+"— run `bunx opencode-swarm update` to refresh";else versionDetail=`${version4} (npm latest: ${versionCache.npmLatest}, checked ${ageMin}m ago)`}checks5.push({name:"Version",status:versionStatus,detail:versionDetail}),checks5.push(checkSwarmDb(directory));let plan=await loadPlanJsonOnly(directory);if(plan){if(checks5.push({name:"plan.json",status:"✅",detail:"Valid schema (v1.0.0)"}),plan.migration_status==="migrated")checks5.push({name:"Migration",status:"✅",detail:"Plan was migrated from legacy plan.md"});else if(plan.migration_status==="migration_failed")checks5.push({name:"Migration",status:"❌",detail:"Migration from plan.md failed — review manually"});let dagResult=validateTaskDag(plan);if(dagResult.valid)checks5.push({name:"Task DAG",status:"✅",detail:"All dependencies resolved"});else checks5.push({name:"Task DAG",status:"❌",detail:`Missing dependencies: ${dagResult.missingDeps.join(", ")}`});let evidenceCheck=await checkEvidenceCompleteness(directory,plan);checks5.push(evidenceCheck)}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(planContent){let hasPhases=/^## Phase \d+/m.test(planContent),hasTasks=/^- \[[ x]\]/m.test(planContent);if(hasPhases&&hasTasks)checks5.push({name:"plan.md",status:"✅",detail:"Found with valid phase structure"});else checks5.push({name:"plan.md",status:"❌",detail:"Found but missing phase/task structure"})}else checks5.push({name:"plan.md",status:"❌",detail:"Not found"})}try{let{states:settlementStates,truncated}=await listCoderSettlementWalStates(directory),truncationNote=truncated?" MORE settlement WALs exist than the scan cap (200) — older ones are not shown.":"",settlementStatuses=[];for(let entry of settlementStates){let workflow=null;try{workflow=getTaskWorkflowSnapshot(await readTaskEvidence(directory,entry.taskId))}catch{workflow=null}settlementStatuses.push(classifySettlementWalState(entry,workflow))}let wedgeScan=await scanWedgedStageA(directory),wedgeStatuses=wedgeScan.results.filter((status2)=>status2.category==="live_wedge"||status2.category==="settlement_wedge"),knownTaskIds=new Set([...settlementStates.map((entry)=>entry.taskId),...wedgeScan.results.map((status2)=>status2.taskId)]),missingStatuses=[];if(!truncated&&!wedgeScan.truncated){let planTaskIds=(plan?.phases??[]).flatMap((phase)=>phase.tasks.map((task)=>task.id)).slice(0,200);for(let taskId of planTaskIds){if(knownTaskIds.has(taskId))continue;missingStatuses.push(classifyEvidenceRecoveryTask(taskId,null,null))}}let nonHealthy=[...settlementStatuses.filter((s)=>s.category!=="healthy"),...wedgeStatuses],missingLines=missingStatuses.map(renderTaskRecoveryLine).filter(Boolean),wedgeTaskIds=new Set(wedgeStatuses.map((s)=>s.taskId)),healthyCount=settlementStatuses.filter((s)=>s.category==="healthy"&&!wedgeTaskIds.has(s.taskId)).length;if(nonHealthy.length===0&&!truncated)checks5.push({name:"Coder Settlements",status:"✅",detail:`${missingLines.length>0?`${missingLines.join("; ")}. `:""}${settlementStates.length===0?"No coder settlement WALs":`${settlementStates.length} settlement(s) all in terminal state`}`});else if(nonHealthy.length===0&&truncated)checks5.push({name:"Coder Settlements",status:"⚠️",detail:`All shown settlements are terminal, but the scan was truncated.${truncationNote} ${renderRecoveryInvocationQuickForms()}`});else{let lines=[...nonHealthy.map(renderTaskRecoveryLine).filter(Boolean),...missingLines];checks5.push({name:"Coder Settlements",status:"⚠️",detail:`${lines.join("; ")}${healthyCount>0?`; ${healthyCount} healthy settlement(s)`:""}. Categories: missing/stale/ambiguous/corrupt/live_wedge/settlement_wedge — stale settlements block dispatches with CODER_DISPATCH_IN_PROGRESS. ${renderRecoveryInvocationQuickForms()}${truncationNote}`})}}catch(error93){checks5.push({name:"Coder Settlements",status:"⚠️",detail:`could not inspect coder settlements: ${error93 instanceof Error?error93.message:String(error93)}`})}if(await readSwarmFileAsync(directory,"context.md"))checks5.push({name:"context.md",status:"✅",detail:"Found"});else checks5.push({name:"context.md",status:"❌",detail:"Not found"});try{if(loadPluginConfig(directory))checks5.push({name:"Plugin config",status:"✅",detail:"Valid configuration loaded"});else checks5.push({name:"Plugin config",status:"✅",detail:"Using defaults (no custom config)"})}catch{checks5.push({name:"Plugin config",status:"❌",detail:"Invalid configuration"})}checks5.push(await checkSwarmIdentity(plan)),checks5.push(await checkPhaseBoundaries(plan)),checks5.push(await checkOrphanedEvidence(directory,plan)),checks5.push(await checkPlanSync(directory,plan)),checks5.push(await checkConfigBackups(directory)),checks5.push(await checkGitRepository(directory)),checks5.push(await getSandboxStatus(sessionID)),checks5.push(await checkSpecStaleness(directory,plan)),checks5.push(await checkConfigParseability(directory)),checks5.push(await checkGrammarWasmFiles()),checks5.push(await checkCheckpointManifest(directory)),checks5.push(await checkEventStreamIntegrity(directory)),checks5.push(await checkSteeringDirectives(directory)),checks5.push(await checkCurator(directory)),checks5.push(await checkKnowledgeHealth(directory)),checks5.push(await checkLearningHealth(directory)),checks5.push(await checkResidueInventory(directory));try{let evidenceDir=path180.join(directory,".swarm","evidence"),snapshotFiles=existsSync93(evidenceDir)?readdirSync26(evidenceDir).filter((f)=>f.startsWith("agent-tools-")&&f.endsWith(".json")):[];if(snapshotFiles.length>0){let latest=snapshotFiles.sort().pop();checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:`${snapshotFiles.length} snapshot(s) found — latest: ${latest}`})}else checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}catch{checks5.push({name:"Agent Tool Snapshots",status:"✅",detail:"No snapshots yet (snapshots written on next session start)"})}if(getDeferredWarnings().length>0)checks5.push({name:"Deferred Warnings",status:"⚠️",detail:`${getDeferredWarnings().length} warning(s) deferred from init — see the Deferred Warnings section below (or set OPENCODE_SWARM_DEBUG=1 for full detail)`});let cachePaths=[...getPluginCachePaths(),...discoverVersionPinnedCachePaths()],cacheRows=[];for(let cachePath of cachePaths)try{if(!existsSync93(cachePath)){cacheRows.push(`⬜ ${cachePath} — absent`);continue}let packageRoot=resolveCachePackageRoot(cachePath),cacheLabel=packageRoot===cachePath?cachePath:`${cachePath} -> ${packageRoot}`,missingGrammarAssets=REQUIRED_CACHE_GRAMMAR_ASSETS.filter((file3)=>!existsSync93(path180.join(packageRoot,"dist","lang","grammars",file3))),pkgJsonPath=path180.join(packageRoot,"package.json");try{let raw=readFileSync68(pkgJsonPath,"utf-8"),parsed=JSON.parse(raw),installedVersion=typeof parsed.version==="string"?parsed.version:"?";if(missingGrammarAssets.length>0){cacheRows.push(`⚠️ ${cacheLabel} — v${installedVersion}, missing grammar assets: ${missingGrammarAssets.join(", ")}; run \`bunx opencode-swarm update\` and restart OpenCode`);continue}cacheRows.push(`✅ ${cacheLabel} — v${installedVersion}`)}catch{cacheRows.push(`⚠️ ${cacheLabel} — present (package.json unreadable)`)}}catch{cacheRows.push(`⚠️ ${cachePath} — status unknown (read error)`)}let hasCacheEntry=cacheRows.some((r)=>r.startsWith("✅")),cacheStatus2=cacheRows.some((r)=>r.startsWith("⚠️"))?"⚠️":hasCacheEntry?"✅":"⬜";if(checks5.push({name:"Plugin Caches",status:cacheStatus2,detail:cacheRows.join(" | ")}),!sessionID)checks5.push({name:"Invocation recovery",status:"⬜",detail:"Session unavailable; scoped circuit and model status omitted"});else{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0,circuits=invocationID>0?listBlockingActionCircuitsForInvocation(sessionID,invocationID):[],circuitRows=[...circuits].sort((a,b)=>b.count-a.count||a.actionDigest.localeCompare(b.actionDigest)).slice(0,3).map((entry)=>`${entry.circuitKind} digest ${entry.actionDigest} (count ${entry.count}) → /swarm guardrail reset ${entry.actionDigest} --invocation ${invocationID}`);if(circuits.length>3)circuitRows.push(`+ ${circuits.length-3} more`);circuitRows.push("fresh re-delegation or a full plugin restart also resets (circuits are in-memory, TTL 30m)"),checks5.push({name:"Invocation circuits",status:circuits.length>0?"⚠️":"✅",detail:circuits.length>0?`${circuits.length} exact-action circuit(s) open for invocation ${invocationID}: ${circuitRows.join(" | ")}`:`No exact-action circuits open${invocationID>0?` for invocation ${invocationID}`:""}`});let selections=getTaskModelRoutingStateSnapshot().scopedSelections.filter((entry)=>entry.key.sessionID===sessionID);checks5.push({name:"Model fallback scope",status:selections.length>0?"⚠️":"✅",detail:selections.length>0?`${selections.length} scoped selection(s) active; highest fallback index ${Math.max(...selections.map((entry)=>entry.fallbackIndex))}`:"No scoped model override is active"});let fullAuto=loadFullAutoRunState(directory,sessionID);checks5.push({name:"Full-Auto recovery",status:fullAuto?.status==="paused"?"⚠️":"✅",detail:fullAuto?`status=${fullAuto.status}; recovery_probe=${fullAuto.lastRecoveryProbe?.outcome??"none"}`:"No durable Full-Auto run state for this session"})}let passCount=checks5.filter((c)=>c.status==="✅"||c.status==="⬜").length,totalCount=checks5.length;return{checks:checks5,passCount,totalCount,allPassed:passCount===totalCount,deferredWarnings:getDeferredWarnings()}}function formatDiagnoseMarkdown(diagnose){let lines=["## Swarm Health Check","",...diagnose.checks.map((c)=>`- ${c.status} **${c.name}**: ${c.detail}`),"",`**Result**: ${diagnose.allPassed?"✅ All checks passed":`⚠️ ${diagnose.passCount}/${diagnose.totalCount} checks passed`}`];if(diagnose.deferredWarnings.length>0){lines.push(""),lines.push("## Deferred Warnings"),lines.push("");for(let warning of diagnose.deferredWarnings)lines.push(`- ${warning}`)}return lines.join(`
2663
- `)}async function handleDiagnoseCommand(directory,_args,sessionID){let diagnoseData=await getDiagnoseData(directory,sessionID);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals143,SWARM_DB_QUICK_CHECK_MAX_BYTES2=67108864,GIT_REPOSITORY_CHECK_TIMEOUT_MS=5000,GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES=65536;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_health();init_core_events();init_gate_bridge();init_manager2();init_action_circuit();init_state3();init_gate_evidence();init_learning_health();init_utils2();init_task_model_routing();init_manager();init_capability_probe();init_executor();init_skip_state();init_path_identity();init_effective_spec();init_state2();init_git_executable();init_coder_settlement();init_recovery_invocation();init_stage_a_repair();init_task_recovery_status();init_knowledge_diagnostics();init_swarm_residue();init_version_check();init_warning_buffer();({version:version4}=package_default),sandboxCapabilityProbe=new SandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS=["tree-sitter.wasm","tree-sitter-javascript.wasm","tree-sitter-typescript.wasm"],_internals143={detectSandboxCapability:()=>sandboxCapabilityProbe.detect(),getSandboxExecutor:getExecutor,execFileSync:(...args2)=>child_process8.execFileSync(...args2)}});var init_diagnose=__esm(()=>{init_diagnose_service()});var exports_config_doctor={};__export(exports_config_doctor,{writeDoctorArtifact:()=>writeDoctorArtifact,writeBackupArtifact:()=>writeBackupArtifact,shouldRunOnStartup:()=>shouldRunOnStartup,runConfigDoctorWithFixes:()=>runConfigDoctorWithFixes,runConfigDoctor:()=>runConfigDoctor,restoreFromBackup:()=>restoreFromBackup,resolvePlanParallelizationFlag:()=>resolvePlanParallelizationFlag,removeStraySwarmDir:()=>removeStraySwarmDir,readDoctorArtifact:()=>readDoctorArtifact,getConfigPaths:()=>getConfigPaths,detectStraySwarmDirs:()=>detectStraySwarmDirs,createConfigBackup:()=>createConfigBackup,collectLeanTurboGateSatisfiabilityFindings:()=>collectLeanTurboGateSatisfiabilityFindings,applySafeAutoFixes:()=>applySafeAutoFixes,_internals:()=>_internals144,LEAN_TURBO_GATE_PRODUCERS:()=>LEAN_TURBO_GATE_PRODUCERS,DEFAULT_FLIPS:()=>DEFAULT_FLIPS,CURRENT_CONFIG_FORMAT_VERSION:()=>CURRENT_CONFIG_FORMAT_VERSION});import*as crypto9 from"node:crypto";import*as fs97 from"node:fs";import*as os24 from"node:os";import*as path181 from"node:path";function levenshteinDistance(a,b){let al=a.length,bl=b.length,matrix=[];for(let i=0;i<=al;i++)matrix[i]=[i];for(let j=0;j<=bl;j++)matrix[0][j]=j;for(let i=1;i<=al;i++)for(let j=1;j<=bl;j++){let cost=a[i-1]===b[j-1]?0:1;matrix[i][j]=Math.min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost)}return matrix[al][bl]}function emitObjectTypeMismatch(key2,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key2}-type`,title:`Invalid ${key2} type`,description:`"${key2}" must be an object, got ${typeof value}`,severity:"error",path:key2,currentValue:value,autoFixable:!1})}function isPlainObject5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectRawCouncilPolicyFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.council===void 0)continue;if(!isPlainObject5(raw.council))continue;let council=raw.council;if("parallelTimeoutMs"in council)findings.push({id:"council-parallel-timeout-deprecated",title:"Deprecated and inert: council.parallelTimeoutMs",description:'Config field "council.parallelTimeoutMs" (in '+configPath+") is deprecated and inert: no runtime consumer exists and no timeout is enforced. It is accepted only for parse compatibility. Remove the key — dispatch timeouts are governed by the agent host. The field is scheduled for removal in a future release.",severity:"warn",path:"council.parallelTimeoutMs",currentValue:council.parallelTimeoutMs,autoFixable:!1});if("escalateOnMaxRounds"in council)findings.push({id:"council-escalate-inert",title:"Inert: council.escalateOnMaxRounds",description:'Config field "council.escalateOnMaxRounds" (in '+configPath+") is set, but the handler/webhook remains INERT in this release: no handler, webhook, or outbound execution exists or was added (issue #1650). Max-rounds exhaustion emits a durable structured event (.swarm/council/events/max-rounds-exhaustion.jsonl) and a user escalation message instead; the run stays fail-closed. Wiring real outbound escalation requires a separate security review.",severity:"warn",path:"council.escalateOnMaxRounds",currentValue:"[redacted: handler/webhook strings are never echoed]",autoFixable:!1});if(isPlainObject5(council.finalCompletionPolicy)&&council.finalCompletionPolicy.mode==="quorum")findings.push({id:"council-final-quorum-weaker",title:'council.finalCompletionPolicy.mode "quorum" weakens the strict final council',description:"Final-council completion is configured in quorum mode (in "+configPath+"): a bounded minimum of distinct canonical members can accept the project instead of the strict default (all five canonical roles, zero absentees). This is weaker than the strict default. Any change to this policy invalidates previously accepted final-council evidence.",severity:"warn",path:"council.finalCompletionPolicy",currentValue:council.finalCompletionPolicy,autoFixable:!1})}catch{}}return findings}function collectLeanTurboGateSatisfiabilityFindings(config3,registeredToolNames=TOOL_NAME_SET){let findings=[],lean=config3?.turbo?.lean;for(let entry of LEAN_TURBO_GATE_PRODUCERS){let enabled=lean?.[entry.gate]??!0;if(!enabled)continue;if(registeredToolNames.has(entry.producerTool))continue;findings.push({id:`lean-turbo-gate-unsatisfiable-${entry.gate}`,title:`turbo.lean.${entry.gate} gate has no registered producer tool`,description:`turbo.lean.${entry.gate} is enabled (default true), but its evidence producer tool "${entry.producerTool}" is not registered, so the gate that reads ${entry.evidencePathConvention} is structurally unsatisfiable in production and Lean Turbo phase_complete would dead-end. Re-register the producer tool or disable the gate (issue #2470 / #2007).`,severity:"error",path:`turbo.lean.${entry.gate}`,currentValue:enabled,autoFixable:!1})}return findings}function collectRawGatesConfigFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.gates===void 0)continue;if(!isPlainObject5(raw.gates)){findings.push({id:"invalid-gates-config",title:"Invalid gates config",description:`"gates" in ${configPath} must be an object. The loader ignores that section and keeps other valid config sections active.`,severity:"error",path:"gates",currentValue:raw.gates,autoFixable:!1});continue}for(let[sectionName,sectionValue]of Object.entries(raw.gates)){let schema=GateConfigSchema.shape[sectionName];if(!schema){findings.push({id:"unknown-gates-section",title:"Unknown gates config section",description:`Unknown gates section "gates.${sectionName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1});continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[sectionName];if(knownFields&&isPlainObject5(sectionValue)){let knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(sectionValue))if(!knownFieldSet.has(fieldName))findings.push({id:"unknown-gates-key",title:"Unknown gates config key",description:`Unknown gates key "gates.${sectionName}.${fieldName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}.${fieldName}`,currentValue:sectionValue[fieldName],autoFixable:!1})}if(!schema.safeParse(sectionValue).success)findings.push({id:"invalid-gates-section",title:"Invalid gates config section",description:`"gates.${sectionName}" in ${configPath} failed validation. The loader uses defaults for that gate section and keeps other valid config sections active.`,severity:"error",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1})}}catch{}}return findings}function collectRawStrictSectionFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;let seen=new Set;for(let issue3 of parsed.error.issues){if(issue3.code!=="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let keys=issue3.keys??[];for(let key2 of keys){let dotted2=[...issue3.path.map(String),key2].join(".");if(seen.has(dotted2))continue;seen.add(dotted2),findings.push({id:"unknown-config-key",title:"Unknown config key",description:`Unrecognized key "${dotted2}" in ${configPath} is ignored by the loader (the rest of your config is preserved). Fix or remove it.`,severity:"warn",path:dotted2,currentValue:void 0,autoFixable:!1})}}}catch{}}return findings}function getRawValueAtPath(raw,issuePath){let node=raw;for(let seg of issuePath){if(node===null||typeof node!=="object")return;node=node[seg]}return node}function collectRawValueConstraintFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),applyTargetPath=fs97.existsSync(projectConfigPath)?projectConfigPath:userConfigPath,seen=new Set,filesInApplyOrder=applyTargetPath===projectConfigPath?[projectConfigPath,userConfigPath]:[userConfigPath,projectConfigPath];for(let configPath of filesInApplyOrder){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;for(let issue3 of parsed.error.issues){if(issue3.code==="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let dotted2=issue3.path.map(String).join("."),dedupeKey=`${dotted2}|${issue3.code}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);let current=getRawValueAtPath(raw,issue3.path);if(issue3.code==="too_big"&&dotted2.endsWith("fallback_models")&&Array.isArray(current)&&current.length>FALLBACK_MODELS_MAX){let trimmed=current.slice(0,FALLBACK_MODELS_MAX),dropped=current.slice(FALLBACK_MODELS_MAX).map(String),inApplyTarget=configPath===applyTargetPath,drop=`${dropped.length} entr${dropped.length===1?"y":"ies"}`;findings.push({id:"fallback-models-too-many",title:"Too many fallback models",description:`"${dotted2}" in ${configPath} lists ${current.length} models; the maximum is ${FALLBACK_MODELS_MAX}. A config that fails validation is discarded in favor of safe defaults. `+(inApplyTarget?`Run /swarm config doctor --fix to trim to the first ${FALLBACK_MODELS_MAX} (drops ${drop}: ${dropped.join(", ")}), or edit the file yourself.`:`Remove ${drop} from that file (would drop: ${dropped.join(", ")}).`),severity:"error",path:dotted2,currentValue:current,autoFixable:inApplyTarget,proposedFix:{type:"update",path:dotted2,value:trimmed,description:`Trim "${dotted2}" to the first ${FALLBACK_MODELS_MAX} models`,risk:"low",lossy:!0}});continue}findings.push({id:"invalid-config-value",title:"Invalid config value",description:`"${dotted2||"(root)"}" in ${configPath} is invalid: ${issue3.message}. A config that fails validation is discarded in favor of safe defaults until this is fixed.`,severity:"error",path:dotted2,currentValue:current,autoFixable:!1})}}catch{}}return findings}function collectRawAutoReviewCompatibilityFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf8"));if(!isPlainObject5(raw)||!isPlainObject5(raw.auto_review))continue;let autoReview=raw.auto_review;if(autoReview.structured_findings===!1&&isPlainObject5(autoReview.final_review)&&autoReview.final_review.mode==="gate"){findings.push({id:"invalid-auto-review-gate-compatibility",title:"Invalid auto-review gate configuration",description:'auto_review.final_review.mode="gate" requires auto_review.structured_findings=true so gate evidence is machine-verifiable.',severity:"error",path:"auto_review.structured_findings",currentValue:!1,autoFixable:!1});break}}catch{}}return findings}async function resolvePlanParallelizationFlag(directory){let plan=null;try{plan=await _internals144.loadPlanJsonOnly(directory)}catch{return null}if(!plan?.execution_profile)return null;return plan.execution_profile.parallelization_enabled===!0}function emitWorktreeIsolationLayeringAdvisory(config3,findings,planParallelizationEnabled){let worktreePolicy=config3.worktree?.policy??"auto";if(planParallelizationEnabled===!0&&worktreePolicy!=="disabled")findings.push({id:"worktree-isolation-baseline-active",title:"Worktree isolation is already active for standard parallel coders",description:"Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",severity:"warn",path:"worktree.policy",currentValue:worktreePolicy,autoFixable:!1})}function getUserConfigDir3(){return process.env.XDG_CONFIG_HOME||path181.join(os24.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path181.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path181.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto9.createHash("sha256").update(content,"utf-8").digest("hex")}function isValidConfigPath(configPath,directory){let pathParts=configPath.replace(/\\/g,"/").split("/");for(let part of pathParts)if(part===".."||part===""){if(part==="..")return!1}let{userConfigPath,projectConfigPath}=getConfigPaths(directory);try{let resolvedConfig=path181.resolve(configPath),resolvedUser=path181.resolve(userConfigPath),resolvedProject=path181.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs97.existsSync(resolvedConfig)){if(fs97.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs97.writeFileSync(tmpPath,content,"utf-8");try{fs97.renameSync(tmpPath,filePath)}catch{try{fs97.unlinkSync(filePath)}catch{}fs97.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs97.existsSync(projectConfigPath))try{content=fs97.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs97.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs97.readFileSync(userConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] user config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}}if(content===null)return null;return{createdAt:Date.now(),configPath,content,contentHash:computeHash(content)}}function writeBackupArtifact(directory,backup){let swarmDir=path181.join(directory,".swarm");if(!fs97.existsSync(swarmDir))fs97.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path181.join(swarmDir,backupFilename),artifact={createdAt:backup.createdAt,configPath:backup.configPath,contentHash:backup.contentHash,content:backup.content,preview:backup.content.substring(0,500)+(backup.content.length>500?"...":"")};return atomicWriteFileSync(backupPath,JSON.stringify(artifact,null,2)),backupPath}function restoreFromBackup(backupPath,directory){if(!fs97.existsSync(backupPath))return null;let swarmDir=path181.resolve(directory,".swarm"),resolvedBackup=path181.resolve(backupPath);if(!isCanonicalPathWithinRoot(resolvedBackup,swarmDir))return null;try{let artifact=JSON.parse(fs97.readFileSync(backupPath,"utf-8"));if(!artifact.content||!artifact.configPath||!artifact.contentHash)return null;if(!isValidConfigPath(artifact.configPath,directory))return null;let computedHash=computeHash(artifact.content),storedHash=artifact.contentHash;if(!/^\d+$/.test(storedHash)&&computedHash!==storedHash)return null;log("[ConfigDoctor] Warning: restoring from backup with legacy numeric hash (pre-SHA-256). Consider re-backing up.",{});let targetPath=artifact.configPath,targetDir=path181.dirname(targetPath);if(!fs97.existsSync(targetDir))fs97.mkdirSync(targetDir,{recursive:!0});return atomicWriteFileSync(targetPath,artifact.content),targetPath}catch{return null}}function readConfigFromFile(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent=null;if(fs97.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs97.readFileSync(projectConfigPath,"utf-8");else if(fs97.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs97.readFileSync(userConfigPath,"utf-8");if(configContent===null)return null;try{return{config:JSON.parse(configContent),configPath}}catch(error93){return log(`[ConfigDoctor] Failed to parse config file: ${configPath}`,{error:error93 instanceof Error?error93.message:String(error93)}),null}}function validateConfigKey(path182,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path182===depPath&&!depInfo.isDefaultValue(value))findings.push({id:"deprecated-field",title:`Deprecated config field: ${depPath}`,description:`Config field "${depPath}" is deprecated. Replacement: ${depInfo.replacement}.`,severity:"info",path:depPath,currentValue:value,autoFixable:!1});switch(path182){case"agents":{if(value!==void 0)findings.push({id:"deprecated-agents-config",title:"Deprecated agents configuration",description:'The "agents" field is deprecated. Use "swarms" instead for multi-swarm support.',severity:"warn",path:"agents",currentValue:value,autoFixable:!1,proposedFix:{type:"remove",path:"agents",description:"Remove deprecated agents config - use swarms instead",risk:"low"}});break}case"config_format_version":{if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<0)findings.push({id:"type-mismatch",title:`Config field "${path182}" has wrong type`,description:`Expected non-negative integer, got ${typeof value==="number"?Number.isInteger(value)?value:`${value} (non-integer)`:typeof value}`,severity:"error",path:path182,currentValue:value,autoFixable:!1});break}case"preset":{if(value!=="default"&&value!=="conservative")findings.push({id:"type-mismatch",title:`Config field "${path182}" has wrong type`,description:`Expected "default" or "conservative", got ${JSON.stringify(value)}`,severity:"error",path:path182,currentValue:value,autoFixable:!1});break}case"guardrails.enabled":{if(value===!1)findings.push({id:"guardrails-disabled",title:"Guardrails disabled",description:"Guardrails have been explicitly disabled. This removes safety limits.",severity:"error",path:"guardrails.enabled",currentValue:value,autoFixable:!1});break}case"guardrails.profiles":{let profiles=value;if(profiles){let validAgents=new Set(ALL_AGENT_NAMES);for(let[agentName,profile]of Object.entries(profiles))if(!validAgents.has(agentName))findings.push({id:"unknown-agent-profile",title:"Unknown agent profile",description:`Profile for unknown agent "${agentName}" will be ignored.`,severity:"info",path:`guardrails.profiles.${agentName}`,currentValue:profile,autoFixable:!0,proposedFix:{type:"remove",path:`guardrails.profiles.${agentName}`,description:`Remove unknown agent profile "${agentName}"`,risk:"low"}})}break}case"automation.mode":{let validModes=["manual","hybrid","auto"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-automation-mode",title:"Invalid automation mode",description:`Invalid automation mode "${value}". Valid: ${validModes.join(", ")}`,severity:"error",path:"automation.mode",currentValue:value,autoFixable:!0,proposedFix:{type:"update",path:"automation.mode",value:"manual",description:'Reset to safe default "manual"',risk:"low"}});break}case"automation.capabilities":{let caps=value;if(caps){let capabilityNames=["plan_sync","phase_preflight","config_doctor_on_startup","evidence_auto_summaries","decision_drift_detection"];for(let[name,capValue]of Object.entries(caps))if(capabilityNames.includes(name)&&typeof capValue!=="boolean")findings.push({id:"invalid-capability-type",title:"Invalid capability type",description:`Capability "${name}" must be boolean, got ${typeof capValue}`,severity:"error",path:`automation.capabilities.${name}`,currentValue:capValue,autoFixable:!0,proposedFix:{type:"update",path:`automation.capabilities.${name}`,value:!1,description:`Reset capability "${name}" to false`,risk:"low"}})}break}case"hooks":{if(emitObjectTypeMismatch("hooks",value,findings),value!==void 0&&typeof value==="object"&&!Array.isArray(value)&&value!==null){let hooks2=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks2))if(!validHooks.includes(hookName))findings.push({id:"unknown-hook-field",title:"Unknown hook configuration",description:`Unknown hook "${hookName}" will be ignored.`,severity:"info",path:`hooks.${hookName}`,currentValue:hooks2[hookName],autoFixable:!0,proposedFix:{type:"remove",path:`hooks.${hookName}`,description:`Remove unknown hook "${hookName}"`,risk:"low"}})}break}case"max_iterations":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-iterations",title:"max_iterations out of bounds",description:`max_iterations must be 1-10, got ${numValue}`,severity:"error",path:"max_iterations",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"max_iterations",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"qa_retry_limit":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-retry-limit",title:"qa_retry_limit out of bounds",description:`qa_retry_limit must be 1-10, got ${numValue}`,severity:"error",path:"qa_retry_limit",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"qa_retry_limit",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"swarms":{if(value!==void 0){if(typeof value!=="object"||Array.isArray(value)||value===null){findings.push({id:"invalid-swarms-type",title:"Invalid swarms type",description:`"swarms" must be an object, got ${typeof value}`,severity:"error",path:"swarms",currentValue:value,autoFixable:!1});break}let swarms=value;if(Object.keys(swarms).length===0)findings.push({id:"empty-swarms",title:"Empty swarms configuration",description:'The "swarms" field is an empty object. No swarm configurations are defined.',severity:"info",path:"swarms",autoFixable:!1});for(let swarmId of Object.keys(swarms))if(swarmId.includes("..")||swarmId.includes("/")||swarmId.includes("\\")||swarmId.includes("\x00"))findings.push({id:"swarm-id-path-traversal",title:"Path traversal in swarm ID",description:`Swarm ID "${swarmId}" contains path traversal characters.`,severity:"error",path:`swarms.${swarmId}`,autoFixable:!1});let validAgents=new Set(ALL_AGENT_NAMES);for(let[swarmId,swarmConfig]of Object.entries(swarms)){let swarm=swarmConfig;if(swarm.agents&&typeof swarm.agents==="object")for(let[agentName]of Object.entries(swarm.agents)){let baseName=stripKnownSwarmPrefix(agentName);if(baseName!==agentName&&agentName.startsWith(`${swarmId}_`)&&validAgents.has(baseName))findings.push({id:"prefixed-swarm-agent-override",title:"Prefixed agent override is ignored",description:`Agent "${agentName}" in swarm "${swarmId}" uses a generated agent name. Per-swarm overrides must use the canonical key "${baseName}", e.g. "swarms.${swarmId}.agents.${baseName}.model". Otherwise the override is ignored and the agent falls back to its default model.`,severity:"warn",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1});else if(!validAgents.has(baseName))findings.push({id:"unknown-swarm-agent",title:"Unknown agent in swarm",description:`Agent "${agentName}" in swarm "${swarmId}" may not be recognized.`,severity:"info",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1})}}}break}case"default_agent":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-default_agent-type",title:"Invalid default_agent type",description:`"default_agent" must be a string, got ${typeof value}`,severity:"error",path:"default_agent",currentValue:value,autoFixable:!1});break}case"auto_select_architect":{if(value!==void 0&&typeof value!=="boolean"&&typeof value!=="string")findings.push({id:"invalid-auto_select_architect-type",title:"Invalid auto_select_architect type",description:`"auto_select_architect" must be a boolean or string, got ${typeof value}`,severity:"error",path:"auto_select_architect",currentValue:value,autoFixable:!1});break}case"pipeline":{emitObjectTypeMismatch("pipeline",value,findings);break}case"harness_evolution":{emitObjectTypeMismatch("harness_evolution",value,findings);break}case"harness_opt":{emitObjectTypeMismatch("harness_opt",value,findings);break}case"phase_complete":{emitObjectTypeMismatch("phase_complete",value,findings);break}case"execution_mode":{let validModes=["strict","balanced","fast"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-execution_mode-type",title:"Invalid execution_mode",description:`"execution_mode" must be one of: ${validModes.join(", ")}, got "${value}"`,severity:"error",path:"execution_mode",currentValue:value,autoFixable:!1});break}case"inject_phase_reminders":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-inject_phase_reminders-type",title:"Invalid inject_phase_reminders type",description:`"inject_phase_reminders" must be a boolean, got ${typeof value}`,severity:"error",path:"inject_phase_reminders",currentValue:value,autoFixable:!1});break}case"gates":{emitObjectTypeMismatch("gates",value,findings);break}case"context_budget":{emitObjectTypeMismatch("context_budget",value,findings);break}case"pricing":{emitObjectTypeMismatch("pricing",value,findings);break}case"guardrails":{emitObjectTypeMismatch("guardrails",value,findings);break}case"watchdog":{emitObjectTypeMismatch("watchdog",value,findings);break}case"self_review":{emitObjectTypeMismatch("self_review",value,findings);break}case"tool_filter":{emitObjectTypeMismatch("tool_filter",value,findings);break}case"authority":{emitObjectTypeMismatch("authority",value,findings);break}case"plan_cursor":{emitObjectTypeMismatch("plan_cursor",value,findings);break}case"context_map":{emitObjectTypeMismatch("context_map",value,findings);break}case"evidence":{emitObjectTypeMismatch("evidence",value,findings);break}case"summaries":{emitObjectTypeMismatch("summaries",value,findings);break}case"auto_review":{emitObjectTypeMismatch("auto_review",value,findings);break}case"repo_graph":{emitObjectTypeMismatch("repo_graph",value,findings);break}case"retention":{emitObjectTypeMismatch("retention",value,findings);break}case"review_passes":{emitObjectTypeMismatch("review_passes",value,findings);break}case"adversarial_detection":{emitObjectTypeMismatch("adversarial_detection",value,findings);break}case"adversarial_testing":{emitObjectTypeMismatch("adversarial_testing",value,findings);break}case"integration_analysis":{emitObjectTypeMismatch("integration_analysis",value,findings);break}case"docs":{emitObjectTypeMismatch("docs",value,findings);break}case"forge":{emitObjectTypeMismatch("forge",value,findings);break}case"design_docs":{emitObjectTypeMismatch("design_docs",value,findings);break}case"git":{emitObjectTypeMismatch("git",value,findings);break}case"git.binary":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-git-binary-type",title:"Invalid git.binary type",description:`"git.binary" must be a string, got ${typeof value}`,severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});else if(typeof value==="string"&&value.trim()==="")findings.push({id:"empty-git-binary",title:"Empty git.binary",description:'"git.binary" is blank, so no git executable is named. Remove the key to fall back to the default `git` lookup, or set it to a real git executable path.',severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});break}case"ui_review":{emitObjectTypeMismatch("ui_review",value,findings);break}case"compaction_advisory":{emitObjectTypeMismatch("compaction_advisory",value,findings);break}case"lint":{emitObjectTypeMismatch("lint",value,findings);break}case"secretscan":{emitObjectTypeMismatch("secretscan",value,findings);break}case"checkpoint":{emitObjectTypeMismatch("checkpoint",value,findings);break}case"apply_patch":{emitObjectTypeMismatch("apply_patch",value,findings);break}case"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",value,findings);break}case"observability":{if(emitObjectTypeMismatch("observability",value,findings),typeof value==="object"&&value!==null&&!Array.isArray(value)){let exportCfg=value.export;if(typeof exportCfg==="object"&&exportCfg!==null&&exportCfg.enabled===!0){let endpoint=exportCfg.endpoint,problem=null;if(typeof endpoint!=="string"||endpoint.length===0)problem="observability.export.enabled is true but endpoint is empty — the exporter stays disabled until an endpoint is configured.";else try{let url3=new URL(endpoint),host=url3.hostname.replace(/^\[|\]$/g,""),isLoopback=host==="localhost"||host==="127.0.0.1"||host==="::1";if(url3.protocol!=="https:"&&!isLoopback)problem="observability.export.endpoint uses plain http: for a non-loopback host — exported telemetry would travel unencrypted; use https: outside local test collectors."}catch{problem="observability.export.endpoint is not a valid URL — the exporter stays disabled."}if(problem!==null)findings.push({id:"observability-export-endpoint-policy",title:"OTLP export endpoint policy",description:problem,severity:"warn",path:"observability.export.endpoint",autoFixable:!1})}}break}case"learning":{emitObjectTypeMismatch("learning",value,findings);break}case"consensus":{emitObjectTypeMismatch("consensus",value,findings);break}case"curator":{emitObjectTypeMismatch("curator",value,findings);break}case"architectural_supervision":{emitObjectTypeMismatch("architectural_supervision",value,findings);break}case"knowledge_application":{emitObjectTypeMismatch("knowledge_application",value,findings);break}case"skillPropagation":{emitObjectTypeMismatch("skillPropagation",value,findings);break}case"skill_improver":{emitObjectTypeMismatch("skill_improver",value,findings);break}case"skills":{emitObjectTypeMismatch("skills",value,findings);break}case"spec_writer":{emitObjectTypeMismatch("spec_writer",value,findings);break}case"tool_output":{emitObjectTypeMismatch("tool_output",value,findings);break}case"slop_detector":{emitObjectTypeMismatch("slop_detector",value,findings);break}case"todo_gate":{emitObjectTypeMismatch("todo_gate",value,findings);break}case"incremental_verify":{emitObjectTypeMismatch("incremental_verify",value,findings);break}case"compaction_service":{emitObjectTypeMismatch("compaction_service",value,findings);break}case"prm":{emitObjectTypeMismatch("prm",value,findings);break}case"council":{emitObjectTypeMismatch("council",value,findings);break}case"parallelization":{emitObjectTypeMismatch("parallelization",value,findings);break}case"worktree":{emitObjectTypeMismatch("worktree",value,findings);break}case"turbo":{emitObjectTypeMismatch("turbo",value,findings);break}case"turbo_mode":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-turbo_mode-type",title:"Invalid turbo_mode type",description:`"turbo_mode" must be a boolean, got ${typeof value}`,severity:"error",path:"turbo_mode",currentValue:value,autoFixable:!1});break}case"quiet":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-quiet-type",title:"Invalid quiet type",description:`"quiet" must be a boolean, got ${typeof value}`,severity:"error",path:"quiet",currentValue:value,autoFixable:!1});break}case"version_check":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-version_check-type",title:"Invalid version_check type",description:`"version_check" must be a boolean, got ${typeof value}`,severity:"error",path:"version_check",currentValue:value,autoFixable:!1});break}case"$schema":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-$schema-type",title:"Invalid $schema type",description:`"$schema" must be a string (JSON Schema URL), got ${typeof value}`,severity:"error",path:"$schema",currentValue:value,autoFixable:!1});break}case"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"pr_feedback_loop":{emitObjectTypeMismatch("pr_feedback_loop",value,findings);break}case"pr_review_resilience":{emitObjectTypeMismatch("pr_review_resilience",value,findings);break}case"speckit_checkoff":{emitObjectTypeMismatch("speckit_checkoff",value,findings);break}case"review_routing":{if(emitObjectTypeMismatch("review_routing",value,findings),isPlainObject5(value)){let enforceReceipts=value.enforce_receipts;if(enforceReceipts!==void 0&&typeof enforceReceipts!=="boolean")findings.push({id:"invalid-review_routing-enforce_receipts-type",title:"Invalid review_routing.enforce_receipts type",description:`"review_routing.enforce_receipts" must be a boolean, got ${typeof enforceReceipts}`,severity:"error",path:"review_routing.enforce_receipts",currentValue:enforceReceipts,autoFixable:!1})}break}case"lane_liveness_watchdog":{emitObjectTypeMismatch("lane_liveness_watchdog",value,findings);break}case"dispatch_protection":{emitObjectTypeMismatch("dispatch_protection",value,findings);break}case"pr_review_legacy_transcript_compatibility":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-pr_review_legacy_transcript_compatibility-type",title:"Invalid pr_review_legacy_transcript_compatibility type",description:`"pr_review_legacy_transcript_compatibility" must be a boolean, got ${typeof value}`,severity:"error",path:"pr_review_legacy_transcript_compatibility",currentValue:value,autoFixable:!1});break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}case"skill_opt":{emitObjectTypeMismatch("skill_opt",value,findings);break}case"dashboard":{emitObjectTypeMismatch("dashboard",value,findings);break}default:{let topLevel=path182.split(".")[0];if(KNOWN_TOP_LEVEL_KEYS.has(topLevel))break;let MAX_SUGGESTION_KEY_LENGTH=100,lowerTopLevel=topLevel.toLowerCase(),suggestion,matchCount=0;if(lowerTopLevel.length<=MAX_SUGGESTION_KEY_LENGTH){for(let knownKey of KNOWN_TOP_LEVEL_KEYS)if(levenshteinDistance(lowerTopLevel,knownKey.toLowerCase())<=2){if(matchCount++,matchCount===1)suggestion=knownKey}}if(matchCount===1&&suggestion)findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path182}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path182,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path182}" is not in the schema.`,severity:"warn",path:path182,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path182,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path182&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path182,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path182,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path182}`,description:`Config value at "${path182}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path182,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path182,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path182}[${index}]`,findings,visited)});return}for(let[key2,value]of Object.entries(obj)){let newPath=path182?`${path182}.${key2}`:key2;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory,planParallelizationEnabled=null){let findings=[];walkConfigAndValidate(config3,"",findings),findings.push(...collectRawGatesConfigFindings(directory)),findings.push(...collectRawCouncilPolicyFindings(directory)),findings.push(...collectRawStrictSectionFindings(directory)),findings.push(...collectRawValueConstraintFindings(directory)),findings.push(...collectRawAutoReviewCompatibilityFindings(directory)),findings.push(...collectLeanTurboGateSatisfiabilityFindings(config3)),emitWorktreeIsolationLayeringAdvisory(config3,findings,planParallelizationEnabled);let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length},hasAutoFixableIssues=findings.some((f)=>f.autoFixable&&f.proposedFix?.risk==="low"),{userConfigPath,projectConfigPath}=getConfigPaths(directory),configSource="defaults";if(fs97.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs97.existsSync(userConfigPath))configSource=userConfigPath;let rawConfigVersion=config3.config_format_version,configVersion=typeof rawConfigVersion==="number"&&Number.isFinite(rawConfigVersion)&&Number.isInteger(rawConfigVersion)&&rawConfigVersion>=0?rawConfigVersion:1,availableMigrations=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(configVersion<depInfo.deprecatedIn)availableMigrations.push({field:depPath,replacement:depInfo.replacement,deprecatedIn:depInfo.deprecatedIn,sinceVersion:depInfo.sinceVersion,currentFormatVersion:configVersion});for(let flip of DEFAULT_FLIPS)if(configVersion<flip.sinceVersion)findings.push({id:"defaults-flip",title:`v8 default change pending for "${flip.field}"`,description:`Default flips from ${flip.v7Default} to ${flip.v8Default}. Kill switch: set ${flip.killSwitch}. Restore all v7 defaults with preset: "${flip.preset}". Evidence and rollback: ${flip.evidence} (#2504).`,severity:"info",path:flip.field,currentValue:"v7 default",autoFixable:!1});return summary.info=findings.filter((f)=>f.severity==="info").length,summary.warn=findings.filter((f)=>f.severity==="warn").length,summary.error=findings.filter((f)=>f.severity==="error").length,{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource,...availableMigrations.length>0?{availableMigrations}:{}}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe3(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result,options={}){let applyLossy=options.applyLossy===!0,appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs97.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs97.readFileSync(projectConfigPath,"utf-8");else if(fs97.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs97.readFileSync(userConfigPath,"utf-8");else return{appliedFixes,updatedConfigPath:null};let config3;try{config3=JSON.parse(configContent)}catch{return{appliedFixes,updatedConfigPath:null}}let safeFixes=result.findings.filter((f)=>f.autoFixable&&f.proposedFix?.risk==="low"&&(applyLossy||!f.proposedFix?.lossy));for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe3(fix.path))continue;let pathParts=fix.path.split("."),current=config3,navigated=!0;for(let i=0;i<pathParts.length-1;i++){let part=pathParts[i];if(current===null||current===void 0){navigated=!1;break}if(typeof current!=="object"||Array.isArray(current)){navigated=!1;break}let obj=current;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null){navigated=!1;break}else if(typeof obj[part]!=="object"){navigated=!1;break}current=obj[part]}if(!navigated)continue;let lastPart=pathParts[pathParts.length-1];switch(fix.type){case"remove":if(current!==null&&current!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(applyLossy&&result.availableMigrations&&result.availableMigrations.length>0)for(let migration of result.availableMigrations){if(!isPathSafe3(migration.field)||!isPathSafe3(migration.replacement))continue;let legacyParts=migration.field.split("."),legacyParent=config3,legacyNavigated=!0;for(let i=0;i<legacyParts.length-1;i++){let part=legacyParts[i];if(legacyParent===null||legacyParent===void 0||typeof legacyParent!=="object"||Array.isArray(legacyParent)){legacyNavigated=!1;break}let obj=legacyParent;if(obj[part]===void 0||obj[part]===null){legacyNavigated=!1;break}legacyParent=obj[part]}if(!legacyNavigated)continue;let legacyKey=legacyParts[legacyParts.length-1],legacyHolder=legacyParent;if(!(legacyKey in legacyHolder))continue;let legacyValue=legacyHolder[legacyKey],depInfo=DEPRECATED_FIELDS.get(migration.field);if(!depInfo||depInfo.isDefaultValue(legacyValue))continue;let replParts=migration.replacement.split("."),replParent=config3,replNavigated=!0;for(let i=0;i<replParts.length-1;i++){let part=replParts[i];if(replParent===null||replParent===void 0||typeof replParent!=="object"||Array.isArray(replParent)){replNavigated=!1;break}let obj=replParent;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null||typeof obj[part]!=="object"){replNavigated=!1;break}replParent=obj[part]}if(!replNavigated)continue;let replKey=replParts[replParts.length-1];replParent[replKey]=legacyValue,delete legacyHolder[legacyKey],appliedFixes.push({type:"update",path:migration.replacement,value:legacyValue,description:`Migrate deprecated field \`${migration.field}\` → \`${migration.replacement}\``,risk:"low",lossy:!0}),appliedFixes.push({type:"remove",path:migration.field,description:`Remove deprecated field \`${migration.field}\` (migrated to \`${migration.replacement}\`)`,risk:"low",lossy:!0})}if(appliedFixes.length>0){let configDir=path181.dirname(configPath);if(!fs97.existsSync(configDir))fs97.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path181.join(directory,".swarm","config-doctor.json");if(!fs97.existsSync(artifactPath))return null;let content=fs97.readFileSync(artifactPath,"utf-8"),artifact=JSON.parse(content),summary=artifact.summary;if(!summary||typeof summary!=="object")return null;let{info:infoVal,warn:warnVal,error:errorVal}=summary;if(typeof infoVal!=="number"||!Number.isFinite(infoVal)||typeof warnVal!=="number"||!Number.isFinite(warnVal)||typeof errorVal!=="number"||!Number.isFinite(errorVal))return null;let ts=artifact.timestamp;if(typeof ts!=="number"||!Number.isFinite(ts))return null;let findingsCount=infoVal+warnVal+errorVal,findings=artifact.findings,autoFixableCount=Array.isArray(findings)?findings.filter((f)=>f.autoFixable===!0).length:0;return{timestamp:new Date(ts).toISOString(),findingsCount,autoFixableCount}}catch{return null}}function writeDoctorArtifact(directory,result){let swarmDir=path181.join(directory,".swarm");if(!fs97.existsSync(swarmDir))fs97.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path181.join(swarmDir,"config-doctor.json"),guiOutput={timestamp:result.timestamp,summary:result.summary,hasAutoFixableIssues:result.hasAutoFixableIssues,configSource:result.configSource,findings:result.findings.map((f)=>({id:f.id,title:f.title,description:f.description,severity:f.severity,path:f.path,autoFixable:f.autoFixable,proposedFix:f.proposedFix?{type:f.proposedFix.type,path:f.proposedFix.path,description:f.proposedFix.description,risk:f.proposedFix.risk,lossy:f.proposedFix.lossy===!0}:null}))};return atomicWriteFileSync(artifactPath,JSON.stringify(guiOutput,null,2)),artifactPath}function shouldRunOnStartup(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.config_doctor_on_startup===!0}async function runConfigDoctorWithFixes(directory,config3,autoFix=!1,options={}){let planParallelizationEnabled=await resolvePlanParallelizationFlag(directory),result=runConfigDoctor(config3,directory,planParallelizationEnabled),artifactPath=writeDoctorArtifact(directory,result);if(!autoFix)return{result,backupPath:null,appliedFixes:[],updatedConfigPath:null,artifactPath};let backup=createConfigBackup(directory),backupPath=null;if(backup)backupPath=writeBackupArtifact(directory,backup);let{appliedFixes,updatedConfigPath}=applySafeAutoFixes(directory,result,options),hasDefaultsFlipFindings=result.findings.some((finding)=>finding.id==="defaults-flip");if(options.applyLossy===!0&&(appliedFixes.length>0||hasDefaultsFlipFindings))try{let{userConfigPath:stampUserPath,projectConfigPath:stampProjectPath}=getConfigPaths(directory),stampPath=fs97.existsSync(stampProjectPath)?stampProjectPath:fs97.existsSync(stampUserPath)?stampUserPath:null;if(stampPath){let stampContent=fs97.readFileSync(stampPath,"utf-8"),sanitizedStampContent=stampContent.charCodeAt(0)===65279?stampContent.slice(1):stampContent,stampConfig=JSON.parse(sanitizedStampContent),currentVersion=stampConfig.config_format_version;if(typeof currentVersion!=="number"||!Number.isInteger(currentVersion)||currentVersion<0||currentVersion<CURRENT_CONFIG_FORMAT_VERSION){stampConfig.config_format_version=CURRENT_CONFIG_FORMAT_VERSION;let stampDir=path181.dirname(stampPath);if(!fs97.existsSync(stampDir))fs97.mkdirSync(stampDir,{recursive:!0});atomicWriteFileSync(stampPath,JSON.stringify(stampConfig,null,2))}}}catch(stampError){log(`[ConfigDoctor] acknowledgment stamp failed (non-fatal): ${stampError instanceof Error?stampError.message:String(stampError)}`)}if(appliedFixes.length>0){let freshConfig=readConfigFromFile(directory);if(freshConfig){let newResult=runConfigDoctor(freshConfig.config,directory,planParallelizationEnabled);writeDoctorArtifact(directory,newResult)}}return{result,backupPath,appliedFixes,updatedConfigPath,artifactPath}}function detectStraySwarmDirs(projectRoot){let findings=[],SKIP_DIRS=new Set(["node_modules",".git","dist",".cache",".next","coverage",".turbo",".vercel",".terraform","__pycache__",".tox"]),MAX_DEPTH=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries2;try{entries2=fs97.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path181.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path181.join(fullPath,".git");try{let gitStat=fs97.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path181.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs97.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path181.relative(projectRoot,fullPath).replace(/\\/g,"/"),absolutePath:fullPath,contents:contents.slice(0,20),totalEntries:contents.length});continue}walk(fullPath,depth+1)}}return walk(projectRoot,0),findings}function removeStraySwarmDir(projectRoot,strayPath){let canonicalRoot,canonicalStray;try{canonicalRoot=fs97.realpathSync(projectRoot),canonicalStray=fs97.realpathSync(path181.isAbsolute(strayPath)?strayPath:path181.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path181.join(canonicalRoot,".swarm");if(sameExistingFilesystemPath(canonicalStray,rootSwarm)||sameExistingFilesystemPath(canonicalStray,canonicalRoot))return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!isCanonicalPathWithinRoot(canonicalStray,canonicalRoot))return{success:!1,message:"Path is outside project root — refusing to remove"};if(!canonicalStray.replace(/\\/g,"/").endsWith("/.swarm"))return{success:!1,message:"Path is not a .swarm directory — refusing to remove"};try{return fs97.rmSync(canonicalStray,{recursive:!0,force:!0}),{success:!0,message:`Removed stray .swarm directory: ${canonicalStray}`}}catch(err){return{success:!1,message:`Failed to remove: ${err instanceof Error?err.message:String(err)}`}}}var CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES=102400,KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,CURRENT_CONFIG_FORMAT_VERSION=3,DEFAULT_FLIPS,LEAN_TURBO_GATE_PRODUCERS,_internals144,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_manager();init_tool_metadata();init_utils();init_filesystem_identity();init_path_security();KNOWN_TOP_LEVEL_KEYS=new Set(Object.keys(PluginConfigSchema.shape)),DEPRECATED_FIELDS=new Map([["skill_improver.model",{message:"deprecated",replacement:"agents.skill_improver.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}]]),DEFAULT_FLIPS=[{field:"auto_review.enabled",v7Default:"false (opt-in)",v8Default:"release-gated true (advisory) — activates on the first 8.x release",killSwitch:"auto_review.enabled: false",preset:"conservative",sinceVersion:3,evidence:"docs/defaults-governance.md"},{field:"execution_profile.parallelization_enabled",v7Default:"false (serial)",v8Default:"true for new plans (since v7.132.0, gate-enforced serial fallback)",killSwitch:"execution_profile.parallelization_enabled: false (per plan)",preset:"conservative",sinceVersion:3,evidence:"docs/defaults-governance.md"}];LEAN_TURBO_GATE_PRODUCERS=[{gate:"phase_critic",producerTool:"lean_turbo_critic",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-critic.json"},{gate:"phase_reviewer",producerTool:"lean_turbo_review",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-reviewer.json"},{gate:"integrated_diff_required",producerTool:"lean_turbo_run_phase",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo/lean-turbo-phase.json"}];_internals144={loadPlanJsonOnly};DANGEROUS_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"])});class LanguageRegistry{profiles;extensionIndex;constructor(){this.profiles=new Map,this.extensionIndex=new Map}unregister(id){let profile=this.profiles.get(id);if(!profile)return;if(this.profiles.delete(id),!profile.parserOnly){for(let ext of profile.extensions)if(this.extensionIndex.get(ext)===id)this.extensionIndex.delete(ext)}}register(profile){let existing=this.profiles.get(profile.id);if(existing&&existing!==profile)throw Error(`LanguageRegistry: profile id "${profile.id}" registered twice. Each LanguageProfile.id must be unique. Got: ${profile.displayName} vs existing ${existing.displayName}.`);if(!profile.parserOnly)for(let ext of profile.extensions){let claimedBy=this.extensionIndex.get(ext);if(claimedBy&&claimedBy!==profile.id)throw Error(`LanguageRegistry: extension "${ext}" registered by both "${claimedBy}" and "${profile.id}". A non-parserOnly profile must not collide on extensions. If both languages legitimately share an extension, mark one parserOnly: true.`);this.extensionIndex.set(ext,profile.id)}this.profiles.set(profile.id,profile)}get(id){return this.profiles.get(id)}getById(id){return this.profiles.get(id)}getByExtension(ext){let profileId=this.extensionIndex.get(ext);if(profileId)return this.profiles.get(profileId);return}getAll(){return Array.from(this.profiles.values())}getTier(tier){return Array.from(this.profiles.values()).filter((p)=>p.tier===tier)}}var LANGUAGE_REGISTRY;var init_profiles=__esm(()=>{LANGUAGE_REGISTRY=new LanguageRegistry;LANGUAGE_REGISTRY.register({id:"typescript",displayName:"TypeScript",tier:1,extensions:[".ts",".tsx"],treeSitter:{grammarId:"typescript",wasmFile:"tree-sitter-typescript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"javascript",displayName:"JavaScript",tier:1,extensions:[".js",".jsx",".mjs",".cjs"],treeSitter:{grammarId:"javascript",wasmFile:"tree-sitter-javascript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"python",displayName:"Python",tier:1,extensions:[".py",".pyw"],treeSitter:{grammarId:"python",wasmFile:"tree-sitter-python.wasm",commentNodes:["comment"]},build:{detectFiles:["setup.py","pyproject.toml","setup.cfg"],commands:[{name:"pip install",cmd:"pip install -e .",detectFile:"setup.py",priority:10},{name:"build",cmd:"python -m build",detectFile:"pyproject.toml",priority:9}]},test:{detectFiles:["pytest.ini","pyproject.toml","setup.cfg","conftest.py"],frameworks:[{name:"pytest",detect:"pytest.ini",cmd:"pytest",priority:10},{name:"unittest",detect:"setup.py",cmd:"python -m unittest discover",priority:8}]},lint:{detectFiles:["pyproject.toml",".ruff.toml","setup.cfg"],linters:[{name:"ruff",detect:"pyproject.toml",cmd:"ruff check --fix .",priority:10},{name:"flake8",detect:"setup.cfg",cmd:"flake8 .",priority:8}]},audit:{detectFiles:["requirements.txt","Pipfile.lock","pyproject.toml"],command:"pip-audit --format json",outputFormat:"json"},sast:{nativeRuleSet:"python",semgrepSupport:"ga"},prompts:{coderConstraints:["Use type annotations on all function signatures (PEP 484)","Prefer f-strings over .format() or % formatting","Use pathlib.Path over os.path for filesystem operations","Never use bare except:; catch specific exception types","Follow PEP 8 style; max line length 120 characters"],reviewerChecklist:["Verify type annotations are present on all public functions","Check for bare except clauses or overly broad exception handling","Confirm no mutable default arguments (def f(x=[]) anti-pattern)","Validate f-string usage and no format string injection risks","Check imports are organized (stdlib → third-party → local)"]}});LANGUAGE_REGISTRY.register({id:"rust",displayName:"Rust",tier:1,extensions:[".rs"],treeSitter:{grammarId:"rust",wasmFile:"tree-sitter-rust.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["Cargo.toml"],commands:[{name:"cargo build",cmd:"cargo build",detectFile:"Cargo.toml",priority:10},{name:"cargo check",cmd:"cargo check",detectFile:"Cargo.toml",priority:9}]},test:{detectFiles:["Cargo.toml"],frameworks:[{name:"cargo",detect:"Cargo.toml",cmd:"cargo test",priority:10}]},lint:{detectFiles:["Cargo.toml"],linters:[{name:"clippy",detect:"Cargo.toml",cmd:"cargo clippy --fix --allow-dirty",priority:10},{name:"rustfmt",detect:"Cargo.toml",cmd:"cargo fmt",priority:9}]},audit:{detectFiles:["Cargo.lock"],command:"cargo audit --json",outputFormat:"json"},sast:{nativeRuleSet:"rust",semgrepSupport:"ga"},prompts:{coderConstraints:["Prefer owned types over references where ownership is clear; use lifetimes sparingly","Use Result<T, E> and ? operator for error propagation; never unwrap() in library code","Prefer iterators and combinators over explicit loops","Derive standard traits (Debug, Clone, PartialEq) whenever sensible","Avoid unsafe blocks; document any unsafe usage with SAFETY comments"],reviewerChecklist:["Verify no unwrap() or expect() calls in library/production paths","Check for potential panics in indexing, arithmetic overflow, or slice operations","Confirm error types implement std::error::Error and are propagated correctly","Validate lifetime annotations are minimal and correct","Check unsafe blocks have SAFETY comments explaining invariants"]}});LANGUAGE_REGISTRY.register({id:"go",displayName:"Go",tier:1,extensions:[".go"],treeSitter:{grammarId:"go",wasmFile:"tree-sitter-go.wasm",commentNodes:["comment"]},build:{detectFiles:["go.mod"],commands:[{name:"go build",cmd:"go build ./...",detectFile:"go.mod",priority:10},{name:"go vet",cmd:"go vet ./...",detectFile:"go.mod",priority:9}]},test:{detectFiles:["go.mod"],frameworks:[{name:"go-test",detect:"go.mod",cmd:"go test ./...",priority:10}]},lint:{detectFiles:["go.mod",".golangci.yml",".golangci.yaml"],linters:[{name:"golangci-lint",detect:".golangci.yml",cmd:"golangci-lint run --fix",priority:10},{name:"gofmt",detect:"go.mod",cmd:"gofmt -w .",priority:9}]},audit:{detectFiles:["go.mod"],command:"govulncheck -json ./...",outputFormat:"json"},sast:{nativeRuleSet:"go",semgrepSupport:"ga"},prompts:{coderConstraints:["Always check and return errors; never discard error return values","Use idiomatic Go error wrapping with fmt.Errorf and %w verb","Prefer table-driven tests; use t.Run for subtests","Avoid global mutable state; use dependency injection via interfaces","Use context.Context as first parameter for all I/O-bound functions"],reviewerChecklist:["Verify all error return values are checked (no _ = err pattern)","Check goroutine usage — confirm no goroutine leaks or missing WaitGroups","Validate context propagation through call chains","Confirm exported types/functions have doc comments","Check for data races in concurrent code (verify sync usage)"]}});LANGUAGE_REGISTRY.register({id:"java",displayName:"Java",tier:2,extensions:[".java"],treeSitter:{grammarId:"java",wasmFile:"tree-sitter-java.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],commands:[{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:8}]},test:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],frameworks:[{name:"maven",detect:"pom.xml",cmd:"mvn test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["checkstyle.xml","pom.xml"],linters:[{name:"checkstyle",detect:"checkstyle.xml",cmd:"mvn checkstyle:check",priority:10}]},audit:{detectFiles:["pom.xml","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"java",semgrepSupport:"ga"},prompts:{coderConstraints:["Use checked exceptions for recoverable conditions; unchecked for programming errors","Prefer composition over inheritance; favor interfaces over abstract classes","Use Optional<T> for nullable return values rather than returning null","Follow Java naming conventions: PascalCase classes, camelCase methods/fields","Close resources in try-with-resources blocks; never rely on finalizers"],reviewerChecklist:["Check for unclosed resources — verify try-with-resources or explicit close()","Verify null checks are present for all external/injected dependencies","Confirm thread safety for shared mutable state (synchronized, volatile, atomic)","Validate exception handling — no swallowed exceptions or empty catch blocks","Check for proper equals()/hashCode() overrides on value objects"]}});LANGUAGE_REGISTRY.register({id:"kotlin",displayName:"Kotlin",tier:2,extensions:[".kt",".kts"],treeSitter:{grammarId:"kotlin",wasmFile:"tree-sitter-kotlin.wasm",commentNodes:["line_comment","multiline_comment"]},build:{detectFiles:["build.gradle.kts","build.gradle","pom.xml"],commands:[{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:8}]},test:{detectFiles:["build.gradle.kts","build.gradle"],frameworks:[{name:"gradle",detect:"build.gradle.kts",cmd:"gradle test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["build.gradle.kts","build.gradle"],linters:[{name:"ktlint",detect:"build.gradle.kts",cmd:"ktlint --format",priority:10}]},audit:{detectFiles:["build.gradle.kts","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"beta"},prompts:{coderConstraints:["Prefer val over var; use data classes for value objects","Use Kotlin coroutines for async operations; avoid blocking calls on Dispatchers.Main","Leverage extension functions instead of utility classes","Use sealed classes for exhaustive when expressions","Avoid platform types; always declare explicit nullability in API surfaces"],reviewerChecklist:["Verify no non-null assertions (!!) in production code without justification","Check coroutine scope lifecycle — confirm scopes are cancelled when no longer needed","Validate when expressions are exhaustive (sealed class coverage)","Confirm data class equals/hashCode/copy semantics are appropriate","Check for blocking I/O on the wrong coroutine dispatcher"]}});LANGUAGE_REGISTRY.register({id:"csharp",displayName:"C# / .NET",tier:2,extensions:[".cs",".csx"],treeSitter:{grammarId:"csharp",wasmFile:"tree-sitter-c-sharp.wasm",commentNodes:["comment"]},build:{detectFiles:["*.csproj","*.sln","Directory.Build.props"],commands:[{name:"dotnet build",cmd:"dotnet build -v quiet",detectFile:"*.csproj",priority:10},{name:"dotnet build sln",cmd:"dotnet build -v quiet",detectFile:"*.sln",priority:9}]},test:{detectFiles:["*.csproj","*.sln"],frameworks:[{name:"dotnet-test",detect:"*.csproj",cmd:"dotnet test",priority:10}]},lint:{detectFiles:["*.csproj",".editorconfig"],linters:[{name:"dotnet-format",detect:"*.csproj",cmd:"dotnet format",priority:10}]},audit:{detectFiles:["*.csproj","packages.lock.json"],command:"dotnet list package --vulnerable --include-transitive",outputFormat:"text"},sast:{nativeRuleSet:"csharp",semgrepSupport:"ga"},prompts:{coderConstraints:["Use async/await throughout; avoid .Result or .Wait() which can deadlock","Prefer records for immutable value types; use struct only for small value types","Use nullable reference types (NRT) — enable <Nullable>enable</Nullable>","Dispose IDisposable resources with using statements or declarations","Follow C# naming conventions: PascalCase for public members, _camelCase for private fields"],reviewerChecklist:["Verify no .Result or .Wait() calls that could cause deadlocks","Check all IDisposable are properly disposed (using / IAsyncDisposable)","Confirm nullable reference type annotations are present and correct","Validate LINQ queries do not cause N+1 query patterns in EF contexts","Check for missing ConfigureAwait(false) in library code"]}});LANGUAGE_REGISTRY.register({id:"cpp",displayName:"C / C++",tier:2,extensions:[".c",".h",".cpp",".hpp",".cc",".cxx"],treeSitter:{grammarId:"cpp",wasmFile:"tree-sitter-cpp.wasm",commentNodes:["comment"]},build:{detectFiles:["CMakeLists.txt","Makefile","meson.build"],commands:[{name:"cmake",cmd:"cmake --build build",detectFile:"CMakeLists.txt",priority:10},{name:"make",cmd:"make",detectFile:"Makefile",priority:9},{name:"meson",cmd:"meson compile -C builddir",detectFile:"meson.build",priority:8}]},test:{detectFiles:["CMakeLists.txt"],frameworks:[{name:"ctest",detect:"CMakeLists.txt",cmd:"ctest --test-dir build",priority:10}]},lint:{detectFiles:[".clang-tidy","CMakeLists.txt"],linters:[{name:"cppcheck",detect:"CMakeLists.txt",cmd:"cppcheck --error-exitcode=1 .",priority:10},{name:"clang-tidy",detect:".clang-tidy",cmd:"clang-tidy -p build",priority:9}]},audit:{detectFiles:["CMakeLists.txt","vcpkg.json","conanfile.txt"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"cpp",semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer RAII and smart pointers (unique_ptr, shared_ptr) over raw pointers","Use const-correctness throughout; mark all non-mutating methods const","Avoid undefined behaviour: no out-of-bounds access, no use-after-free","Initialize all variables; prefer in-class initializers for member variables","Use std::array or std::vector instead of C-style arrays"],reviewerChecklist:["Verify no raw owning pointers; confirm smart pointer ownership semantics","Check for memory leaks — every new has a corresponding delete or smart pointer","Validate bounds checking on all array/buffer accesses","Confirm no undefined behavior patterns (signed overflow, strict aliasing violations)","Check thread safety for shared data (mutex, atomic, lock-free patterns)"]}});LANGUAGE_REGISTRY.register({id:"swift",displayName:"Swift",tier:2,extensions:[".swift"],treeSitter:{grammarId:"swift",wasmFile:"tree-sitter-swift.wasm",commentNodes:["comment","multiline_comment"]},build:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace"],commands:[{name:"swift build",cmd:"swift build",detectFile:"Package.swift",priority:10},{name:"xcodebuild",cmd:"xcodebuild build -quiet",detectFile:"*.xcodeproj",priority:9}]},test:{detectFiles:["Package.swift","*.xcodeproj"],frameworks:[{name:"swift-test",detect:"Package.swift",cmd:"swift test",priority:10},{name:"xcodebuild-test",detect:"*.xcodeproj",cmd:"xcodebuild test -quiet",priority:9}]},lint:{detectFiles:[".swiftlint.yml","Package.swift"],linters:[{name:"swiftlint",detect:".swiftlint.yml",cmd:"swiftlint --fix",priority:10}]},audit:{detectFiles:["Package.resolved","Package.swift"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer value types (structs, enums) over classes; use classes only for reference semantics","Use Swift concurrency (async/await, actors) over GCD for new code","Avoid force unwrap (!) and force cast (as!); use guard let or if let","Use Swift Package Manager for dependencies where possible","Mark types and methods as final when subclassing is not intended"],reviewerChecklist:["Verify no force unwraps (!) or force casts (as!) in production code","Check for retain cycles in closures — confirm [weak self] where needed","Validate Swift concurrency usage — no data races across actor boundaries","Confirm proper error handling with do-try-catch or Result<T,E>","Check value vs reference type choice is appropriate for the use case"]}});LANGUAGE_REGISTRY.register({id:"dart",displayName:"Dart / Flutter",tier:3,extensions:[".dart"],treeSitter:{grammarId:"dart",wasmFile:"tree-sitter-dart.wasm",commentNodes:["comment","documentation_comment"]},build:{detectFiles:["pubspec.yaml"],commands:[{name:"flutter build",cmd:"flutter build apk",detectFile:"pubspec.yaml",priority:10},{name:"dart compile",cmd:"dart compile exe .",detectFile:"pubspec.yaml",priority:9}]},test:{detectFiles:["pubspec.yaml"],frameworks:[{name:"flutter test",detect:"pubspec.yaml",cmd:"flutter test",priority:10},{name:"dart test",detect:"pubspec.yaml",cmd:"dart test",priority:9}]},lint:{detectFiles:["analysis_options.yaml","pubspec.yaml"],linters:[{name:"dart analyze",detect:"pubspec.yaml",cmd:"dart analyze",priority:10}]},audit:{detectFiles:["pubspec.yaml","pubspec.lock"],command:"dart pub outdated --json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"none"},prompts:{coderConstraints:["Use null safety features — prefer late, required, and ? annotations over dynamic","Follow Dart effective style: lowerCamelCase for variables, UpperCamelCase for types","Prefer const constructors where possible for performance","Use async/await over raw Future callbacks","Separate business logic from UI widgets; use BLoC or Provider patterns"],reviewerChecklist:["Verify null safety annotations are correct (no unnecessary ?)","Check that const constructors are used where the widget tree is static","Confirm async operations handle error states (catchError or try-catch)","Validate no direct UI state mutation outside setState or stream","Check for platform-specific code isolation (dart:io vs dart:html)"]}});LANGUAGE_REGISTRY.register({id:"ruby",displayName:"Ruby",tier:3,extensions:[".rb",".rake",".gemspec"],treeSitter:{grammarId:"ruby",wasmFile:"tree-sitter-ruby.wasm",commentNodes:["comment"]},build:{detectFiles:["Gemfile","Rakefile"],commands:[{name:"bundle install",cmd:"bundle install",detectFile:"Gemfile",priority:10},{name:"rake",cmd:"rake",detectFile:"Rakefile",priority:9}]},test:{detectFiles:["Gemfile",".rspec","spec/spec_helper.rb"],frameworks:[{name:"rspec",detect:".rspec",cmd:"bundle exec rspec",priority:10},{name:"minitest",detect:"Rakefile",cmd:"bundle exec rake test",priority:9}]},lint:{detectFiles:[".rubocop.yml","Gemfile"],linters:[{name:"rubocop",detect:".rubocop.yml",cmd:"rubocop --autocorrect",priority:10}]},audit:{detectFiles:["Gemfile.lock"],command:"bundle-audit check --format json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Follow Ruby community style (Rubocop defaults); 120-char line limit","Prefer symbols over strings for hash keys","Use frozen_string_literal: true magic comment in all files","Avoid monkey-patching core classes; prefer refinements","Use keyword arguments for methods with more than 2 parameters"],reviewerChecklist:["Verify frozen_string_literal comment is present in new files","Check for N+1 query patterns in ActiveRecord code","Validate no eval or send with user-controlled input (code injection risk)","Confirm exception handling is specific — no bare rescue","Check for missing validations on ActiveRecord models"]}});LANGUAGE_REGISTRY.register({id:"php",displayName:"PHP",tier:3,extensions:[".php",".phtml",".blade.php"],treeSitter:{grammarId:"php",wasmFile:"tree-sitter-php.wasm",commentNodes:["comment"]},build:{detectFiles:["composer.json"],commands:[{name:"Composer Install",cmd:"composer install --no-interaction --prefer-dist",detectFile:"composer.json",priority:10}]},test:{detectFiles:["Pest.php","phpunit.xml","phpunit.xml.dist"],frameworks:[{name:"Pest",detect:"Pest.php",cmd:"vendor/bin/pest",priority:10},{name:"PHPUnit",detect:"phpunit.xml",cmd:"vendor/bin/phpunit",priority:8},{name:"PHPUnit",detect:"phpunit.xml.dist",cmd:"vendor/bin/phpunit",priority:7}]},lint:{detectFiles:["phpstan.neon","phpstan.neon.dist","pint.json",".php-cs-fixer.php","phpcs.xml"],linters:[{name:"PHPStan",detect:"phpstan.neon",cmd:"vendor/bin/phpstan analyse",priority:10},{name:"PHPStan",detect:"phpstan.neon.dist",cmd:"vendor/bin/phpstan analyse",priority:9},{name:"Pint",detect:"pint.json",cmd:"vendor/bin/pint --test",priority:8},{name:"PHP-CS-Fixer",detect:".php-cs-fixer.php",cmd:"vendor/bin/php-cs-fixer fix --dry-run --diff",priority:7}]},audit:{detectFiles:["composer.lock"],command:"composer audit --locked --format=json",outputFormat:"json"},sast:{nativeRuleSet:"php",semgrepSupport:"ga"},prompts:{coderConstraints:["Follow PSR-12 coding standards","Use strict types declaration: declare(strict_types=1)","Prefer type hints and return type declarations on all functions","Use dependency injection over static methods and singletons","Prefer named constructors and value objects over primitive obsession"],reviewerChecklist:["Verify no user input reaches SQL queries without parameterised binding","Check for XSS — all output must be escaped with htmlspecialchars()","Confirm no eval(), exec(), or shell_exec() with user-controlled input","Validate proper error handling — no bare catch blocks that swallow errors","Challenge any PHP/Laravel documentation or README claim that exceeds what is implemented and CI-verified in v6.49.0 (composer build, PHPUnit/Pest/artisan test, Pint/PHP-CS-Fixer lint, PHPStan static analysis, composer audit, Laravel detection, Blade scanning, 3 Laravel SAST rules). If a PR adds docs claiming broader support, verify it is backed by tests."],testConstraints:["Prefer feature tests for HTTP, middleware, and authentication flows — use Laravel RefreshDatabase or DatabaseTransactions traits","Use unit tests for isolated business logic classes that do not require the full Laravel application container","Pest and PHPUnit coexist in many Laravel repos — php artisan test runs both; do not assume PHPUnit-only","Use .env.testing for test environment configuration; run php artisan config:clear when environment changes affect tests","For database tests, prefer RefreshDatabase over manual setUp/tearDown to avoid state leakage between tests","Run php artisan config:clear and php artisan cache:clear before running tests if environment variables changed","Use separate .env.testing file for test-specific configuration; never rely on .env for CI test runs","For parallel testing with php artisan test --parallel, ensure database connections use separate databases per worker (APP_ENV=testing + test database suffix pattern)"]}})});import{access as access4,readdir as readdir12}from"node:fs/promises";import{extname as extname9,join as join137}from"node:path";function getProfileForFile(filePath){let ext=extname9(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries2;try{dirEntries=await readdir12(dir,{withFileTypes:!0}),entries2=dirEntries.map((e)=>e.name)}catch{return}for(let profile of LANGUAGE_REGISTRY.getAll())for(let detectFile of profile.build.detectFiles){if(detectFile.includes("*")||detectFile.includes("?")){let regex=new RegExp(`^${detectFile.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);if(dirEntries.some((e)=>!e.isDirectory()&&regex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join137(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries2){let ext=extname9(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir12(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join137(projectDir,entry.name))}catch{}let result=[];for(let id of detected){let profile=LANGUAGE_REGISTRY.getById(id);if(profile)result.push(profile)}return result.sort((a,b)=>a.tier-b.tier),result}var init_detector=__esm(()=>{init_profiles()});import*as fs98 from"node:fs";import*as path182 from"node:path";function tokenizeCommand(command){let out=[],buf="",quote=null;for(let ch of command.trim()){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}function findCommandSuffixStart(command){let quote=null,sawTokenChar=!1;for(let i=0;i<command.length;i++){let ch=command[i];if(quote){if(ch===quote)quote=null;else sawTokenChar=!0;continue}if(ch==='"'||ch==="'"){quote=ch,sawTokenChar=!0;continue}if((ch===" "||ch==="\t")&&sawTokenChar)return i;if(ch!==" "&&ch!=="\t")sawTokenChar=!0}return command.length}function resolveLocalCandidate(binary,workingDir,platform=process.platform,isAvailable){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`,absolute=path182.join(workingDir,"node_modules",".bin",executable);if(!fs98.existsSync(absolute))continue;if(candidate.requiresNode&&isAvailable&&!isAvailable("node"))continue;let relative39=platform==="win32"?path182.win32.join("node_modules",".bin",executable):path182.posix.join("node_modules",".bin",executable);return{absolute,relative:relative39,requiresNode:candidate.requiresNode}}return null}function hasAnyLocalCandidate(binary,workingDir,platform=process.platform){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`;if(fs98.existsSync(path182.join(workingDir,"node_modules",".bin",executable)))return!0}return!1}function resolveLocalCommand(command,workingDir,isAvailable,platform=process.platform){let tokens2=tokenizeCommand(command);if(tokens2.length===0)return null;let[binary,...args2]=tokens2;if(["npx","bunx","pnpx"].includes(binary))return null;if(binary.includes("/")||binary.includes("\\"))return null;let trimmed=command.trim(),local=resolveLocalCandidate(binary,workingDir,platform,isAvailable);if(local){let shellPath=platform==="win32"?local.relative:`./${local.relative}`;return{argv:[local.absolute,...args2],shellCommand:`${shellPath}${trimmed.slice(findCommandSuffixStart(trimmed))}`}}if(hasAnyLocalCandidate(binary,workingDir,platform))return null;return isAvailable(binary)?{argv:tokens2,shellCommand:command}:null}function resolveLocalNodeTool(tool3,args2,workingDir,platform=process.platform,isAvailable){let local=resolveLocalCandidate(tool3,workingDir,platform,platform==="win32"?isAvailable:void 0);if(local)return[local.absolute,...args2];if(hasAnyLocalCandidate(tool3,workingDir,platform))return null;return isAvailable?.(tool3)?[tool3,...args2]:null}var WINDOWS_LOCAL_SHIM_CANDIDATES;var init_command_resolution=__esm(()=>{WINDOWS_LOCAL_SHIM_CANDIDATES=[{suffix:".cmd",requiresNode:!0},{suffix:".exe",requiresNode:!1},{suffix:".bat",requiresNode:!0},{suffix:".ps1",requiresNode:!0},{suffix:"",requiresNode:!0}]});import*as fs99 from"node:fs";import*as path183 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32";try{let searchName=isWindows?command:command,available=_internals145.spawnSyncImpl(isWindows?["where",searchName]:["which",searchName],{cwd:process.cwd(),stdin:"ignore",stdout:"ignore",stderr:"ignore",timeout:IS_COMMAND_AVAILABLE_TIMEOUT_MS}).success;return toolchainCache.set(command,available),available}catch{return toolchainCache.set(command,!1),!1}}function checkToolchain(commands){return commands.some((cmd)=>_internals145.isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs99.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path183.join(dir,matches[0])}catch{}}else{let filePath=path183.join(workingDir,pattern);if(fs99.existsSync(filePath))return filePath}return null}function sanitizeEvidenceText(raw,maxChars){let withoutControls="";for(let char of raw){let code=char.charCodeAt(0);withoutControls+=code<32||code===127?" ":char}let normalized=withoutControls.replace(/\s+/g," ").trim();if(!normalized)return"(empty)";if(normalized.length<=maxChars)return normalized;if(maxChars<=3)return normalized.slice(0,maxChars);return`${normalized.slice(0,maxChars-3)}...`}function sanitizeRequiredCommand(command){let sanitized=sanitizeEvidenceText(command,40);return sanitized==="(empty)"?null:sanitized}function getBinaryFromCommand(command){return command.trim().split(/\s+/)[0]??""}function getProfileRequiredCommands(commands){let uniqueCommands=new Set;for(let command of commands){let binary=sanitizeRequiredCommand(getBinaryFromCommand(command.cmd));if(binary)uniqueCommands.add(binary)}return Array.from(uniqueCommands)}function getNoMatchingBuildFilesReason(profileId,commands){let detectFiles=Array.from(new Set(commands.map((command)=>command.detectFile?.trim()).filter((detectFile)=>Boolean(detectFile))));if(detectFiles.length===0)return`No matching build files for profile ${profileId}`;return`No matching build files for profile ${profileId}: expected ${detectFiles.join(" or ")}`}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path183.join(workingDir,"package.json");if(!fs99.existsSync(packageJsonPath))return{commands:[],hasScripts:!1};try{let content=fs99.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return{commands:[],hasScripts:!1};let scriptNames=scripts.filter((name)=>typeof pkg.scripts[name]==="string"&&pkg.scripts[name].trim());if(scriptNames.length===0)return{commands:[],hasScripts:!1};let rawPackageManager=typeof pkg.packageManager==="string"?pkg.packageManager.trim():void 0,declared=rawPackageManager?.split("@")[0]?.trim(),supported=[...SUPPORTED_NODE_PACKAGE_MANAGERS],sanitizedDeclared=declared?sanitizeRequiredCommand(declared):null,candidates=declared?[declared]:supported;if(rawPackageManager!==void 0&&(!declared||!supported.includes(declared)))return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:sanitizedDeclared?[sanitizedDeclared]:[],reason:`Unsupported packageManager: ${sanitizeEvidenceText(rawPackageManager,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS)}`}};let manager=candidates.find((candidate)=>_internals145.isCommandAvailable(candidate));if(!manager)return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:candidates,reason:`Package manager not available: ${candidates.join(" or ")}`}};return{hasScripts:!0,commands:scriptNames.map((scriptName)=>({command:`${manager} run ${scriptName}`,priority:100}))}}catch{return{commands:[],hasScripts:!1}}}function filterByScope(workingDir,scope,changedFiles){if(scope==="all")return findAllBuildFiles(workingDir);if(!changedFiles||changedFiles.length===0)return[];return changedFiles}function findAllBuildFiles(workingDir){let allBuildFiles=new Set;for(let ecosystem of ECOSYSTEMS)for(let pattern of ecosystem.buildFiles)if(pattern.includes("*")){let regex=simpleGlobToRegex(pattern);findFilesRecursive(workingDir,regex,allBuildFiles)}else{let filePath=path183.join(workingDir,pattern);if(fs99.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries2=fs99.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path183.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&&regex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await _internals145.detectProjectLanguagesImpl(workingDir);for(let profile of detectedProfiles){let fullProfile=_internals145.getLanguageProfileImpl(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>b.priority-a.priority),applicableCommands=sortedCommands.filter((cmd)=>{if(!cmd.detectFile)return!0;let detectFilePath=path183.join(workingDir,cmd.detectFile);return fs99.existsSync(detectFilePath)});if(applicableCommands.length===0){skipped.push({ecosystem:fullProfile.id,reason:getNoMatchingBuildFilesReason(fullProfile.id,sortedCommands)});continue}let foundCommand=!1;for(let cmd of applicableCommands){let resolved=resolveLocalCommand(cmd.cmd,workingDir,_internals145.isCommandAvailable);if(resolved){commands.push({ecosystem:fullProfile.id,command:resolved.shellCommand,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let requiredCommands=getProfileRequiredCommands(applicableCommands),triedBinaries=requiredCommands.join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,code:"environment_unavailable",required_commands:requiredCommands,reason}),warn(`[build-discovery] profile ${fullProfile.id}: no binary available, skipping`)}}return{commands,skipped}}async function discoverBuildCommands(workingDir,options){let scope=options?.scope??"all",changedFiles=options?.changedFiles??[],_filesToCheck=filterByScope(workingDir,scope,changedFiles),profileResult=await _internals145.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,repoDefinedScriptsByEcosystem=new Map,repoScriptSkips=[],repoDeclaredEcosystems=new Set;for(let ecosystem of ECOSYSTEMS){if(!ecosystem.repoDefinedScripts)continue;let repoResult=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoResult.commands.length>0)repoDefinedScriptsByEcosystem.set(ecosystem.ecosystem,repoResult.commands);if(repoResult.hasScripts)repoDeclaredEcosystems.add(ecosystem.ecosystem);if(repoResult.skip)repoScriptSkips.push(repoResult.skip)}let filteredProfileCommands=profileCommands.filter((cmd)=>{return(PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[]).every((name)=>!repoDeclaredEcosystems.has(name))}),coveredEcosystems=new Set;for(let cmd of filteredProfileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...filteredProfileCommands],skipped=[...profileSkipped,...repoScriptSkips];for(let ecosystem of ECOSYSTEMS){if(!findBuildFiles(workingDir,ecosystem.buildFiles))continue;let repoScripts=repoDefinedScriptsByEcosystem.get(ecosystem.ecosystem);if(repoScripts&&repoScripts.length>0){for(let script of repoScripts)commands.push({ecosystem:ecosystem.ecosystem,command:script.command,cwd:workingDir,priority:script.priority});continue}if(repoDeclaredEcosystems.has(ecosystem.ecosystem))continue;if(coveredEcosystems.has(ecosystem.ecosystem)){skipped.push({ecosystem:ecosystem.ecosystem,reason:"Covered by profile detection"});continue}if(!checkToolchain(ecosystem.toolchainCommands)){skipped.push({ecosystem:ecosystem.ecosystem,code:"environment_unavailable",required_commands:ecosystem.toolchainCommands,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}let availableCommands=ecosystem.commands;for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>b.priority-a.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var SUPPORTED_NODE_PACKAGE_MANAGERS,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS=120,ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals145,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();init_command_resolution();SUPPORTED_NODE_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn"],ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:[...SUPPORTED_NODE_PACKAGE_MANAGERS],commands:[{command:"npm run build",priority:30},{command:"npm run typecheck",priority:20},{command:"npm run check",priority:10}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:20},{command:"cargo check",priority:10}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:10}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m build",priority:20},{command:"python -m py_compile",priority:10}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:10}]},{ecosystem:"java-gradle",buildFiles:["build.gradle","build.gradle.kts","gradle.properties"],toolchainCommands:["gradle","gradlew"],commands:[{command:process.platform==="win32"?"gradlew.bat build":"./gradlew build",priority:20},{command:"gradle build",priority:10}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:10}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:10}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart compile",priority:20},{command:"dart analyze",priority:10}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:20},{command:"cmake -B build && cmake --build build",priority:10}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:10}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["node"],javascript:["node"],python:["python"],rust:["rust"],go:["go"],java:["java-maven","java-gradle"],kotlin:["java-gradle"],csharp:["dotnet"],cpp:["cpp"],swift:["swift"],dart:["dart"],ruby:[],php:["php-composer"]},toolchainCache=new Map;_internals145={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,detectProjectLanguagesImpl:detectProjectLanguages,getLanguageProfileImpl:LANGUAGE_REGISTRY.get.bind(LANGUAGE_REGISTRY),spawnSyncImpl:bunSpawnSync};build_discovery=tool({description:"Discover build commands for various ecosystems in a project directory",args:{workingDir:tool.schema.string().describe("Directory to scan for build commands (defaults to current directory)"),scope:tool.schema.string().optional().describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changedFiles:tool.schema.array(tool.schema.string()).optional().describe('List of changed files when scope is "changed"')},async execute(args2,_context){let result=await discoverBuildCommands(args2.workingDir,{scope:args2.scope??"all",changedFiles:args2.changedFiles??[]});return JSON.stringify(result,null,2)}})});var init_tool_names=__esm(()=>{init_tool_metadata()});var exports_tool_doctor={};__export(exports_tool_doctor,{runToolDoctor:()=>runToolDoctor,getBinaryReadinessAdvisory:()=>getBinaryReadinessAdvisory,checkAgentToolMapAlignment:()=>checkAgentToolMapAlignment});function getRegisteredToolKeys(){return new Set(TOOL_NAME_SET)}function checkAgentToolMapAlignment(registeredKeys){let findings=[];for(let[agentName,tools]of Object.entries(AGENT_TOOL_MAP))for(let toolName of tools)if(!registeredKeys.has(toolName))findings.push({id:`agent-tool-map-mismatch-${agentName}-${toolName}`,title:"AGENT_TOOL_MAP alignment gap",description:`Tool "${toolName}" is assigned to agent "${agentName}" in AGENT_TOOL_MAP but is not a registered tool name. The agent will not be able to use this tool.`,severity:"error",path:`AGENT_TOOL_MAP.${agentName}`,currentValue:toolName,autoFixable:!1});return findings}function checkBinaryReadiness(){let findings=[];for(let{binary,language}of BINARY_CHECKLIST)if(!isCommandAvailable(binary))findings.push({id:`missing-binary-${binary}`,title:"Class 3 tool binary not found",description:`Binary "${binary}" is not available on PATH. ${language} linting will not be available. Install ${binary} to enable ${language} language support.`,severity:"warn",path:`toolchain.${binary}`,currentValue:void 0,autoFixable:!1});return findings}function getBinaryReadinessAdvisory(){let findings=checkBinaryReadiness();if(findings.length===0)return null;return["[PRE-FLIGHT ADVISORY] The following Class 3 tool binaries were not found on PATH at session start.","These tools will soft-skip at invocation. Plan tasks accordingly.",...findings.map((f)=>`- MISSING BINARY: ${f.currentValue??f.path?.split(".")[1]??"unknown"} — ${f.description}`)].join(`
2663
+ `)}async function handleDiagnoseCommand(directory,_args,sessionID){let diagnoseData=await getDiagnoseData(directory,sessionID);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals143,SWARM_DB_QUICK_CHECK_MAX_BYTES2=67108864,GIT_REPOSITORY_CHECK_TIMEOUT_MS=5000,GIT_REPOSITORY_CHECK_MAX_BUFFER_BYTES=65536;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_health();init_core_events();init_gate_bridge();init_manager2();init_action_circuit();init_state3();init_gate_evidence();init_learning_health();init_utils2();init_task_model_routing();init_manager();init_capability_probe();init_executor();init_skip_state();init_path_identity();init_effective_spec();init_state2();init_git_executable();init_coder_settlement();init_recovery_invocation();init_stage_a_repair();init_task_recovery_status();init_knowledge_diagnostics();init_swarm_residue();init_version_check();init_warning_buffer();({version:version4}=package_default),sandboxCapabilityProbe=new SandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS=["tree-sitter.wasm","tree-sitter-javascript.wasm","tree-sitter-typescript.wasm"],_internals143={detectSandboxCapability:()=>sandboxCapabilityProbe.detect(),getSandboxExecutor:getExecutor,execFileSync:(...args2)=>child_process8.execFileSync(...args2)}});var init_diagnose=__esm(()=>{init_diagnose_service()});var CONFIG_CONSUMERS;var init_consumers=__esm(()=>{CONFIG_CONSUMERS={$schema:{consumers:["src/services/config-doctor.ts:validateConfigKey"]},config_format_version:{consumers:["src/services/config-doctor.ts:validateConfigKey","src/services/config-doctor.ts:runConfigDoctor"]},preset:{consumers:["src/commands/council.ts:parseArgs","src/config/loader.ts:loadRawConfigFromPath","src/index.ts:initializeOpenCodeSwarm","src/tools/phase-complete/gates/final-review-gate.ts:runFinalReviewGate"]},agents:{consumers:["src/agents/index.ts:_swarmAgentsMap","src/commands/full-auto.ts:handleFullAutoCommand"]},default_agent:{consumers:["src/agents/index.ts:getAgentConfigs","src/services/model-preflight.ts:collectEnabledAgentModels","src/services/config-doctor.ts:validateConfigKey"]},auto_select_architect:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},swarms:{consumers:["src/agents/index.ts:createAgents","src/config/agent-model.ts:resolveAgentTarget","src/index.ts:initializeOpenCodeSwarm","src/review/runtime.ts:effectiveAgentConfig"]},max_iterations:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},pipeline:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/memory/embeddings/local-provider.ts:LocalEmbeddingProvider","src/memory/embeddings/reranker.ts:CrossEncoderReranker","src/memory/pii.ts:NerPiiDetector"]},phase_complete:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/tools/phase-complete.ts:executePhaseComplete","src/tools/plugin-registration.ts:buildPluginToolObject","src/services/config-doctor.ts:validateConfigKey"]},qa_retry_limit:{consumers:["src/agents/index.ts:createSwarmAgents","src/services/config-doctor.ts:validateConfigKey"]},execution_mode:{consumers:["src/agents/architect.ts:createArchitectAgent","src/agents/index.ts:createSwarmAgents","src/index.ts:initializeOpenCodeSwarm","src/plan/planning-profile.ts:resolveRepositoryDefaultPlanningProfile"]},inject_phase_reminders:{consumers:["src/hooks/pipeline-tracker.ts:createPipelineTrackerHook","src/services/config-doctor.ts:validateConfigKey"]},hooks:{consumers:["src/commands/registry.ts:handlePrFeedbackCommandWithTransition","src/hooks/agent-activity.ts:createAgentActivityHooks","src/hooks/compaction-customizer.ts:createCompactionCustomizerHook","src/hooks/delegation-tracker.ts:createDelegationTrackerHook"]},pr_review_resilience:{consumers:["src/tools/dispatch-lanes.ts:executeDispatchLanesAsync","src/services/config-doctor.ts:validateConfigKey"]},review_routing:{consumers:["src/background/stage-b-gates.ts:ingestBackgroundStageBCompletion","src/hooks/delegation-gate.ts:createDelegationGateHook","src/tools/update-task-status.ts:routeGateAllowsTask","src/services/config-doctor.ts:validateConfigKey"]},lane_liveness_watchdog:{consumers:["src/commands/registry.ts:handlePrFeedbackCommandWithTransition","src/tools/abort-pr-workflow.ts:executeAbortPrWorkflow","src/tools/complete-pr-workflow.ts:executeCompletePrWorkflow","src/services/config-doctor.ts:validateConfigKey"]},dispatch_protection:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},pr_review_legacy_transcript_compatibility:{consumers:["src/tools/dispatch-lanes.ts:launchAsyncLane","src/services/config-doctor.ts:validateConfigKey"]},gates:{consumers:["src/config/loader.ts:sanitizeGatesConfig","src/commands/qa-gates.ts:handleQaGatesCommand","src/commands/gate-audit.ts:parseArgs"]},context_budget:{consumers:["src/hooks/context-budget.ts:createContextBudgetHandler","src/hooks/final-context-accounting.ts:createFinalContextAccountingStep","src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/index.ts:initializeOpenCodeSwarm"]},pricing:{consumers:["src/background/delegation-lifecycle.ts:emitDelegationCostObservation","src/evaluation/ephemeral-agent-dispatcher.ts:unavailableCostFields","src/index.ts:emitPendingCostCorrection","src/services/cost-accounting.ts:extractCostEvidence"]},guardrails:{consumers:["src/config/loader.ts:buildConfigWithMeta","src/hooks/full-auto-permission.ts:createFullAutoPermissionHook","src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},watchdog:{consumers:["src/hooks/pr-workflow-gate.ts:evaluateLaneLivenessWatchdogEscalation","src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},self_review:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},auto_review:{consumers:["src/agents/index.ts:createSwarmAgents","src/index.ts:initializeOpenCodeSwarm","src/tools/phase-complete/gates/final-review-gate.ts:runFinalReviewGate","src/tools/plugin-registration.ts:buildPluginToolObject"]},tool_filter:{consumers:["src/agents/index.ts:getAgentConfigs","src/full-auto/policy.ts:resolveAgentCapabilityTools","src/services/config-doctor.ts:validateConfigKey"]},authority:{consumers:["src/hooks/delegation-gate/worktree-isolation.ts:maybeSelectRecoverableAuthority","src/hooks/delegation-gate/worktree-recovery-authority.ts:publishWorktreeRecoveryAuthorityUnlocked","src/index.ts:initializeOpenCodeSwarm","src/learning/provenance.ts:stampLearningProvenance"]},plan_cursor:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},context_map:{consumers:["src/hooks/context-capsule-inject.ts:createContextCapsuleInjectHook","src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},repo_graph:{consumers:["src/evaluation/retrieval-quality.ts:materializeDisposableWorkspace","src/hooks/repo-graph-injection.ts:buildLaneOrientationBlock","src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/index.ts:initializeOpenCodeSwarm"]},evidence:{consumers:["src/background/candidate-parser.ts:parseText","src/background/pr-review-trigger-contract.ts:buildPrReviewTriggerReceiptV2","src/background/stage-b-gates.ts:resolveBackgroundStageBRoute","src/commands/archive.ts:handleArchiveCommand"]},summaries:{consumers:["src/commands/close/orchestrator.ts:handleCloseCommand","src/index.ts:createSwarmCommandSystemRuleHook","src/services/config-doctor.ts:validateConfigKey"]},retention:{consumers:["src/commands/close/orchestrator.ts:handleCloseCommand","src/index.ts:initializeOpenCodeSwarm","src/training/vault.ts:sweepTrainingVaultExpiry","src/services/config-doctor.ts:validateConfigKey"]},review_passes:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},adversarial_detection:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},adversarial_testing:{consumers:["src/agents/index.ts:createSwarmAgents","src/services/config-doctor.ts:validateConfigKey"]},integration_analysis:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},docs:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},design_docs:{consumers:["src/agents/index.ts:createSwarmAgents","src/commands/design-docs.ts:handleDesignDocsCommand","src/services/model-preflight.ts:collectConfiguredAgentModels","src/tools/phase-complete.ts:executePhaseComplete"]},speckit_checkoff:{consumers:["src/sdd/speckit-checkoff.ts:maybePropagateSpeckitCheckoff","src/services/config-doctor.ts:validateConfigKey"]},git:{consumers:["src/config/loader.ts:exposedGitBinary"]},ui_review:{consumers:["src/agents/index.ts:createSwarmAgents","src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/model-preflight.ts:collectConfiguredAgentModels","src/services/config-doctor.ts:validateConfigKey"]},compaction_advisory:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/config-doctor.ts:validateConfigKey"]},lint:{consumers:["src/agents/project-context.ts:selectLintCommand","src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/services/trajectory-cluster.ts:motifPredicate","src/tools/pre-check-batch.ts:serializePreCheckResult"]},secretscan:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/tools/secretscan.ts:runSecretscan","src/services/config-doctor.ts:validateConfigKey"]},checkpoint:{consumers:["src/background/delegation-health.ts:writeDelegationHealthArtifact","src/hooks/knowledge-receipt-ledger.ts:validateRecordPayload","src/plan/auto-checkpoint.ts:maybeSaveAutoCheckpoint","src/services/status-service.ts:formatStatusMarkdown"]},apply_patch:{consumers:["src/tools/apply-patch.ts:isUnsupportedPatchFormat","src/services/config-doctor.ts:validateConfigKey"]},automation:{consumers:["src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/index.ts:initializeOpenCodeSwarm","src/services/status-service.ts:collectDecisionDriftSnapshot","src/services/config-doctor.ts:validateConfigKey"]},knowledge:{consumers:["src/commands/close/orchestrator.ts:handleCloseCommand","src/commands/consolidate.ts:handleConsolidateCommand","src/commands/curate.ts:handleCurateCommand","src/commands/knowledge.ts:authorizeUserCuration"]},memory:{consumers:["src/agents/index.ts:createSwarmAgents","src/commands/close/orchestrator.ts:handleCloseCommand","src/commands/memory-link.ts:handleMemoryLinkCommand","src/commands/memory.ts:handleMemoryConsolidationLogCommand"]},forge:{consumers:["src/providers/forge-provider.ts:resolveForgeContextFromPluginConfig"]},observability:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},learning:{consumers:["src/hooks/knowledge-dedup-sweep.ts:sweepActiveNearDuplicates","src/hooks/system-enhancer.ts:createSystemEnhancerHook","src/index.ts:initializeOpenCodeSwarm","src/memory/config.ts:resolveMemoryConfig"]},consensus:{consumers:["src/tools/consensus-mine.ts:consensus_mine","src/services/config-doctor.ts:validateConfigKey"]},curator:{consumers:["src/hooks/phase-monitor.ts:createPhaseMonitorHook","src/services/diagnose-service.ts:checkCurator"]},architectural_supervision:{consumers:["src/agents/index.ts:createSwarmAgents","src/hooks/phase-monitor.ts:createPhaseMonitorHook","src/tools/phase-complete/gates/architecture-supervisor-gate.ts:runArchitectureSupervisorGate","src/tools/phase-complete.ts:executePhaseComplete"]},knowledge_application:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},skillPropagation:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},skill_improver:{consumers:["src/commands/close/finalize-stage.ts:runFinalizeStage","src/commands/consolidate.ts:handleConsolidateCommand","src/index.ts:initializeOpenCodeSwarm","src/tools/phase-complete.ts:executePhaseComplete"]},harness_evolution:{consumers:["src/commands/harness.ts:getHarnessConfig","src/services/config-doctor.ts:validateConfigKey"]},harness_opt:{consumers:["src/commands/harness-opt.ts:readHarnessOptConfigFromProject","src/services/config-doctor.ts:validateConfigKey"]},spec_writer:{consumers:["src/tools/spec-write.ts:MAX_SPEC_BYTES"]},tool_output:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},slop_detector:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},todo_gate:{consumers:["src/tools/check-gate-status.ts:readEvidenceFile","src/tools/phase-complete/gates/todo-gate.ts:runTodoGateGate","src/services/config-doctor.ts:validateConfigKey"]},incremental_verify:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},compaction_service:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},prm:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},council:{consumers:["src/agents/index.ts:createSwarmAgents","src/commands/pr-review.ts:parseArgs","src/full-auto/policy.ts:resolveAgentCapabilityTools","src/gate-evidence.ts:clearWorkflowGateProof"]},parallelization:{inert:"PR-1 dark foundation — no production code path branches on enabled=true yet, so setting this key has no runtime effect. For live parallel dispatch use the plan execution_profile (parallelization_enabled, max_concurrent_tasks, set per-plan by the architect; see /swarm concurrency)."},worktree:{consumers:["src/background/completion-observer.ts:createBackgroundCompletionObserver","src/background/pending-delegations.ts:isUnsettledWorktreeOwner","src/config/worktree-isolation-config.ts:resolveWorktreeIsolationConfig","src/hooks/delegation-gate/worktree-collision-ownership.ts:classifyRecord"]},turbo:{consumers:["src/agents/index.ts:createSwarmAgents","src/commands/epic.ts:renderCalibration","src/commands/turbo.ts:handleTurboCommand","src/config/worktree-isolation-config.ts:resolveWorktreeIsolationConfig"]},turbo_mode:{consumers:["src/state.ts:resolveInitialTurboMode","src/services/config-doctor.ts:validateConfigKey"]},quiet:{consumers:["src/agents/index.ts:createSwarmAgents","src/hooks/skill-injection.ts:SKILL_INJECTION_TOP_N","src/index.ts:initializeOpenCodeSwarm","src/utils/gitignore-warning.ts:ensureSwarmGitExcluded"]},version_check:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},full_auto:{consumers:["src/commands/full-auto.ts:handleFullAutoCommand","src/config/loader.ts:rawFullAutoLocked","src/full-auto/cadence.ts:configCadence","src/hooks/full-auto-delegation.ts:scanForProtectedPaths"]},pr_feedback_loop:{consumers:["src/background/pr-feedback-loop-runtime.ts:isPrFeedbackLoopEnabled","src/background/pr-feedback-loop.ts:claimAndProcessPrFeedbackEventUnlocked","src/services/config-doctor.ts:validateConfigKey"]},pr_monitor:{consumers:["src/background/pr-feedback-loop-runtime.ts:isPrFeedbackLoopEnabled","src/commands/pr-subscribe.ts:handlePrSubscribeCommand","src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]},external_skills:{consumers:["src/agents/index.ts:createSwarmAgents","src/full-auto/policy.ts:resolveAgentCapabilityTools"]},skills:{consumers:["src/agents/index.ts:createSwarmAgents","src/config/lane-permissions.ts:LastWinsRuleMap","src/full-auto/policy.ts:resolveAgentCapabilityTools","src/services/skill-improver.ts:buildUserPrompt"]},skill_opt:{consumers:["src/commands/skill-opt.ts:readSkillOptConfigFromProject","src/services/config-doctor.ts:validateConfigKey"]},dashboard:{consumers:["src/index.ts:initializeOpenCodeSwarm","src/services/config-doctor.ts:validateConfigKey"]}}});var exports_config_doctor={};__export(exports_config_doctor,{writeDoctorArtifact:()=>writeDoctorArtifact,writeBackupArtifact:()=>writeBackupArtifact,shouldRunOnStartup:()=>shouldRunOnStartup,runConfigDoctorWithFixes:()=>runConfigDoctorWithFixes,runConfigDoctor:()=>runConfigDoctor,restoreFromBackup:()=>restoreFromBackup,resolvePlanParallelizationFlag:()=>resolvePlanParallelizationFlag,removeStraySwarmDir:()=>removeStraySwarmDir,readDoctorArtifact:()=>readDoctorArtifact,getConfigPaths:()=>getConfigPaths,detectStraySwarmDirs:()=>detectStraySwarmDirs,createConfigBackup:()=>createConfigBackup,collectLeanTurboGateSatisfiabilityFindings:()=>collectLeanTurboGateSatisfiabilityFindings,applySafeAutoFixes:()=>applySafeAutoFixes,_internals:()=>_internals144,LEAN_TURBO_GATE_PRODUCERS:()=>LEAN_TURBO_GATE_PRODUCERS,DEFAULT_FLIPS:()=>DEFAULT_FLIPS,CURRENT_CONFIG_FORMAT_VERSION:()=>CURRENT_CONFIG_FORMAT_VERSION});import*as crypto9 from"node:crypto";import*as fs97 from"node:fs";import*as os24 from"node:os";import*as path181 from"node:path";function levenshteinDistance(a,b){let al=a.length,bl=b.length,matrix=[];for(let i=0;i<=al;i++)matrix[i]=[i];for(let j=0;j<=bl;j++)matrix[0][j]=j;for(let i=1;i<=al;i++)for(let j=1;j<=bl;j++){let cost=a[i-1]===b[j-1]?0:1;matrix[i][j]=Math.min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost)}return matrix[al][bl]}function emitObjectTypeMismatch(key2,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key2}-type`,title:`Invalid ${key2} type`,description:`"${key2}" must be an object, got ${typeof value}`,severity:"error",path:key2,currentValue:value,autoFixable:!1})}function isPlainObject5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectRawInertKeyFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),seen=new Set;for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;for(let key2 of Object.keys(raw)){if(seen.has(key2))continue;let declaration=CONFIG_CONSUMERS[key2];if(!declaration||!("inert"in declaration))continue;seen.add(key2),findings.push({id:"inert-config-key",title:`Inert config key: ${key2}`,description:`Config key "${key2}" (in ${configPath}) is declared inert: ${declaration.inert}`,severity:"warn",path:key2,currentValue:raw[key2],autoFixable:!1})}}catch{}}return findings}function collectRawCouncilPolicyFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.council===void 0)continue;if(!isPlainObject5(raw.council))continue;let council=raw.council;if("parallelTimeoutMs"in council)findings.push({id:"council-parallel-timeout-deprecated",title:"Deprecated and inert: council.parallelTimeoutMs",description:'Config field "council.parallelTimeoutMs" (in '+configPath+") is deprecated and inert: no runtime consumer exists and no timeout is enforced. It is accepted only for parse compatibility. Remove the key — dispatch timeouts are governed by the agent host. The field is scheduled for removal in a future release.",severity:"warn",path:"council.parallelTimeoutMs",currentValue:council.parallelTimeoutMs,autoFixable:!1});if("escalateOnMaxRounds"in council)findings.push({id:"council-escalate-inert",title:"Inert: council.escalateOnMaxRounds",description:'Config field "council.escalateOnMaxRounds" (in '+configPath+") is set, but the handler/webhook remains INERT in this release: no handler, webhook, or outbound execution exists or was added (issue #1650). Max-rounds exhaustion emits a durable structured event (.swarm/council/events/max-rounds-exhaustion.jsonl) and a user escalation message instead; the run stays fail-closed. Wiring real outbound escalation requires a separate security review.",severity:"warn",path:"council.escalateOnMaxRounds",currentValue:"[redacted: handler/webhook strings are never echoed]",autoFixable:!1});if(isPlainObject5(council.finalCompletionPolicy)&&council.finalCompletionPolicy.mode==="quorum")findings.push({id:"council-final-quorum-weaker",title:'council.finalCompletionPolicy.mode "quorum" weakens the strict final council',description:"Final-council completion is configured in quorum mode (in "+configPath+"): a bounded minimum of distinct canonical members can accept the project instead of the strict default (all five canonical roles, zero absentees). This is weaker than the strict default. Any change to this policy invalidates previously accepted final-council evidence.",severity:"warn",path:"council.finalCompletionPolicy",currentValue:council.finalCompletionPolicy,autoFixable:!1})}catch{}}return findings}function collectLeanTurboGateSatisfiabilityFindings(config3,registeredToolNames=TOOL_NAME_SET){let findings=[],lean=config3?.turbo?.lean;for(let entry of LEAN_TURBO_GATE_PRODUCERS){let enabled=lean?.[entry.gate]??!0;if(!enabled)continue;if(registeredToolNames.has(entry.producerTool))continue;findings.push({id:`lean-turbo-gate-unsatisfiable-${entry.gate}`,title:`turbo.lean.${entry.gate} gate has no registered producer tool`,description:`turbo.lean.${entry.gate} is enabled (default true), but its evidence producer tool "${entry.producerTool}" is not registered, so the gate that reads ${entry.evidencePathConvention} is structurally unsatisfiable in production and Lean Turbo phase_complete would dead-end. Re-register the producer tool or disable the gate (issue #2470 / #2007).`,severity:"error",path:`turbo.lean.${entry.gate}`,currentValue:enabled,autoFixable:!1})}return findings}function collectRawGatesConfigFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw)||raw.gates===void 0)continue;if(!isPlainObject5(raw.gates)){findings.push({id:"invalid-gates-config",title:"Invalid gates config",description:`"gates" in ${configPath} must be an object. The loader ignores that section and keeps other valid config sections active.`,severity:"error",path:"gates",currentValue:raw.gates,autoFixable:!1});continue}for(let[sectionName,sectionValue]of Object.entries(raw.gates)){let schema=GateConfigSchema.shape[sectionName];if(!schema){findings.push({id:"unknown-gates-section",title:"Unknown gates config section",description:`Unknown gates section "gates.${sectionName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1});continue}let knownFields=GATE_CONFIG_KNOWN_SECTION_KEYS[sectionName];if(knownFields&&isPlainObject5(sectionValue)){let knownFieldSet=new Set(knownFields);for(let fieldName of Object.keys(sectionValue))if(!knownFieldSet.has(fieldName))findings.push({id:"unknown-gates-key",title:"Unknown gates config key",description:`Unknown gates key "gates.${sectionName}.${fieldName}" in ${configPath} is ignored by the loader.`,severity:"warn",path:`gates.${sectionName}.${fieldName}`,currentValue:sectionValue[fieldName],autoFixable:!1})}if(!schema.safeParse(sectionValue).success)findings.push({id:"invalid-gates-section",title:"Invalid gates config section",description:`"gates.${sectionName}" in ${configPath} failed validation. The loader uses defaults for that gate section and keeps other valid config sections active.`,severity:"error",path:`gates.${sectionName}`,currentValue:sectionValue,autoFixable:!1})}}catch{}}return findings}function collectRawStrictSectionFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;let seen=new Set;for(let issue3 of parsed.error.issues){if(issue3.code!=="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let keys=issue3.keys??[];for(let key2 of keys){let dotted2=[...issue3.path.map(String),key2].join(".");if(seen.has(dotted2))continue;seen.add(dotted2),findings.push({id:"unknown-config-key",title:"Unknown config key",description:`Unrecognized key "${dotted2}" in ${configPath} is ignored by the loader (the rest of your config is preserved). Fix or remove it.`,severity:"warn",path:dotted2,currentValue:void 0,autoFixable:!1})}}}catch{}}return findings}function getRawValueAtPath(raw,issuePath){let node=raw;for(let seg of issuePath){if(node===null||typeof node!=="object")return;node=node[seg]}return node}function collectRawValueConstraintFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory),applyTargetPath=fs97.existsSync(projectConfigPath)?projectConfigPath:userConfigPath,seen=new Set,filesInApplyOrder=applyTargetPath===projectConfigPath?[projectConfigPath,userConfigPath]:[userConfigPath,projectConfigPath];for(let configPath of filesInApplyOrder){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf-8"));if(!isPlainObject5(raw))continue;let parsed=PluginConfigSchema.safeParse(raw);if(parsed.success)continue;for(let issue3 of parsed.error.issues){if(issue3.code==="unrecognized_keys")continue;if(issue3.path[0]==="gates")continue;let dotted2=issue3.path.map(String).join("."),dedupeKey=`${dotted2}|${issue3.code}`;if(seen.has(dedupeKey))continue;seen.add(dedupeKey);let current=getRawValueAtPath(raw,issue3.path);if(issue3.code==="too_big"&&dotted2.endsWith("fallback_models")&&Array.isArray(current)&&current.length>FALLBACK_MODELS_MAX){let trimmed=current.slice(0,FALLBACK_MODELS_MAX),dropped=current.slice(FALLBACK_MODELS_MAX).map(String),inApplyTarget=configPath===applyTargetPath,drop=`${dropped.length} entr${dropped.length===1?"y":"ies"}`;findings.push({id:"fallback-models-too-many",title:"Too many fallback models",description:`"${dotted2}" in ${configPath} lists ${current.length} models; the maximum is ${FALLBACK_MODELS_MAX}. A config that fails validation is discarded in favor of safe defaults. `+(inApplyTarget?`Run /swarm config doctor --fix to trim to the first ${FALLBACK_MODELS_MAX} (drops ${drop}: ${dropped.join(", ")}), or edit the file yourself.`:`Remove ${drop} from that file (would drop: ${dropped.join(", ")}).`),severity:"error",path:dotted2,currentValue:current,autoFixable:inApplyTarget,proposedFix:{type:"update",path:dotted2,value:trimmed,description:`Trim "${dotted2}" to the first ${FALLBACK_MODELS_MAX} models`,risk:"low",lossy:!0}});continue}findings.push({id:"invalid-config-value",title:"Invalid config value",description:`"${dotted2||"(root)"}" in ${configPath} is invalid: ${issue3.message}. A config that fails validation is discarded in favor of safe defaults until this is fixed.`,severity:"error",path:dotted2,currentValue:current,autoFixable:!1})}}catch{}}return findings}function collectRawAutoReviewCompatibilityFindings(directory){let findings=[],{userConfigPath,projectConfigPath}=getConfigPaths(directory);for(let configPath of[userConfigPath,projectConfigPath]){if(!fs97.existsSync(configPath))continue;try{if(fs97.statSync(configPath).size>CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES)continue;let raw=JSON.parse(fs97.readFileSync(configPath,"utf8"));if(!isPlainObject5(raw)||!isPlainObject5(raw.auto_review))continue;let autoReview=raw.auto_review;if(autoReview.structured_findings===!1&&isPlainObject5(autoReview.final_review)&&autoReview.final_review.mode==="gate"){findings.push({id:"invalid-auto-review-gate-compatibility",title:"Invalid auto-review gate configuration",description:'auto_review.final_review.mode="gate" requires auto_review.structured_findings=true so gate evidence is machine-verifiable.',severity:"error",path:"auto_review.structured_findings",currentValue:!1,autoFixable:!1});break}}catch{}}return findings}async function resolvePlanParallelizationFlag(directory){let plan=null;try{plan=await _internals144.loadPlanJsonOnly(directory)}catch{return null}if(!plan?.execution_profile)return null;return plan.execution_profile.parallelization_enabled===!0}function emitWorktreeIsolationLayeringAdvisory(config3,findings,planParallelizationEnabled){let worktreePolicy=config3.worktree?.policy??"auto";if(planParallelizationEnabled===!0&&worktreePolicy!=="disabled")findings.push({id:"worktree-isolation-baseline-active",title:"Worktree isolation is already active for standard parallel coders",description:"Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",severity:"warn",path:"worktree.policy",currentValue:worktreePolicy,autoFixable:!1})}function getUserConfigDir3(){return process.env.XDG_CONFIG_HOME||path181.join(os24.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path181.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path181.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto9.createHash("sha256").update(content,"utf-8").digest("hex")}function isValidConfigPath(configPath,directory){let pathParts=configPath.replace(/\\/g,"/").split("/");for(let part of pathParts)if(part===".."||part===""){if(part==="..")return!1}let{userConfigPath,projectConfigPath}=getConfigPaths(directory);try{let resolvedConfig=path181.resolve(configPath),resolvedUser=path181.resolve(userConfigPath),resolvedProject=path181.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs97.existsSync(resolvedConfig)){if(fs97.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs97.writeFileSync(tmpPath,content,"utf-8");try{fs97.renameSync(tmpPath,filePath)}catch{try{fs97.unlinkSync(filePath)}catch{}fs97.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs97.existsSync(projectConfigPath))try{content=fs97.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs97.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs97.readFileSync(userConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] user config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}}if(content===null)return null;return{createdAt:Date.now(),configPath,content,contentHash:computeHash(content)}}function writeBackupArtifact(directory,backup){let swarmDir=path181.join(directory,".swarm");if(!fs97.existsSync(swarmDir))fs97.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path181.join(swarmDir,backupFilename),artifact={createdAt:backup.createdAt,configPath:backup.configPath,contentHash:backup.contentHash,content:backup.content,preview:backup.content.substring(0,500)+(backup.content.length>500?"...":"")};return atomicWriteFileSync(backupPath,JSON.stringify(artifact,null,2)),backupPath}function restoreFromBackup(backupPath,directory){if(!fs97.existsSync(backupPath))return null;let swarmDir=path181.resolve(directory,".swarm"),resolvedBackup=path181.resolve(backupPath);if(!isCanonicalPathWithinRoot(resolvedBackup,swarmDir))return null;try{let artifact=JSON.parse(fs97.readFileSync(backupPath,"utf-8"));if(!artifact.content||!artifact.configPath||!artifact.contentHash)return null;if(!isValidConfigPath(artifact.configPath,directory))return null;let computedHash=computeHash(artifact.content),storedHash=artifact.contentHash;if(!/^\d+$/.test(storedHash)&&computedHash!==storedHash)return null;log("[ConfigDoctor] Warning: restoring from backup with legacy numeric hash (pre-SHA-256). Consider re-backing up.",{});let targetPath=artifact.configPath,targetDir=path181.dirname(targetPath);if(!fs97.existsSync(targetDir))fs97.mkdirSync(targetDir,{recursive:!0});return atomicWriteFileSync(targetPath,artifact.content),targetPath}catch{return null}}function readConfigFromFile(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent=null;if(fs97.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs97.readFileSync(projectConfigPath,"utf-8");else if(fs97.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs97.readFileSync(userConfigPath,"utf-8");if(configContent===null)return null;try{return{config:JSON.parse(configContent),configPath}}catch(error93){return log(`[ConfigDoctor] Failed to parse config file: ${configPath}`,{error:error93 instanceof Error?error93.message:String(error93)}),null}}function validateConfigKey(path182,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path182===depPath&&!depInfo.isDefaultValue(value))findings.push({id:"deprecated-field",title:`Deprecated config field: ${depPath}`,description:`Config field "${depPath}" is deprecated. Replacement: ${depInfo.replacement}.`,severity:"info",path:depPath,currentValue:value,autoFixable:!1});switch(path182){case"agents":{if(value!==void 0)findings.push({id:"deprecated-agents-config",title:"Deprecated agents configuration",description:'The "agents" field is deprecated. Use "swarms" instead for multi-swarm support.',severity:"warn",path:"agents",currentValue:value,autoFixable:!1,proposedFix:{type:"remove",path:"agents",description:"Remove deprecated agents config - use swarms instead",risk:"low"}});break}case"config_format_version":{if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<0)findings.push({id:"type-mismatch",title:`Config field "${path182}" has wrong type`,description:`Expected non-negative integer, got ${typeof value==="number"?Number.isInteger(value)?value:`${value} (non-integer)`:typeof value}`,severity:"error",path:path182,currentValue:value,autoFixable:!1});break}case"preset":{if(value!=="default"&&value!=="conservative")findings.push({id:"type-mismatch",title:`Config field "${path182}" has wrong type`,description:`Expected "default" or "conservative", got ${JSON.stringify(value)}`,severity:"error",path:path182,currentValue:value,autoFixable:!1});break}case"guardrails.enabled":{if(value===!1)findings.push({id:"guardrails-disabled",title:"Guardrails disabled",description:"Guardrails have been explicitly disabled. This removes safety limits.",severity:"error",path:"guardrails.enabled",currentValue:value,autoFixable:!1});break}case"guardrails.profiles":{let profiles=value;if(profiles){let validAgents=new Set(ALL_AGENT_NAMES);for(let[agentName,profile]of Object.entries(profiles))if(!validAgents.has(agentName))findings.push({id:"unknown-agent-profile",title:"Unknown agent profile",description:`Profile for unknown agent "${agentName}" will be ignored.`,severity:"info",path:`guardrails.profiles.${agentName}`,currentValue:profile,autoFixable:!0,proposedFix:{type:"remove",path:`guardrails.profiles.${agentName}`,description:`Remove unknown agent profile "${agentName}"`,risk:"low"}})}break}case"automation.mode":{let validModes=["manual","hybrid","auto"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-automation-mode",title:"Invalid automation mode",description:`Invalid automation mode "${value}". Valid: ${validModes.join(", ")}`,severity:"error",path:"automation.mode",currentValue:value,autoFixable:!0,proposedFix:{type:"update",path:"automation.mode",value:"manual",description:'Reset to safe default "manual"',risk:"low"}});break}case"automation.capabilities":{let caps=value;if(caps){let capabilityNames=["plan_sync","phase_preflight","config_doctor_on_startup","evidence_auto_summaries","decision_drift_detection"];for(let[name,capValue]of Object.entries(caps))if(capabilityNames.includes(name)&&typeof capValue!=="boolean")findings.push({id:"invalid-capability-type",title:"Invalid capability type",description:`Capability "${name}" must be boolean, got ${typeof capValue}`,severity:"error",path:`automation.capabilities.${name}`,currentValue:capValue,autoFixable:!0,proposedFix:{type:"update",path:`automation.capabilities.${name}`,value:!1,description:`Reset capability "${name}" to false`,risk:"low"}})}break}case"hooks":{if(emitObjectTypeMismatch("hooks",value,findings),value!==void 0&&typeof value==="object"&&!Array.isArray(value)&&value!==null){let hooks2=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks2))if(!validHooks.includes(hookName))findings.push({id:"unknown-hook-field",title:"Unknown hook configuration",description:`Unknown hook "${hookName}" will be ignored.`,severity:"info",path:`hooks.${hookName}`,currentValue:hooks2[hookName],autoFixable:!0,proposedFix:{type:"remove",path:`hooks.${hookName}`,description:`Remove unknown hook "${hookName}"`,risk:"low"}})}break}case"max_iterations":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-iterations",title:"max_iterations out of bounds",description:`max_iterations must be 1-10, got ${numValue}`,severity:"error",path:"max_iterations",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"max_iterations",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"qa_retry_limit":{let numValue=value;if(typeof numValue==="number"){if(numValue<1||numValue>10)findings.push({id:"out-of-bounds-retry-limit",title:"qa_retry_limit out of bounds",description:`qa_retry_limit must be 1-10, got ${numValue}`,severity:"error",path:"qa_retry_limit",currentValue:numValue,autoFixable:!0,proposedFix:{type:"update",path:"qa_retry_limit",value:Math.max(1,Math.min(10,numValue)),description:"Clamp to valid range 1-10",risk:"low"}})}break}case"swarms":{if(value!==void 0){if(typeof value!=="object"||Array.isArray(value)||value===null){findings.push({id:"invalid-swarms-type",title:"Invalid swarms type",description:`"swarms" must be an object, got ${typeof value}`,severity:"error",path:"swarms",currentValue:value,autoFixable:!1});break}let swarms=value;if(Object.keys(swarms).length===0)findings.push({id:"empty-swarms",title:"Empty swarms configuration",description:'The "swarms" field is an empty object. No swarm configurations are defined.',severity:"info",path:"swarms",autoFixable:!1});for(let swarmId of Object.keys(swarms))if(swarmId.includes("..")||swarmId.includes("/")||swarmId.includes("\\")||swarmId.includes("\x00"))findings.push({id:"swarm-id-path-traversal",title:"Path traversal in swarm ID",description:`Swarm ID "${swarmId}" contains path traversal characters.`,severity:"error",path:`swarms.${swarmId}`,autoFixable:!1});let validAgents=new Set(ALL_AGENT_NAMES);for(let[swarmId,swarmConfig]of Object.entries(swarms)){let swarm=swarmConfig;if(swarm.agents&&typeof swarm.agents==="object")for(let[agentName]of Object.entries(swarm.agents)){let baseName=stripKnownSwarmPrefix(agentName);if(baseName!==agentName&&agentName.startsWith(`${swarmId}_`)&&validAgents.has(baseName))findings.push({id:"prefixed-swarm-agent-override",title:"Prefixed agent override is ignored",description:`Agent "${agentName}" in swarm "${swarmId}" uses a generated agent name. Per-swarm overrides must use the canonical key "${baseName}", e.g. "swarms.${swarmId}.agents.${baseName}.model". Otherwise the override is ignored and the agent falls back to its default model.`,severity:"warn",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1});else if(!validAgents.has(baseName))findings.push({id:"unknown-swarm-agent",title:"Unknown agent in swarm",description:`Agent "${agentName}" in swarm "${swarmId}" may not be recognized.`,severity:"info",path:`swarms.${swarmId}.agents.${agentName}`,currentValue:swarm.agents[agentName],autoFixable:!1})}}}break}case"default_agent":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-default_agent-type",title:"Invalid default_agent type",description:`"default_agent" must be a string, got ${typeof value}`,severity:"error",path:"default_agent",currentValue:value,autoFixable:!1});break}case"auto_select_architect":{if(value!==void 0&&typeof value!=="boolean"&&typeof value!=="string")findings.push({id:"invalid-auto_select_architect-type",title:"Invalid auto_select_architect type",description:`"auto_select_architect" must be a boolean or string, got ${typeof value}`,severity:"error",path:"auto_select_architect",currentValue:value,autoFixable:!1});break}case"pipeline":{emitObjectTypeMismatch("pipeline",value,findings);break}case"harness_evolution":{emitObjectTypeMismatch("harness_evolution",value,findings);break}case"harness_opt":{emitObjectTypeMismatch("harness_opt",value,findings);break}case"phase_complete":{emitObjectTypeMismatch("phase_complete",value,findings);break}case"execution_mode":{let validModes=["strict","balanced","fast"];if(value!==void 0&&!validModes.includes(value))findings.push({id:"invalid-execution_mode-type",title:"Invalid execution_mode",description:`"execution_mode" must be one of: ${validModes.join(", ")}, got "${value}"`,severity:"error",path:"execution_mode",currentValue:value,autoFixable:!1});break}case"inject_phase_reminders":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-inject_phase_reminders-type",title:"Invalid inject_phase_reminders type",description:`"inject_phase_reminders" must be a boolean, got ${typeof value}`,severity:"error",path:"inject_phase_reminders",currentValue:value,autoFixable:!1});break}case"gates":{emitObjectTypeMismatch("gates",value,findings);break}case"context_budget":{emitObjectTypeMismatch("context_budget",value,findings);break}case"pricing":{emitObjectTypeMismatch("pricing",value,findings);break}case"guardrails":{emitObjectTypeMismatch("guardrails",value,findings);break}case"watchdog":{emitObjectTypeMismatch("watchdog",value,findings);break}case"self_review":{emitObjectTypeMismatch("self_review",value,findings);break}case"tool_filter":{emitObjectTypeMismatch("tool_filter",value,findings);break}case"authority":{emitObjectTypeMismatch("authority",value,findings);break}case"plan_cursor":{emitObjectTypeMismatch("plan_cursor",value,findings);break}case"context_map":{emitObjectTypeMismatch("context_map",value,findings);break}case"evidence":{emitObjectTypeMismatch("evidence",value,findings);break}case"summaries":{emitObjectTypeMismatch("summaries",value,findings);break}case"auto_review":{emitObjectTypeMismatch("auto_review",value,findings);break}case"repo_graph":{emitObjectTypeMismatch("repo_graph",value,findings);break}case"retention":{emitObjectTypeMismatch("retention",value,findings);break}case"review_passes":{emitObjectTypeMismatch("review_passes",value,findings);break}case"adversarial_detection":{emitObjectTypeMismatch("adversarial_detection",value,findings);break}case"adversarial_testing":{emitObjectTypeMismatch("adversarial_testing",value,findings);break}case"integration_analysis":{emitObjectTypeMismatch("integration_analysis",value,findings);break}case"docs":{emitObjectTypeMismatch("docs",value,findings);break}case"forge":{emitObjectTypeMismatch("forge",value,findings);break}case"design_docs":{emitObjectTypeMismatch("design_docs",value,findings);break}case"git":{emitObjectTypeMismatch("git",value,findings);break}case"git.binary":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-git-binary-type",title:"Invalid git.binary type",description:`"git.binary" must be a string, got ${typeof value}`,severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});else if(typeof value==="string"&&value.trim()==="")findings.push({id:"empty-git-binary",title:"Empty git.binary",description:'"git.binary" is blank, so no git executable is named. Remove the key to fall back to the default `git` lookup, or set it to a real git executable path.',severity:"error",path:"git.binary",currentValue:value,autoFixable:!1});break}case"ui_review":{emitObjectTypeMismatch("ui_review",value,findings);break}case"compaction_advisory":{emitObjectTypeMismatch("compaction_advisory",value,findings);break}case"lint":{emitObjectTypeMismatch("lint",value,findings);break}case"secretscan":{emitObjectTypeMismatch("secretscan",value,findings);break}case"checkpoint":{emitObjectTypeMismatch("checkpoint",value,findings);break}case"apply_patch":{emitObjectTypeMismatch("apply_patch",value,findings);break}case"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",value,findings);break}case"observability":{if(emitObjectTypeMismatch("observability",value,findings),typeof value==="object"&&value!==null&&!Array.isArray(value)){let exportCfg=value.export;if(typeof exportCfg==="object"&&exportCfg!==null&&exportCfg.enabled===!0){let endpoint=exportCfg.endpoint,problem=null;if(typeof endpoint!=="string"||endpoint.length===0)problem="observability.export.enabled is true but endpoint is empty — the exporter stays disabled until an endpoint is configured.";else try{let url3=new URL(endpoint),host=url3.hostname.replace(/^\[|\]$/g,""),isLoopback=host==="localhost"||host==="127.0.0.1"||host==="::1";if(url3.protocol!=="https:"&&!isLoopback)problem="observability.export.endpoint uses plain http: for a non-loopback host — exported telemetry would travel unencrypted; use https: outside local test collectors."}catch{problem="observability.export.endpoint is not a valid URL — the exporter stays disabled."}if(problem!==null)findings.push({id:"observability-export-endpoint-policy",title:"OTLP export endpoint policy",description:problem,severity:"warn",path:"observability.export.endpoint",autoFixable:!1})}}break}case"learning":{emitObjectTypeMismatch("learning",value,findings);break}case"consensus":{emitObjectTypeMismatch("consensus",value,findings);break}case"curator":{emitObjectTypeMismatch("curator",value,findings);break}case"architectural_supervision":{emitObjectTypeMismatch("architectural_supervision",value,findings);break}case"knowledge_application":{emitObjectTypeMismatch("knowledge_application",value,findings);break}case"skillPropagation":{emitObjectTypeMismatch("skillPropagation",value,findings);break}case"skill_improver":{emitObjectTypeMismatch("skill_improver",value,findings);break}case"skills":{emitObjectTypeMismatch("skills",value,findings);break}case"spec_writer":{emitObjectTypeMismatch("spec_writer",value,findings);break}case"tool_output":{emitObjectTypeMismatch("tool_output",value,findings);break}case"slop_detector":{emitObjectTypeMismatch("slop_detector",value,findings);break}case"todo_gate":{emitObjectTypeMismatch("todo_gate",value,findings);break}case"incremental_verify":{emitObjectTypeMismatch("incremental_verify",value,findings);break}case"compaction_service":{emitObjectTypeMismatch("compaction_service",value,findings);break}case"prm":{emitObjectTypeMismatch("prm",value,findings);break}case"council":{emitObjectTypeMismatch("council",value,findings);break}case"parallelization":{emitObjectTypeMismatch("parallelization",value,findings);break}case"worktree":{emitObjectTypeMismatch("worktree",value,findings);break}case"turbo":{emitObjectTypeMismatch("turbo",value,findings);break}case"turbo_mode":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-turbo_mode-type",title:"Invalid turbo_mode type",description:`"turbo_mode" must be a boolean, got ${typeof value}`,severity:"error",path:"turbo_mode",currentValue:value,autoFixable:!1});break}case"quiet":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-quiet-type",title:"Invalid quiet type",description:`"quiet" must be a boolean, got ${typeof value}`,severity:"error",path:"quiet",currentValue:value,autoFixable:!1});break}case"version_check":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-version_check-type",title:"Invalid version_check type",description:`"version_check" must be a boolean, got ${typeof value}`,severity:"error",path:"version_check",currentValue:value,autoFixable:!1});break}case"$schema":{if(value!==void 0&&typeof value!=="string")findings.push({id:"invalid-$schema-type",title:"Invalid $schema type",description:`"$schema" must be a string (JSON Schema URL), got ${typeof value}`,severity:"error",path:"$schema",currentValue:value,autoFixable:!1});break}case"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"pr_feedback_loop":{emitObjectTypeMismatch("pr_feedback_loop",value,findings);break}case"pr_review_resilience":{emitObjectTypeMismatch("pr_review_resilience",value,findings);break}case"speckit_checkoff":{emitObjectTypeMismatch("speckit_checkoff",value,findings);break}case"review_routing":{if(emitObjectTypeMismatch("review_routing",value,findings),isPlainObject5(value)){let enforceReceipts=value.enforce_receipts;if(enforceReceipts!==void 0&&typeof enforceReceipts!=="boolean")findings.push({id:"invalid-review_routing-enforce_receipts-type",title:"Invalid review_routing.enforce_receipts type",description:`"review_routing.enforce_receipts" must be a boolean, got ${typeof enforceReceipts}`,severity:"error",path:"review_routing.enforce_receipts",currentValue:enforceReceipts,autoFixable:!1})}break}case"lane_liveness_watchdog":{emitObjectTypeMismatch("lane_liveness_watchdog",value,findings);break}case"dispatch_protection":{emitObjectTypeMismatch("dispatch_protection",value,findings);break}case"pr_review_legacy_transcript_compatibility":{if(value!==void 0&&typeof value!=="boolean")findings.push({id:"invalid-pr_review_legacy_transcript_compatibility-type",title:"Invalid pr_review_legacy_transcript_compatibility type",description:`"pr_review_legacy_transcript_compatibility" must be a boolean, got ${typeof value}`,severity:"error",path:"pr_review_legacy_transcript_compatibility",currentValue:value,autoFixable:!1});break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}case"skill_opt":{emitObjectTypeMismatch("skill_opt",value,findings);break}case"dashboard":{emitObjectTypeMismatch("dashboard",value,findings);break}default:{let topLevel=path182.split(".")[0];if(KNOWN_TOP_LEVEL_KEYS.has(topLevel))break;let MAX_SUGGESTION_KEY_LENGTH=100,lowerTopLevel=topLevel.toLowerCase(),suggestion,matchCount=0;if(lowerTopLevel.length<=MAX_SUGGESTION_KEY_LENGTH){for(let knownKey of KNOWN_TOP_LEVEL_KEYS)if(levenshteinDistance(lowerTopLevel,knownKey.toLowerCase())<=2){if(matchCount++,matchCount===1)suggestion=knownKey}}if(matchCount===1&&suggestion)findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path182}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path182,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path182}" is not in the schema.`,severity:"warn",path:path182,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path182,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path182&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path182,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path182,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path182}`,description:`Config value at "${path182}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path182,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path182,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path182}[${index}]`,findings,visited)});return}for(let[key2,value]of Object.entries(obj)){let newPath=path182?`${path182}.${key2}`:key2;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory,planParallelizationEnabled=null){let findings=[];walkConfigAndValidate(config3,"",findings),findings.push(...collectRawGatesConfigFindings(directory)),findings.push(...collectRawCouncilPolicyFindings(directory)),findings.push(...collectRawStrictSectionFindings(directory)),findings.push(...collectRawValueConstraintFindings(directory)),findings.push(...collectRawAutoReviewCompatibilityFindings(directory)),findings.push(...collectRawInertKeyFindings(directory)),findings.push(...collectLeanTurboGateSatisfiabilityFindings(config3)),emitWorktreeIsolationLayeringAdvisory(config3,findings,planParallelizationEnabled);let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length},hasAutoFixableIssues=findings.some((f)=>f.autoFixable&&f.proposedFix?.risk==="low"),{userConfigPath,projectConfigPath}=getConfigPaths(directory),configSource="defaults";if(fs97.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs97.existsSync(userConfigPath))configSource=userConfigPath;let rawConfigVersion=config3.config_format_version,configVersion=typeof rawConfigVersion==="number"&&Number.isFinite(rawConfigVersion)&&Number.isInteger(rawConfigVersion)&&rawConfigVersion>=0?rawConfigVersion:1,availableMigrations=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(configVersion<depInfo.deprecatedIn)availableMigrations.push({field:depPath,replacement:depInfo.replacement,deprecatedIn:depInfo.deprecatedIn,sinceVersion:depInfo.sinceVersion,currentFormatVersion:configVersion});for(let flip of DEFAULT_FLIPS)if(configVersion<flip.sinceVersion)findings.push({id:"defaults-flip",title:`v8 default change pending for "${flip.field}"`,description:`Default flips from ${flip.v7Default} to ${flip.v8Default}. Kill switch: set ${flip.killSwitch}. Restore all v7 defaults with preset: "${flip.preset}". Evidence and rollback: ${flip.evidence} (#2504).`,severity:"info",path:flip.field,currentValue:"v7 default",autoFixable:!1});return summary.info=findings.filter((f)=>f.severity==="info").length,summary.warn=findings.filter((f)=>f.severity==="warn").length,summary.error=findings.filter((f)=>f.severity==="error").length,{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource,...availableMigrations.length>0?{availableMigrations}:{}}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe3(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result,options={}){let applyLossy=options.applyLossy===!0,appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs97.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs97.readFileSync(projectConfigPath,"utf-8");else if(fs97.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs97.readFileSync(userConfigPath,"utf-8");else return{appliedFixes,updatedConfigPath:null};let config3;try{config3=JSON.parse(configContent)}catch{return{appliedFixes,updatedConfigPath:null}}let safeFixes=result.findings.filter((f)=>f.autoFixable&&f.proposedFix?.risk==="low"&&(applyLossy||!f.proposedFix?.lossy));for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe3(fix.path))continue;let pathParts=fix.path.split("."),current=config3,navigated=!0;for(let i=0;i<pathParts.length-1;i++){let part=pathParts[i];if(current===null||current===void 0){navigated=!1;break}if(typeof current!=="object"||Array.isArray(current)){navigated=!1;break}let obj=current;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null){navigated=!1;break}else if(typeof obj[part]!=="object"){navigated=!1;break}current=obj[part]}if(!navigated)continue;let lastPart=pathParts[pathParts.length-1];switch(fix.type){case"remove":if(current!==null&&current!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&&current!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(applyLossy&&result.availableMigrations&&result.availableMigrations.length>0)for(let migration of result.availableMigrations){if(!isPathSafe3(migration.field)||!isPathSafe3(migration.replacement))continue;let legacyParts=migration.field.split("."),legacyParent=config3,legacyNavigated=!0;for(let i=0;i<legacyParts.length-1;i++){let part=legacyParts[i];if(legacyParent===null||legacyParent===void 0||typeof legacyParent!=="object"||Array.isArray(legacyParent)){legacyNavigated=!1;break}let obj=legacyParent;if(obj[part]===void 0||obj[part]===null){legacyNavigated=!1;break}legacyParent=obj[part]}if(!legacyNavigated)continue;let legacyKey=legacyParts[legacyParts.length-1],legacyHolder=legacyParent;if(!(legacyKey in legacyHolder))continue;let legacyValue=legacyHolder[legacyKey],depInfo=DEPRECATED_FIELDS.get(migration.field);if(!depInfo||depInfo.isDefaultValue(legacyValue))continue;let replParts=migration.replacement.split("."),replParent=config3,replNavigated=!0;for(let i=0;i<replParts.length-1;i++){let part=replParts[i];if(replParent===null||replParent===void 0||typeof replParent!=="object"||Array.isArray(replParent)){replNavigated=!1;break}let obj=replParent;if(obj[part]===void 0)obj[part]={};else if(obj[part]===null||typeof obj[part]!=="object"){replNavigated=!1;break}replParent=obj[part]}if(!replNavigated)continue;let replKey=replParts[replParts.length-1];replParent[replKey]=legacyValue,delete legacyHolder[legacyKey],appliedFixes.push({type:"update",path:migration.replacement,value:legacyValue,description:`Migrate deprecated field \`${migration.field}\` → \`${migration.replacement}\``,risk:"low",lossy:!0}),appliedFixes.push({type:"remove",path:migration.field,description:`Remove deprecated field \`${migration.field}\` (migrated to \`${migration.replacement}\`)`,risk:"low",lossy:!0})}if(appliedFixes.length>0){let configDir=path181.dirname(configPath);if(!fs97.existsSync(configDir))fs97.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path181.join(directory,".swarm","config-doctor.json");if(!fs97.existsSync(artifactPath))return null;let content=fs97.readFileSync(artifactPath,"utf-8"),artifact=JSON.parse(content),summary=artifact.summary;if(!summary||typeof summary!=="object")return null;let{info:infoVal,warn:warnVal,error:errorVal}=summary;if(typeof infoVal!=="number"||!Number.isFinite(infoVal)||typeof warnVal!=="number"||!Number.isFinite(warnVal)||typeof errorVal!=="number"||!Number.isFinite(errorVal))return null;let ts=artifact.timestamp;if(typeof ts!=="number"||!Number.isFinite(ts))return null;let findingsCount=infoVal+warnVal+errorVal,findings=artifact.findings,autoFixableCount=Array.isArray(findings)?findings.filter((f)=>f.autoFixable===!0).length:0;return{timestamp:new Date(ts).toISOString(),findingsCount,autoFixableCount}}catch{return null}}function writeDoctorArtifact(directory,result){let swarmDir=path181.join(directory,".swarm");if(!fs97.existsSync(swarmDir))fs97.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path181.join(swarmDir,"config-doctor.json"),guiOutput={timestamp:result.timestamp,summary:result.summary,hasAutoFixableIssues:result.hasAutoFixableIssues,configSource:result.configSource,findings:result.findings.map((f)=>({id:f.id,title:f.title,description:f.description,severity:f.severity,path:f.path,autoFixable:f.autoFixable,proposedFix:f.proposedFix?{type:f.proposedFix.type,path:f.proposedFix.path,description:f.proposedFix.description,risk:f.proposedFix.risk,lossy:f.proposedFix.lossy===!0}:null}))};return atomicWriteFileSync(artifactPath,JSON.stringify(guiOutput,null,2)),artifactPath}function shouldRunOnStartup(automationConfig){if(!automationConfig)return!1;if(automationConfig.mode==="manual")return!1;return automationConfig.capabilities?.config_doctor_on_startup===!0}async function runConfigDoctorWithFixes(directory,config3,autoFix=!1,options={}){let planParallelizationEnabled=await resolvePlanParallelizationFlag(directory),result=runConfigDoctor(config3,directory,planParallelizationEnabled),artifactPath=writeDoctorArtifact(directory,result);if(!autoFix)return{result,backupPath:null,appliedFixes:[],updatedConfigPath:null,artifactPath};let backup=createConfigBackup(directory),backupPath=null;if(backup)backupPath=writeBackupArtifact(directory,backup);let{appliedFixes,updatedConfigPath}=applySafeAutoFixes(directory,result,options),hasDefaultsFlipFindings=result.findings.some((finding)=>finding.id==="defaults-flip");if(options.applyLossy===!0&&(appliedFixes.length>0||hasDefaultsFlipFindings))try{let{userConfigPath:stampUserPath,projectConfigPath:stampProjectPath}=getConfigPaths(directory),stampPath=fs97.existsSync(stampProjectPath)?stampProjectPath:fs97.existsSync(stampUserPath)?stampUserPath:null;if(stampPath){let stampContent=fs97.readFileSync(stampPath,"utf-8"),sanitizedStampContent=stampContent.charCodeAt(0)===65279?stampContent.slice(1):stampContent,stampConfig=JSON.parse(sanitizedStampContent),currentVersion=stampConfig.config_format_version;if(typeof currentVersion!=="number"||!Number.isInteger(currentVersion)||currentVersion<0||currentVersion<CURRENT_CONFIG_FORMAT_VERSION){stampConfig.config_format_version=CURRENT_CONFIG_FORMAT_VERSION;let stampDir=path181.dirname(stampPath);if(!fs97.existsSync(stampDir))fs97.mkdirSync(stampDir,{recursive:!0});atomicWriteFileSync(stampPath,JSON.stringify(stampConfig,null,2))}}}catch(stampError){log(`[ConfigDoctor] acknowledgment stamp failed (non-fatal): ${stampError instanceof Error?stampError.message:String(stampError)}`)}if(appliedFixes.length>0){let freshConfig=readConfigFromFile(directory);if(freshConfig){let newResult=runConfigDoctor(freshConfig.config,directory,planParallelizationEnabled);writeDoctorArtifact(directory,newResult)}}return{result,backupPath,appliedFixes,updatedConfigPath,artifactPath}}function detectStraySwarmDirs(projectRoot){let findings=[],SKIP_DIRS=new Set(["node_modules",".git","dist",".cache",".next","coverage",".turbo",".vercel",".terraform","__pycache__",".tox"]),MAX_DEPTH=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries2;try{entries2=fs97.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path181.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path181.join(fullPath,".git");try{let gitStat=fs97.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path181.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs97.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path181.relative(projectRoot,fullPath).replace(/\\/g,"/"),absolutePath:fullPath,contents:contents.slice(0,20),totalEntries:contents.length});continue}walk(fullPath,depth+1)}}return walk(projectRoot,0),findings}function removeStraySwarmDir(projectRoot,strayPath){let canonicalRoot,canonicalStray;try{canonicalRoot=fs97.realpathSync(projectRoot),canonicalStray=fs97.realpathSync(path181.isAbsolute(strayPath)?strayPath:path181.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path181.join(canonicalRoot,".swarm");if(sameExistingFilesystemPath(canonicalStray,rootSwarm)||sameExistingFilesystemPath(canonicalStray,canonicalRoot))return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!isCanonicalPathWithinRoot(canonicalStray,canonicalRoot))return{success:!1,message:"Path is outside project root — refusing to remove"};if(!canonicalStray.replace(/\\/g,"/").endsWith("/.swarm"))return{success:!1,message:"Path is not a .swarm directory — refusing to remove"};try{return fs97.rmSync(canonicalStray,{recursive:!0,force:!0}),{success:!0,message:`Removed stray .swarm directory: ${canonicalStray}`}}catch(err){return{success:!1,message:`Failed to remove: ${err instanceof Error?err.message:String(err)}`}}}var CONFIG_DOCTOR_MAX_CONFIG_FILE_BYTES=102400,KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,CURRENT_CONFIG_FORMAT_VERSION=3,DEFAULT_FLIPS,LEAN_TURBO_GATE_PRODUCERS,_internals144,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_consumers();init_schema();init_manager();init_tool_metadata();init_utils();init_filesystem_identity();init_path_security();KNOWN_TOP_LEVEL_KEYS=new Set(Object.keys(PluginConfigSchema.shape)),DEPRECATED_FIELDS=new Map([["skill_improver.model",{message:"deprecated",replacement:"agents.skill_improver.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null,deprecatedIn:2,sinceVersion:1}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0,deprecatedIn:2,sinceVersion:1}]]),DEFAULT_FLIPS=[{field:"auto_review.enabled",v7Default:"false (opt-in)",v8Default:"release-gated true (advisory) — activates on the first 8.x release",killSwitch:"auto_review.enabled: false",preset:"conservative",sinceVersion:3,evidence:"docs/defaults-governance.md"},{field:"execution_profile.parallelization_enabled",v7Default:"false (serial)",v8Default:"true for new plans (since v7.132.0, gate-enforced serial fallback)",killSwitch:"execution_profile.parallelization_enabled: false (per plan)",preset:"conservative",sinceVersion:3,evidence:"docs/defaults-governance.md"}];LEAN_TURBO_GATE_PRODUCERS=[{gate:"phase_critic",producerTool:"lean_turbo_critic",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-critic.json"},{gate:"phase_reviewer",producerTool:"lean_turbo_review",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo-reviewer.json"},{gate:"integrated_diff_required",producerTool:"lean_turbo_run_phase",evidencePathConvention:".swarm/evidence/{phase}/lean-turbo/lean-turbo-phase.json"}];_internals144={loadPlanJsonOnly};DANGEROUS_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"])});class LanguageRegistry{profiles;extensionIndex;constructor(){this.profiles=new Map,this.extensionIndex=new Map}unregister(id){let profile=this.profiles.get(id);if(!profile)return;if(this.profiles.delete(id),!profile.parserOnly){for(let ext of profile.extensions)if(this.extensionIndex.get(ext)===id)this.extensionIndex.delete(ext)}}register(profile){let existing=this.profiles.get(profile.id);if(existing&&existing!==profile)throw Error(`LanguageRegistry: profile id "${profile.id}" registered twice. Each LanguageProfile.id must be unique. Got: ${profile.displayName} vs existing ${existing.displayName}.`);if(!profile.parserOnly)for(let ext of profile.extensions){let claimedBy=this.extensionIndex.get(ext);if(claimedBy&&claimedBy!==profile.id)throw Error(`LanguageRegistry: extension "${ext}" registered by both "${claimedBy}" and "${profile.id}". A non-parserOnly profile must not collide on extensions. If both languages legitimately share an extension, mark one parserOnly: true.`);this.extensionIndex.set(ext,profile.id)}this.profiles.set(profile.id,profile)}get(id){return this.profiles.get(id)}getById(id){return this.profiles.get(id)}getByExtension(ext){let profileId=this.extensionIndex.get(ext);if(profileId)return this.profiles.get(profileId);return}getAll(){return Array.from(this.profiles.values())}getTier(tier){return Array.from(this.profiles.values()).filter((p)=>p.tier===tier)}}var LANGUAGE_REGISTRY;var init_profiles=__esm(()=>{LANGUAGE_REGISTRY=new LanguageRegistry;LANGUAGE_REGISTRY.register({id:"typescript",displayName:"TypeScript",tier:1,extensions:[".ts",".tsx"],treeSitter:{grammarId:"typescript",wasmFile:"tree-sitter-typescript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"javascript",displayName:"JavaScript",tier:1,extensions:[".js",".jsx",".mjs",".cjs"],treeSitter:{grammarId:"javascript",wasmFile:"tree-sitter-javascript.wasm",commentNodes:["comment","line_comment","block_comment"]},build:{detectFiles:["package.json"],commands:[{name:"bun build",cmd:"bun run build",detectFile:"package.json",priority:10},{name:"tsc",cmd:"tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"vite build",detectFile:"vite.config.ts",priority:8}]},test:{detectFiles:["package.json","vitest.config.ts","jest.config.js",".mocharc.js",".mocharc.json"],frameworks:[{name:"vitest",detect:"vitest.config.ts",cmd:"bun test",priority:10},{name:"jest",detect:"jest.config.js",cmd:"jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"mocha",priority:7}]},lint:{detectFiles:["biome.json","biome.jsonc",".eslintrc.js",".eslintrc.json"],linters:[{name:"biome",detect:"biome.json",cmd:"biome check --write .",priority:10},{name:"eslint",detect:".eslintrc.js",cmd:"eslint --fix .",priority:9}]},audit:{detectFiles:["package.json"],command:"npm audit --json",outputFormat:"json"},sast:{nativeRuleSet:"javascript",semgrepSupport:"ga"},prompts:{coderConstraints:["Use strict TypeScript; no implicit any or type assertions without justification","Prefer async/await over raw Promises; always handle rejections","Use const/let, never var; prefer immutable data structures","Follow existing import style (ESM); no require() in .ts files","Add JSDoc for all exported functions and types"],reviewerChecklist:["Verify no implicit any or unsafe type casts","Check async error handling — unhandled Promises are bugs","Confirm ESM import consistency (no mixed require/import)","Validate exported API surface matches declared types","Check for missing null/undefined guards on optional fields"]}});LANGUAGE_REGISTRY.register({id:"python",displayName:"Python",tier:1,extensions:[".py",".pyw"],treeSitter:{grammarId:"python",wasmFile:"tree-sitter-python.wasm",commentNodes:["comment"]},build:{detectFiles:["setup.py","pyproject.toml","setup.cfg"],commands:[{name:"pip install",cmd:"pip install -e .",detectFile:"setup.py",priority:10},{name:"build",cmd:"python -m build",detectFile:"pyproject.toml",priority:9}]},test:{detectFiles:["pytest.ini","pyproject.toml","setup.cfg","conftest.py"],frameworks:[{name:"pytest",detect:"pytest.ini",cmd:"pytest",priority:10},{name:"unittest",detect:"setup.py",cmd:"python -m unittest discover",priority:8}]},lint:{detectFiles:["pyproject.toml",".ruff.toml","setup.cfg"],linters:[{name:"ruff",detect:"pyproject.toml",cmd:"ruff check --fix .",priority:10},{name:"flake8",detect:"setup.cfg",cmd:"flake8 .",priority:8}]},audit:{detectFiles:["requirements.txt","Pipfile.lock","pyproject.toml"],command:"pip-audit --format json",outputFormat:"json"},sast:{nativeRuleSet:"python",semgrepSupport:"ga"},prompts:{coderConstraints:["Use type annotations on all function signatures (PEP 484)","Prefer f-strings over .format() or % formatting","Use pathlib.Path over os.path for filesystem operations","Never use bare except:; catch specific exception types","Follow PEP 8 style; max line length 120 characters"],reviewerChecklist:["Verify type annotations are present on all public functions","Check for bare except clauses or overly broad exception handling","Confirm no mutable default arguments (def f(x=[]) anti-pattern)","Validate f-string usage and no format string injection risks","Check imports are organized (stdlib → third-party → local)"]}});LANGUAGE_REGISTRY.register({id:"rust",displayName:"Rust",tier:1,extensions:[".rs"],treeSitter:{grammarId:"rust",wasmFile:"tree-sitter-rust.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["Cargo.toml"],commands:[{name:"cargo build",cmd:"cargo build",detectFile:"Cargo.toml",priority:10},{name:"cargo check",cmd:"cargo check",detectFile:"Cargo.toml",priority:9}]},test:{detectFiles:["Cargo.toml"],frameworks:[{name:"cargo",detect:"Cargo.toml",cmd:"cargo test",priority:10}]},lint:{detectFiles:["Cargo.toml"],linters:[{name:"clippy",detect:"Cargo.toml",cmd:"cargo clippy --fix --allow-dirty",priority:10},{name:"rustfmt",detect:"Cargo.toml",cmd:"cargo fmt",priority:9}]},audit:{detectFiles:["Cargo.lock"],command:"cargo audit --json",outputFormat:"json"},sast:{nativeRuleSet:"rust",semgrepSupport:"ga"},prompts:{coderConstraints:["Prefer owned types over references where ownership is clear; use lifetimes sparingly","Use Result<T, E> and ? operator for error propagation; never unwrap() in library code","Prefer iterators and combinators over explicit loops","Derive standard traits (Debug, Clone, PartialEq) whenever sensible","Avoid unsafe blocks; document any unsafe usage with SAFETY comments"],reviewerChecklist:["Verify no unwrap() or expect() calls in library/production paths","Check for potential panics in indexing, arithmetic overflow, or slice operations","Confirm error types implement std::error::Error and are propagated correctly","Validate lifetime annotations are minimal and correct","Check unsafe blocks have SAFETY comments explaining invariants"]}});LANGUAGE_REGISTRY.register({id:"go",displayName:"Go",tier:1,extensions:[".go"],treeSitter:{grammarId:"go",wasmFile:"tree-sitter-go.wasm",commentNodes:["comment"]},build:{detectFiles:["go.mod"],commands:[{name:"go build",cmd:"go build ./...",detectFile:"go.mod",priority:10},{name:"go vet",cmd:"go vet ./...",detectFile:"go.mod",priority:9}]},test:{detectFiles:["go.mod"],frameworks:[{name:"go-test",detect:"go.mod",cmd:"go test ./...",priority:10}]},lint:{detectFiles:["go.mod",".golangci.yml",".golangci.yaml"],linters:[{name:"golangci-lint",detect:".golangci.yml",cmd:"golangci-lint run --fix",priority:10},{name:"gofmt",detect:"go.mod",cmd:"gofmt -w .",priority:9}]},audit:{detectFiles:["go.mod"],command:"govulncheck -json ./...",outputFormat:"json"},sast:{nativeRuleSet:"go",semgrepSupport:"ga"},prompts:{coderConstraints:["Always check and return errors; never discard error return values","Use idiomatic Go error wrapping with fmt.Errorf and %w verb","Prefer table-driven tests; use t.Run for subtests","Avoid global mutable state; use dependency injection via interfaces","Use context.Context as first parameter for all I/O-bound functions"],reviewerChecklist:["Verify all error return values are checked (no _ = err pattern)","Check goroutine usage — confirm no goroutine leaks or missing WaitGroups","Validate context propagation through call chains","Confirm exported types/functions have doc comments","Check for data races in concurrent code (verify sync usage)"]}});LANGUAGE_REGISTRY.register({id:"java",displayName:"Java",tier:2,extensions:[".java"],treeSitter:{grammarId:"java",wasmFile:"tree-sitter-java.wasm",commentNodes:["line_comment","block_comment"]},build:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],commands:[{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:8}]},test:{detectFiles:["pom.xml","build.gradle","build.gradle.kts"],frameworks:[{name:"maven",detect:"pom.xml",cmd:"mvn test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["checkstyle.xml","pom.xml"],linters:[{name:"checkstyle",detect:"checkstyle.xml",cmd:"mvn checkstyle:check",priority:10}]},audit:{detectFiles:["pom.xml","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"java",semgrepSupport:"ga"},prompts:{coderConstraints:["Use checked exceptions for recoverable conditions; unchecked for programming errors","Prefer composition over inheritance; favor interfaces over abstract classes","Use Optional<T> for nullable return values rather than returning null","Follow Java naming conventions: PascalCase classes, camelCase methods/fields","Close resources in try-with-resources blocks; never rely on finalizers"],reviewerChecklist:["Check for unclosed resources — verify try-with-resources or explicit close()","Verify null checks are present for all external/injected dependencies","Confirm thread safety for shared mutable state (synchronized, volatile, atomic)","Validate exception handling — no swallowed exceptions or empty catch blocks","Check for proper equals()/hashCode() overrides on value objects"]}});LANGUAGE_REGISTRY.register({id:"kotlin",displayName:"Kotlin",tier:2,extensions:[".kt",".kts"],treeSitter:{grammarId:"kotlin",wasmFile:"tree-sitter-kotlin.wasm",commentNodes:["line_comment","multiline_comment"]},build:{detectFiles:["build.gradle.kts","build.gradle","pom.xml"],commands:[{name:"gradle-kts",cmd:"gradle build -q",detectFile:"build.gradle.kts",priority:10},{name:"gradle",cmd:"gradle build -q",detectFile:"build.gradle",priority:9},{name:"maven",cmd:"mvn compile -q",detectFile:"pom.xml",priority:8}]},test:{detectFiles:["build.gradle.kts","build.gradle"],frameworks:[{name:"gradle",detect:"build.gradle.kts",cmd:"gradle test -q",priority:10},{name:"gradle",detect:"build.gradle",cmd:"gradle test -q",priority:9}]},lint:{detectFiles:["build.gradle.kts","build.gradle"],linters:[{name:"ktlint",detect:"build.gradle.kts",cmd:"ktlint --format",priority:10}]},audit:{detectFiles:["build.gradle.kts","build.gradle"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"beta"},prompts:{coderConstraints:["Prefer val over var; use data classes for value objects","Use Kotlin coroutines for async operations; avoid blocking calls on Dispatchers.Main","Leverage extension functions instead of utility classes","Use sealed classes for exhaustive when expressions","Avoid platform types; always declare explicit nullability in API surfaces"],reviewerChecklist:["Verify no non-null assertions (!!) in production code without justification","Check coroutine scope lifecycle — confirm scopes are cancelled when no longer needed","Validate when expressions are exhaustive (sealed class coverage)","Confirm data class equals/hashCode/copy semantics are appropriate","Check for blocking I/O on the wrong coroutine dispatcher"]}});LANGUAGE_REGISTRY.register({id:"csharp",displayName:"C# / .NET",tier:2,extensions:[".cs",".csx"],treeSitter:{grammarId:"csharp",wasmFile:"tree-sitter-c-sharp.wasm",commentNodes:["comment"]},build:{detectFiles:["*.csproj","*.sln","Directory.Build.props"],commands:[{name:"dotnet build",cmd:"dotnet build -v quiet",detectFile:"*.csproj",priority:10},{name:"dotnet build sln",cmd:"dotnet build -v quiet",detectFile:"*.sln",priority:9}]},test:{detectFiles:["*.csproj","*.sln"],frameworks:[{name:"dotnet-test",detect:"*.csproj",cmd:"dotnet test",priority:10}]},lint:{detectFiles:["*.csproj",".editorconfig"],linters:[{name:"dotnet-format",detect:"*.csproj",cmd:"dotnet format",priority:10}]},audit:{detectFiles:["*.csproj","packages.lock.json"],command:"dotnet list package --vulnerable --include-transitive",outputFormat:"text"},sast:{nativeRuleSet:"csharp",semgrepSupport:"ga"},prompts:{coderConstraints:["Use async/await throughout; avoid .Result or .Wait() which can deadlock","Prefer records for immutable value types; use struct only for small value types","Use nullable reference types (NRT) — enable <Nullable>enable</Nullable>","Dispose IDisposable resources with using statements or declarations","Follow C# naming conventions: PascalCase for public members, _camelCase for private fields"],reviewerChecklist:["Verify no .Result or .Wait() calls that could cause deadlocks","Check all IDisposable are properly disposed (using / IAsyncDisposable)","Confirm nullable reference type annotations are present and correct","Validate LINQ queries do not cause N+1 query patterns in EF contexts","Check for missing ConfigureAwait(false) in library code"]}});LANGUAGE_REGISTRY.register({id:"cpp",displayName:"C / C++",tier:2,extensions:[".c",".h",".cpp",".hpp",".cc",".cxx"],treeSitter:{grammarId:"cpp",wasmFile:"tree-sitter-cpp.wasm",commentNodes:["comment"]},build:{detectFiles:["CMakeLists.txt","Makefile","meson.build"],commands:[{name:"cmake",cmd:"cmake --build build",detectFile:"CMakeLists.txt",priority:10},{name:"make",cmd:"make",detectFile:"Makefile",priority:9},{name:"meson",cmd:"meson compile -C builddir",detectFile:"meson.build",priority:8}]},test:{detectFiles:["CMakeLists.txt"],frameworks:[{name:"ctest",detect:"CMakeLists.txt",cmd:"ctest --test-dir build",priority:10}]},lint:{detectFiles:[".clang-tidy","CMakeLists.txt"],linters:[{name:"cppcheck",detect:"CMakeLists.txt",cmd:"cppcheck --error-exitcode=1 .",priority:10},{name:"clang-tidy",detect:".clang-tidy",cmd:"clang-tidy -p build",priority:9}]},audit:{detectFiles:["CMakeLists.txt","vcpkg.json","conanfile.txt"],command:null,outputFormat:"json"},sast:{nativeRuleSet:"cpp",semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer RAII and smart pointers (unique_ptr, shared_ptr) over raw pointers","Use const-correctness throughout; mark all non-mutating methods const","Avoid undefined behaviour: no out-of-bounds access, no use-after-free","Initialize all variables; prefer in-class initializers for member variables","Use std::array or std::vector instead of C-style arrays"],reviewerChecklist:["Verify no raw owning pointers; confirm smart pointer ownership semantics","Check for memory leaks — every new has a corresponding delete or smart pointer","Validate bounds checking on all array/buffer accesses","Confirm no undefined behavior patterns (signed overflow, strict aliasing violations)","Check thread safety for shared data (mutex, atomic, lock-free patterns)"]}});LANGUAGE_REGISTRY.register({id:"swift",displayName:"Swift",tier:2,extensions:[".swift"],treeSitter:{grammarId:"swift",wasmFile:"tree-sitter-swift.wasm",commentNodes:["comment","multiline_comment"]},build:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace"],commands:[{name:"swift build",cmd:"swift build",detectFile:"Package.swift",priority:10},{name:"xcodebuild",cmd:"xcodebuild build -quiet",detectFile:"*.xcodeproj",priority:9}]},test:{detectFiles:["Package.swift","*.xcodeproj"],frameworks:[{name:"swift-test",detect:"Package.swift",cmd:"swift test",priority:10},{name:"xcodebuild-test",detect:"*.xcodeproj",cmd:"xcodebuild test -quiet",priority:9}]},lint:{detectFiles:[".swiftlint.yml","Package.swift"],linters:[{name:"swiftlint",detect:".swiftlint.yml",cmd:"swiftlint --fix",priority:10}]},audit:{detectFiles:["Package.resolved","Package.swift"],command:null,outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Prefer value types (structs, enums) over classes; use classes only for reference semantics","Use Swift concurrency (async/await, actors) over GCD for new code","Avoid force unwrap (!) and force cast (as!); use guard let or if let","Use Swift Package Manager for dependencies where possible","Mark types and methods as final when subclassing is not intended"],reviewerChecklist:["Verify no force unwraps (!) or force casts (as!) in production code","Check for retain cycles in closures — confirm [weak self] where needed","Validate Swift concurrency usage — no data races across actor boundaries","Confirm proper error handling with do-try-catch or Result<T,E>","Check value vs reference type choice is appropriate for the use case"]}});LANGUAGE_REGISTRY.register({id:"dart",displayName:"Dart / Flutter",tier:3,extensions:[".dart"],treeSitter:{grammarId:"dart",wasmFile:"tree-sitter-dart.wasm",commentNodes:["comment","documentation_comment"]},build:{detectFiles:["pubspec.yaml"],commands:[{name:"flutter build",cmd:"flutter build apk",detectFile:"pubspec.yaml",priority:10},{name:"dart compile",cmd:"dart compile exe .",detectFile:"pubspec.yaml",priority:9}]},test:{detectFiles:["pubspec.yaml"],frameworks:[{name:"flutter test",detect:"pubspec.yaml",cmd:"flutter test",priority:10},{name:"dart test",detect:"pubspec.yaml",cmd:"dart test",priority:9}]},lint:{detectFiles:["analysis_options.yaml","pubspec.yaml"],linters:[{name:"dart analyze",detect:"pubspec.yaml",cmd:"dart analyze",priority:10}]},audit:{detectFiles:["pubspec.yaml","pubspec.lock"],command:"dart pub outdated --json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"none"},prompts:{coderConstraints:["Use null safety features — prefer late, required, and ? annotations over dynamic","Follow Dart effective style: lowerCamelCase for variables, UpperCamelCase for types","Prefer const constructors where possible for performance","Use async/await over raw Future callbacks","Separate business logic from UI widgets; use BLoC or Provider patterns"],reviewerChecklist:["Verify null safety annotations are correct (no unnecessary ?)","Check that const constructors are used where the widget tree is static","Confirm async operations handle error states (catchError or try-catch)","Validate no direct UI state mutation outside setState or stream","Check for platform-specific code isolation (dart:io vs dart:html)"]}});LANGUAGE_REGISTRY.register({id:"ruby",displayName:"Ruby",tier:3,extensions:[".rb",".rake",".gemspec"],treeSitter:{grammarId:"ruby",wasmFile:"tree-sitter-ruby.wasm",commentNodes:["comment"]},build:{detectFiles:["Gemfile","Rakefile"],commands:[{name:"bundle install",cmd:"bundle install",detectFile:"Gemfile",priority:10},{name:"rake",cmd:"rake",detectFile:"Rakefile",priority:9}]},test:{detectFiles:["Gemfile",".rspec","spec/spec_helper.rb"],frameworks:[{name:"rspec",detect:".rspec",cmd:"bundle exec rspec",priority:10},{name:"minitest",detect:"Rakefile",cmd:"bundle exec rake test",priority:9}]},lint:{detectFiles:[".rubocop.yml","Gemfile"],linters:[{name:"rubocop",detect:".rubocop.yml",cmd:"rubocop --autocorrect",priority:10}]},audit:{detectFiles:["Gemfile.lock"],command:"bundle-audit check --format json",outputFormat:"json"},sast:{nativeRuleSet:null,semgrepSupport:"experimental"},prompts:{coderConstraints:["Follow Ruby community style (Rubocop defaults); 120-char line limit","Prefer symbols over strings for hash keys","Use frozen_string_literal: true magic comment in all files","Avoid monkey-patching core classes; prefer refinements","Use keyword arguments for methods with more than 2 parameters"],reviewerChecklist:["Verify frozen_string_literal comment is present in new files","Check for N+1 query patterns in ActiveRecord code","Validate no eval or send with user-controlled input (code injection risk)","Confirm exception handling is specific — no bare rescue","Check for missing validations on ActiveRecord models"]}});LANGUAGE_REGISTRY.register({id:"php",displayName:"PHP",tier:3,extensions:[".php",".phtml",".blade.php"],treeSitter:{grammarId:"php",wasmFile:"tree-sitter-php.wasm",commentNodes:["comment"]},build:{detectFiles:["composer.json"],commands:[{name:"Composer Install",cmd:"composer install --no-interaction --prefer-dist",detectFile:"composer.json",priority:10}]},test:{detectFiles:["Pest.php","phpunit.xml","phpunit.xml.dist"],frameworks:[{name:"Pest",detect:"Pest.php",cmd:"vendor/bin/pest",priority:10},{name:"PHPUnit",detect:"phpunit.xml",cmd:"vendor/bin/phpunit",priority:8},{name:"PHPUnit",detect:"phpunit.xml.dist",cmd:"vendor/bin/phpunit",priority:7}]},lint:{detectFiles:["phpstan.neon","phpstan.neon.dist","pint.json",".php-cs-fixer.php","phpcs.xml"],linters:[{name:"PHPStan",detect:"phpstan.neon",cmd:"vendor/bin/phpstan analyse",priority:10},{name:"PHPStan",detect:"phpstan.neon.dist",cmd:"vendor/bin/phpstan analyse",priority:9},{name:"Pint",detect:"pint.json",cmd:"vendor/bin/pint --test",priority:8},{name:"PHP-CS-Fixer",detect:".php-cs-fixer.php",cmd:"vendor/bin/php-cs-fixer fix --dry-run --diff",priority:7}]},audit:{detectFiles:["composer.lock"],command:"composer audit --locked --format=json",outputFormat:"json"},sast:{nativeRuleSet:"php",semgrepSupport:"ga"},prompts:{coderConstraints:["Follow PSR-12 coding standards","Use strict types declaration: declare(strict_types=1)","Prefer type hints and return type declarations on all functions","Use dependency injection over static methods and singletons","Prefer named constructors and value objects over primitive obsession"],reviewerChecklist:["Verify no user input reaches SQL queries without parameterised binding","Check for XSS — all output must be escaped with htmlspecialchars()","Confirm no eval(), exec(), or shell_exec() with user-controlled input","Validate proper error handling — no bare catch blocks that swallow errors","Challenge any PHP/Laravel documentation or README claim that exceeds what is implemented and CI-verified in v6.49.0 (composer build, PHPUnit/Pest/artisan test, Pint/PHP-CS-Fixer lint, PHPStan static analysis, composer audit, Laravel detection, Blade scanning, 3 Laravel SAST rules). If a PR adds docs claiming broader support, verify it is backed by tests."],testConstraints:["Prefer feature tests for HTTP, middleware, and authentication flows — use Laravel RefreshDatabase or DatabaseTransactions traits","Use unit tests for isolated business logic classes that do not require the full Laravel application container","Pest and PHPUnit coexist in many Laravel repos — php artisan test runs both; do not assume PHPUnit-only","Use .env.testing for test environment configuration; run php artisan config:clear when environment changes affect tests","For database tests, prefer RefreshDatabase over manual setUp/tearDown to avoid state leakage between tests","Run php artisan config:clear and php artisan cache:clear before running tests if environment variables changed","Use separate .env.testing file for test-specific configuration; never rely on .env for CI test runs","For parallel testing with php artisan test --parallel, ensure database connections use separate databases per worker (APP_ENV=testing + test database suffix pattern)"]}})});import{access as access4,readdir as readdir12}from"node:fs/promises";import{extname as extname9,join as join137}from"node:path";function getProfileForFile(filePath){let ext=extname9(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries2;try{dirEntries=await readdir12(dir,{withFileTypes:!0}),entries2=dirEntries.map((e)=>e.name)}catch{return}for(let profile of LANGUAGE_REGISTRY.getAll())for(let detectFile of profile.build.detectFiles){if(detectFile.includes("*")||detectFile.includes("?")){let regex=new RegExp(`^${detectFile.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);if(dirEntries.some((e)=>!e.isDirectory()&&regex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join137(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries2){let ext=extname9(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir12(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join137(projectDir,entry.name))}catch{}let result=[];for(let id of detected){let profile=LANGUAGE_REGISTRY.getById(id);if(profile)result.push(profile)}return result.sort((a,b)=>a.tier-b.tier),result}var init_detector=__esm(()=>{init_profiles()});import*as fs98 from"node:fs";import*as path182 from"node:path";function tokenizeCommand(command){let out=[],buf="",quote=null;for(let ch of command.trim()){if(quote){if(ch===quote)quote=null;else buf+=ch;continue}if(ch==='"'||ch==="'"){quote=ch;continue}if(ch===" "||ch==="\t"){if(buf.length>0)out.push(buf),buf="";continue}buf+=ch}if(buf.length>0)out.push(buf);return out}function findCommandSuffixStart(command){let quote=null,sawTokenChar=!1;for(let i=0;i<command.length;i++){let ch=command[i];if(quote){if(ch===quote)quote=null;else sawTokenChar=!0;continue}if(ch==='"'||ch==="'"){quote=ch,sawTokenChar=!0;continue}if((ch===" "||ch==="\t")&&sawTokenChar)return i;if(ch!==" "&&ch!=="\t")sawTokenChar=!0}return command.length}function resolveLocalCandidate(binary,workingDir,platform=process.platform,isAvailable){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`,absolute=path182.join(workingDir,"node_modules",".bin",executable);if(!fs98.existsSync(absolute))continue;if(candidate.requiresNode&&isAvailable&&!isAvailable("node"))continue;let relative39=platform==="win32"?path182.win32.join("node_modules",".bin",executable):path182.posix.join("node_modules",".bin",executable);return{absolute,relative:relative39,requiresNode:candidate.requiresNode}}return null}function hasAnyLocalCandidate(binary,workingDir,platform=process.platform){let candidates=platform==="win32"?WINDOWS_LOCAL_SHIM_CANDIDATES:[{suffix:"",requiresNode:!0}];for(let candidate of candidates){let executable=`${binary}${candidate.suffix}`;if(fs98.existsSync(path182.join(workingDir,"node_modules",".bin",executable)))return!0}return!1}function resolveLocalCommand(command,workingDir,isAvailable,platform=process.platform){let tokens2=tokenizeCommand(command);if(tokens2.length===0)return null;let[binary,...args2]=tokens2;if(["npx","bunx","pnpx"].includes(binary))return null;if(binary.includes("/")||binary.includes("\\"))return null;let trimmed=command.trim(),local=resolveLocalCandidate(binary,workingDir,platform,isAvailable);if(local){let shellPath=platform==="win32"?local.relative:`./${local.relative}`;return{argv:[local.absolute,...args2],shellCommand:`${shellPath}${trimmed.slice(findCommandSuffixStart(trimmed))}`}}if(hasAnyLocalCandidate(binary,workingDir,platform))return null;return isAvailable(binary)?{argv:tokens2,shellCommand:command}:null}function resolveLocalNodeTool(tool3,args2,workingDir,platform=process.platform,isAvailable){let local=resolveLocalCandidate(tool3,workingDir,platform,platform==="win32"?isAvailable:void 0);if(local)return[local.absolute,...args2];if(hasAnyLocalCandidate(tool3,workingDir,platform))return null;return isAvailable?.(tool3)?[tool3,...args2]:null}var WINDOWS_LOCAL_SHIM_CANDIDATES;var init_command_resolution=__esm(()=>{WINDOWS_LOCAL_SHIM_CANDIDATES=[{suffix:".cmd",requiresNode:!0},{suffix:".exe",requiresNode:!1},{suffix:".bat",requiresNode:!0},{suffix:".ps1",requiresNode:!0},{suffix:"",requiresNode:!0}]});import*as fs99 from"node:fs";import*as path183 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32";try{let searchName=isWindows?command:command,available=_internals145.spawnSyncImpl(isWindows?["where",searchName]:["which",searchName],{cwd:process.cwd(),stdin:"ignore",stdout:"ignore",stderr:"ignore",timeout:IS_COMMAND_AVAILABLE_TIMEOUT_MS}).success;return toolchainCache.set(command,available),available}catch{return toolchainCache.set(command,!1),!1}}function checkToolchain(commands){return commands.some((cmd)=>_internals145.isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs99.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path183.join(dir,matches[0])}catch{}}else{let filePath=path183.join(workingDir,pattern);if(fs99.existsSync(filePath))return filePath}return null}function sanitizeEvidenceText(raw,maxChars){let withoutControls="";for(let char of raw){let code=char.charCodeAt(0);withoutControls+=code<32||code===127?" ":char}let normalized=withoutControls.replace(/\s+/g," ").trim();if(!normalized)return"(empty)";if(normalized.length<=maxChars)return normalized;if(maxChars<=3)return normalized.slice(0,maxChars);return`${normalized.slice(0,maxChars-3)}...`}function sanitizeRequiredCommand(command){let sanitized=sanitizeEvidenceText(command,40);return sanitized==="(empty)"?null:sanitized}function getBinaryFromCommand(command){return command.trim().split(/\s+/)[0]??""}function getProfileRequiredCommands(commands){let uniqueCommands=new Set;for(let command of commands){let binary=sanitizeRequiredCommand(getBinaryFromCommand(command.cmd));if(binary)uniqueCommands.add(binary)}return Array.from(uniqueCommands)}function getNoMatchingBuildFilesReason(profileId,commands){let detectFiles=Array.from(new Set(commands.map((command)=>command.detectFile?.trim()).filter((detectFile)=>Boolean(detectFile))));if(detectFiles.length===0)return`No matching build files for profile ${profileId}`;return`No matching build files for profile ${profileId}: expected ${detectFiles.join(" or ")}`}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path183.join(workingDir,"package.json");if(!fs99.existsSync(packageJsonPath))return{commands:[],hasScripts:!1};try{let content=fs99.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return{commands:[],hasScripts:!1};let scriptNames=scripts.filter((name)=>typeof pkg.scripts[name]==="string"&&pkg.scripts[name].trim());if(scriptNames.length===0)return{commands:[],hasScripts:!1};let rawPackageManager=typeof pkg.packageManager==="string"?pkg.packageManager.trim():void 0,declared=rawPackageManager?.split("@")[0]?.trim(),supported=[...SUPPORTED_NODE_PACKAGE_MANAGERS],sanitizedDeclared=declared?sanitizeRequiredCommand(declared):null,candidates=declared?[declared]:supported;if(rawPackageManager!==void 0&&(!declared||!supported.includes(declared)))return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:sanitizedDeclared?[sanitizedDeclared]:[],reason:`Unsupported packageManager: ${sanitizeEvidenceText(rawPackageManager,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS)}`}};let manager=candidates.find((candidate)=>_internals145.isCommandAvailable(candidate));if(!manager)return{commands:[],hasScripts:!0,skip:{ecosystem:"node",code:"environment_unavailable",required_commands:candidates,reason:`Package manager not available: ${candidates.join(" or ")}`}};return{hasScripts:!0,commands:scriptNames.map((scriptName)=>({command:`${manager} run ${scriptName}`,priority:100}))}}catch{return{commands:[],hasScripts:!1}}}function filterByScope(workingDir,scope,changedFiles){if(scope==="all")return findAllBuildFiles(workingDir);if(!changedFiles||changedFiles.length===0)return[];return changedFiles}function findAllBuildFiles(workingDir){let allBuildFiles=new Set;for(let ecosystem of ECOSYSTEMS)for(let pattern of ecosystem.buildFiles)if(pattern.includes("*")){let regex=simpleGlobToRegex(pattern);findFilesRecursive(workingDir,regex,allBuildFiles)}else{let filePath=path183.join(workingDir,pattern);if(fs99.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries2=fs99.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path183.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&&regex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await _internals145.detectProjectLanguagesImpl(workingDir);for(let profile of detectedProfiles){let fullProfile=_internals145.getLanguageProfileImpl(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>b.priority-a.priority),applicableCommands=sortedCommands.filter((cmd)=>{if(!cmd.detectFile)return!0;let detectFilePath=path183.join(workingDir,cmd.detectFile);return fs99.existsSync(detectFilePath)});if(applicableCommands.length===0){skipped.push({ecosystem:fullProfile.id,reason:getNoMatchingBuildFilesReason(fullProfile.id,sortedCommands)});continue}let foundCommand=!1;for(let cmd of applicableCommands){let resolved=resolveLocalCommand(cmd.cmd,workingDir,_internals145.isCommandAvailable);if(resolved){commands.push({ecosystem:fullProfile.id,command:resolved.shellCommand,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let requiredCommands=getProfileRequiredCommands(applicableCommands),triedBinaries=requiredCommands.join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,code:"environment_unavailable",required_commands:requiredCommands,reason}),warn(`[build-discovery] profile ${fullProfile.id}: no binary available, skipping`)}}return{commands,skipped}}async function discoverBuildCommands(workingDir,options){let scope=options?.scope??"all",changedFiles=options?.changedFiles??[],_filesToCheck=filterByScope(workingDir,scope,changedFiles),profileResult=await _internals145.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,repoDefinedScriptsByEcosystem=new Map,repoScriptSkips=[],repoDeclaredEcosystems=new Set;for(let ecosystem of ECOSYSTEMS){if(!ecosystem.repoDefinedScripts)continue;let repoResult=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoResult.commands.length>0)repoDefinedScriptsByEcosystem.set(ecosystem.ecosystem,repoResult.commands);if(repoResult.hasScripts)repoDeclaredEcosystems.add(ecosystem.ecosystem);if(repoResult.skip)repoScriptSkips.push(repoResult.skip)}let filteredProfileCommands=profileCommands.filter((cmd)=>{return(PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[]).every((name)=>!repoDeclaredEcosystems.has(name))}),coveredEcosystems=new Set;for(let cmd of filteredProfileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...filteredProfileCommands],skipped=[...profileSkipped,...repoScriptSkips];for(let ecosystem of ECOSYSTEMS){if(!findBuildFiles(workingDir,ecosystem.buildFiles))continue;let repoScripts=repoDefinedScriptsByEcosystem.get(ecosystem.ecosystem);if(repoScripts&&repoScripts.length>0){for(let script of repoScripts)commands.push({ecosystem:ecosystem.ecosystem,command:script.command,cwd:workingDir,priority:script.priority});continue}if(repoDeclaredEcosystems.has(ecosystem.ecosystem))continue;if(coveredEcosystems.has(ecosystem.ecosystem)){skipped.push({ecosystem:ecosystem.ecosystem,reason:"Covered by profile detection"});continue}if(!checkToolchain(ecosystem.toolchainCommands)){skipped.push({ecosystem:ecosystem.ecosystem,code:"environment_unavailable",required_commands:ecosystem.toolchainCommands,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}let availableCommands=ecosystem.commands;for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>b.priority-a.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var SUPPORTED_NODE_PACKAGE_MANAGERS,MAX_PACKAGE_MANAGER_EVIDENCE_CHARS=120,ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals145,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();init_command_resolution();SUPPORTED_NODE_PACKAGE_MANAGERS=["bun","npm","pnpm","yarn"],ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:[...SUPPORTED_NODE_PACKAGE_MANAGERS],commands:[{command:"npm run build",priority:30},{command:"npm run typecheck",priority:20},{command:"npm run check",priority:10}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:20},{command:"cargo check",priority:10}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:10}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m build",priority:20},{command:"python -m py_compile",priority:10}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:10}]},{ecosystem:"java-gradle",buildFiles:["build.gradle","build.gradle.kts","gradle.properties"],toolchainCommands:["gradle","gradlew"],commands:[{command:process.platform==="win32"?"gradlew.bat build":"./gradlew build",priority:20},{command:"gradle build",priority:10}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:10}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:10}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart compile",priority:20},{command:"dart analyze",priority:10}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:20},{command:"cmake -B build && cmake --build build",priority:10}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:10}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["node"],javascript:["node"],python:["python"],rust:["rust"],go:["go"],java:["java-maven","java-gradle"],kotlin:["java-gradle"],csharp:["dotnet"],cpp:["cpp"],swift:["swift"],dart:["dart"],ruby:[],php:["php-composer"]},toolchainCache=new Map;_internals145={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,detectProjectLanguagesImpl:detectProjectLanguages,getLanguageProfileImpl:LANGUAGE_REGISTRY.get.bind(LANGUAGE_REGISTRY),spawnSyncImpl:bunSpawnSync};build_discovery=tool({description:"Discover build commands for various ecosystems in a project directory",args:{workingDir:tool.schema.string().describe("Directory to scan for build commands (defaults to current directory)"),scope:tool.schema.string().optional().describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changedFiles:tool.schema.array(tool.schema.string()).optional().describe('List of changed files when scope is "changed"')},async execute(args2,_context){let result=await discoverBuildCommands(args2.workingDir,{scope:args2.scope??"all",changedFiles:args2.changedFiles??[]});return JSON.stringify(result,null,2)}})});var init_tool_names=__esm(()=>{init_tool_metadata()});var exports_tool_doctor={};__export(exports_tool_doctor,{runToolDoctor:()=>runToolDoctor,getBinaryReadinessAdvisory:()=>getBinaryReadinessAdvisory,checkAgentToolMapAlignment:()=>checkAgentToolMapAlignment});function getRegisteredToolKeys(){return new Set(TOOL_NAME_SET)}function checkAgentToolMapAlignment(registeredKeys){let findings=[];for(let[agentName,tools]of Object.entries(AGENT_TOOL_MAP))for(let toolName of tools)if(!registeredKeys.has(toolName))findings.push({id:`agent-tool-map-mismatch-${agentName}-${toolName}`,title:"AGENT_TOOL_MAP alignment gap",description:`Tool "${toolName}" is assigned to agent "${agentName}" in AGENT_TOOL_MAP but is not a registered tool name. The agent will not be able to use this tool.`,severity:"error",path:`AGENT_TOOL_MAP.${agentName}`,currentValue:toolName,autoFixable:!1});return findings}function checkBinaryReadiness(){let findings=[];for(let{binary,language}of BINARY_CHECKLIST)if(!isCommandAvailable(binary))findings.push({id:`missing-binary-${binary}`,title:"Class 3 tool binary not found",description:`Binary "${binary}" is not available on PATH. ${language} linting will not be available. Install ${binary} to enable ${language} language support.`,severity:"warn",path:`toolchain.${binary}`,currentValue:void 0,autoFixable:!1});return findings}function getBinaryReadinessAdvisory(){let findings=checkBinaryReadiness();if(findings.length===0)return null;return["[PRE-FLIGHT ADVISORY] The following Class 3 tool binaries were not found on PATH at session start.","These tools will soft-skip at invocation. Plan tasks accordingly.",...findings.map((f)=>`- MISSING BINARY: ${f.currentValue??f.path?.split(".")[1]??"unknown"} — ${f.description}`)].join(`
2664
2664
  `)}function runToolDoctor(_directory2,_pluginRoot){let findings=[],registeredKeys=getRegisteredToolKeys();for(let toolName of TOOL_NAMES)if(!registeredKeys.has(toolName))findings.push({id:`missing-tool-registration-${toolName}`,title:"Missing tool registration",description:`Tool "${toolName}" is defined in TOOL_NAMES but is not present in the plugin tool object derived from TOOL_MANIFEST. This means the tool will not be available at runtime.`,severity:"error",path:`tool.${toolName}`,currentValue:void 0,autoFixable:!1});findings.push(...checkAgentToolMapAlignment(registeredKeys)),findings.push(...checkBinaryReadiness());let summary={info:findings.filter((f)=>f.severity==="info").length,warn:findings.filter((f)=>f.severity==="warn").length,error:findings.filter((f)=>f.severity==="error").length};return{findings,summary,hasAutoFixableIssues:!1,timestamp:Date.now(),configSource:"src/tools/manifest.ts"}}var BINARY_CHECKLIST;var init_tool_doctor=__esm(()=>{init_discovery();init_constants();init_tool_names();BINARY_CHECKLIST=[{binary:"ruff",language:"Python"},{binary:"cargo",language:"Rust (via clippy)"},{binary:"golangci-lint",language:"Go"},{binary:"mvn",language:"Java (Maven)"},{binary:"gradle",language:"Java (Gradle)"},{binary:"dotnet",language:".NET"},{binary:"swift",language:"Swift"},{binary:"swiftlint",language:"Swift (linting)"},{binary:"dart",language:"Dart"},{binary:"flutter",language:"Flutter/Dart"},{binary:"biome",language:"JS/TS (already in project)"},{binary:"eslint",language:"JS/TS"}]});var exports_doctor_knowledge_receipt_phase_id={};__export(exports_doctor_knowledge_receipt_phase_id,{renderKnowledgeReceiptPhaseIdSection:()=>renderKnowledgeReceiptPhaseIdSection});async function renderKnowledgeReceiptPhaseIdSection(directory,enableAutoFix){let inspection;try{inspection=await inspectMembershipPhaseIds(directory)}catch{return section("skipped: knowledge receipt ledger could not be read (advisory check, fail-open).")}if(!inspection.ok){if(inspection.code==="lock_timeout")return section("skipped: ledger lock busy — run repair_knowledge_receipt_ledger with operation backfill_phase_id on demand.");return section(`skipped: ledger unavailable (${inspection.code}) — run repair_knowledge_receipt_ledger (default operation) to diagnose and repair.`)}let{missing,backfillable,unparsable}=inspection;if(missing===0)return enableAutoFix?section("all live memberships carry a phase_id."):"";let fixedNote="";if(enableAutoFix&&backfillable>0){let backfill=await backfillMembershipPhaseIds(directory).catch(()=>null);if(backfill?.ok){let after=await inspectMembershipPhaseIds(directory).catch(()=>null),remaining=after?.ok?after.missing:missing-(backfill.backfilled??0);fixedNote=` (--fix applied: ${backfill.backfilled} membership(s) backfilled; ${remaining} still lacking a phase id)`}else fixedNote=" (--fix attempted but the backfill did not complete; run repair_knowledge_receipt_ledger with operation backfill_phase_id)"}let lines=[`${missing} live receipt membership(s) lack a stable phase_id; ${backfillable} backfillable from their stored label.`];for(let row of unparsable.slice(0,10)){let label=row.label?`"${row.label.slice(0,80).replace(/[\r\n]+/g," ")}"`:" (no label)";lines.push(` - unparsable label on ${row.trace_id}/${row.entry_id}: ${label}`)}if(unparsable.length>10)lines.push(` - … and ${unparsable.length-10} more`);return lines.push(enableAutoFix?"":"Run /swarm doctor --fix to backfill ids from stored labels, or repair_knowledge_receipt_ledger with operation backfill_phase_id."),section(`${lines.filter((l)=>l!=="").join(`
2665
2665
  `)}${fixedNote}`)}function section(body){if(!body.trim())return"";return`
2666
2666
  ---