opencode-swarm 7.151.0 → 7.151.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{config-doctor-23ega26j.js → config-doctor-08zmx89c.js} +2 -2
- package/dist/cli/{core-3g4krkj8.js → core-w0gjhw5q.js} +1 -1
- package/dist/cli/{curator-llm-factory-k0nxn5gt.js → curator-llm-factory-jmx72zhc.js} +17 -17
- package/dist/cli/{curator-rym2wtn6.js → curator-twqjxden.js} +17 -17
- package/dist/cli/{evidence-summary-service-f0gvjesf.js → evidence-summary-service-py66zgn4.js} +6 -6
- package/dist/cli/{gate-evidence-cghq17xc.js → gate-evidence-ynhyzwsw.js} +2 -2
- package/dist/cli/{guardrail-explain-cv52smw2.js → guardrail-explain-j9h5r8gh.js} +18 -18
- package/dist/cli/{guardrail-log-wgwmh9b7.js → guardrail-log-7995v5q5.js} +3 -3
- package/dist/cli/{guardrail-reset-vx7zsmzd.js → guardrail-reset-seextj6h.js} +17 -17
- package/dist/cli/{hive-promoter-jb2nzv3j.js → hive-promoter-a6xtvynw.js} +17 -17
- package/dist/cli/{index-qa8bmwav.js → index-1z7kx41f.js} +1 -1
- package/dist/cli/{index-2qte9nr7.js → index-2xfffkk0.js} +1 -1
- package/dist/cli/{index-fkqfcv14.js → index-4y7n76bn.js} +1 -1
- package/dist/cli/{index-kghpgs47.js → index-5jwbepcr.js} +1 -1
- package/dist/cli/{index-xeptzfb6.js → index-5sh0kqf5.js} +1 -1
- package/dist/cli/{index-8wy7pb4a.js → index-7w2b1z4j.js} +2 -2
- package/dist/cli/{index-02qc4ehj.js → index-9d9p7bv2.js} +3 -3
- package/dist/cli/{index-7qbyetsf.js → index-a2phfdsv.js} +1 -1
- package/dist/cli/{index-bfc4bbq4.js → index-akef15kb.js} +3 -3
- package/dist/cli/{index-wxkgy9gh.js → index-fbj6wvew.js} +3 -3
- package/dist/cli/{index-vs8wtavs.js → index-gqss5zbr.js} +1 -1
- package/dist/cli/{index-vradyw0x.js → index-hw93dwd0.js} +19 -19
- package/dist/cli/{index-fybg880e.js → index-kzdv0g9e.js} +49 -49
- package/dist/cli/{index-5ep31be7.js → index-n35866rr.js} +1 -1
- package/dist/cli/{index-sdff3rvj.js → index-npzmqk01.js} +4 -4
- package/dist/cli/{index-tp1avc8j.js → index-qmwed766.js} +2 -2
- package/dist/cli/{index-zkxnba57.js → index-t9h95vjd.js} +5 -5
- package/dist/cli/{index-tfkc0zf4.js → index-twhhwe74.js} +1 -1
- package/dist/cli/{index-e9qh1j19.js → index-xtyxnxf4.js} +2 -2
- package/dist/cli/{index-sg48w5e4.js → index-xysb3ed7.js} +1 -1
- package/dist/cli/{index-wna9f75x.js → index-z09fmg67.js} +3 -3
- package/dist/cli/index.js +17 -17
- package/dist/cli/{knowledge-escalator-a9dwxqz8.js → knowledge-escalator-bqnkq3k7.js} +6 -6
- package/dist/cli/{knowledge-events-0q4sb713.js → knowledge-events-rz3mt7gf.js} +4 -4
- package/dist/cli/{knowledge-store-y2nbt9jk.js → knowledge-store-1m74b90j.js} +1 -1
- package/dist/cli/{knowledge-validator-4wr1m0xa.js → knowledge-validator-hfvhpkgk.js} +2 -2
- package/dist/cli/{scan-cursor-bsrfrxm6.js → scan-cursor-b36bzxkt.js} +2 -2
- package/dist/cli/{schema-s6yh3rst.js → schema-sc332es3.js} +1 -1
- package/dist/cli/{scope-persistence-f77w4jrx.js → scope-persistence-phkj8438.js} +4 -4
- package/dist/cli/{skill-generator-jr7c8fcg.js → skill-generator-2d005nr6.js} +7 -7
- package/dist/cli/{worktree-isolation-ka20b0rm.js → worktree-isolation-zpgkd71h.js} +17 -17
- package/dist/commands/registry.d.ts +2 -2
- package/dist/index.js +3 -3
- 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.151.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},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, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",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"]},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, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.151.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check: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:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},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, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",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"]},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, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -3560,7 +3560,7 @@ Showing full help:
|
|
|
3560
3560
|
|
|
3561
3561
|
Showing full help:
|
|
3562
3562
|
|
|
3563
|
-
`+fullHelp()}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation){let exactCommand=parsed.prUrl?`/swarm pr-feedback ${parsed.prUrl} continue from ${parsed.continuation.handoffPath}`:`/swarm pr-feedback continue from ${parsed.continuation.handoffPath}`;await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl,exactCommand,confirmedByUser:!0})}else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path214=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path214.indexOf(current),fullChain=[name,...path214.slice(0,cycleStart>0?cycleStart:path214.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path214.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens){if(tokens.length===0)return null;if(tokens.length>=2){let compound=`${tokens[0]} ${tokens[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound)){let entry=COMMAND_REGISTRY[compound],warning=entry.deprecated?`⚠️ "/swarm ${compound}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(2),key:compound,warning}}}let key=tokens[0];if(Object.hasOwn(COMMAND_REGISTRY,key)){let entry=COMMAND_REGISTRY[key],warning=entry.deprecated?`⚠️ "/swarm ${key}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(1),key,warning}}return null}var COMMAND_REGISTRY,VALID_COMMANDS,_internals61,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_pr_workflow_gate();init_logger();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci_monitor();init_ci_simulate();init_close();init_codebase_review();init_concurrency();init_config3();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_recover();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals61.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",toolPolicy:"agent"},"guardrail-explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",aliasOf:"guardrail reset",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Read-only: runs independent of `turbo.epic.cochange.enabled` so it can be used as a what-if diagnostic before opting into the runtime signal.",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Epic Mode (autonomous coupling-aware parallel activation) and inspect its decisions",details:"Epic Mode is an additive overlay that composes Lean Turbo. When on, the architect follows the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → for each wave in order, dispatch one Task per taskId in the wave, ALL in one assistant message (each concurrent coder appears as a visible subagent the user can click into) → epic_record_divergence. epic_decide_phase computes the plan-wide coupling coefficient p and gates parallel promotion on p + a hot-module check + a greenfield rule. epic_plan_waves partitions promoted phases into ordered concurrent groups (waves) that respect dependency order and scope disjointness. Subcommands: on, off, status, decide (read-only what-if), last (most recent decision from durable evidence log), calibration (Capability D state: learned threshold + hot modules + recent divergent tasks). Bare /swarm epic shows status. Decision rationale persists to .swarm/evidence/epic-promotions.jsonl after every epic_decide_phase invocation.",args:"on | off | status | decide | last | calibration",category:"diagnostics",toolPolicy:"none"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. WARNING: alignment discards local changes and gitignored files. Resets agent sessions, delegation chains, and active-agent mappings. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
|
|
3563
|
+
`+fullHelp()}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation){let exactCommand=parsed.prUrl?`/swarm pr-feedback ${parsed.prUrl} continue from ${parsed.continuation.handoffPath}`:`/swarm pr-feedback continue from ${parsed.continuation.handoffPath}`;await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl,exactCommand,confirmedByUser:!0})}else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path214=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path214.indexOf(current),fullChain=[name,...path214.slice(0,cycleStart>0?cycleStart:path214.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path214.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens){if(tokens.length===0)return null;if(tokens.length>=2){let compound=`${tokens[0]} ${tokens[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound)){let entry=COMMAND_REGISTRY[compound],warning=entry.deprecated?`⚠️ "/swarm ${compound}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(2),key:compound,warning}}}let key=tokens[0];if(Object.hasOwn(COMMAND_REGISTRY,key)){let entry=COMMAND_REGISTRY[key],warning=entry.deprecated?`⚠️ "/swarm ${key}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(1),key,warning}}return null}var COMMAND_REGISTRY,VALID_COMMANDS,_internals61,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_pr_workflow_gate();init_logger();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci_monitor();init_ci_simulate();init_close();init_codebase_review();init_concurrency();init_config3();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_recover();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals61.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",toolPolicy:"agent"},"guardrail-explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",aliasOf:"guardrail reset",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Read-only: runs independent of `turbo.epic.cochange.enabled` so it can be used as a what-if diagnostic before opting into the runtime signal.",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Epic Mode (autonomous coupling-aware parallel activation) and inspect its decisions",details:"Epic Mode is an additive overlay that composes Lean Turbo. When on, the architect follows the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → for each wave in order, dispatch one Task per taskId in the wave, ALL in one assistant message (each concurrent coder appears as a visible subagent the user can click into) → epic_record_divergence. epic_decide_phase computes the plan-wide coupling coefficient p and gates parallel promotion on p + a hot-module check + a greenfield rule. epic_plan_waves partitions promoted phases into ordered concurrent groups (waves) that respect dependency order and scope disjointness. Subcommands: on, off, status, decide (read-only what-if), last (most recent decision from durable evidence log), calibration (Capability D state: learned threshold + hot modules + recent divergent tasks). Bare /swarm epic shows status. Decision rationale persists to .swarm/evidence/epic-promotions.jsonl after every epic_decide_phase invocation.",args:"on | off | status | decide | last | calibration",category:"diagnostics",toolPolicy:"none"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. WARNING: alignment discards local changes and gitignored files. Resets agent sessions, delegation chains, and active-agent mappings. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
|
|
3564
3564
|
When set, the override takes precedence over the plan's locked execution_profile.max_concurrent_tasks.
|
|
3565
3565
|
`+`The override is session-scoped — it does not modify the plan and is cleared on session reset.
|
|
3566
3566
|
`+`
|
|
@@ -6994,4 +6994,4 @@ ${footerLines.join(`
|
|
|
6994
6994
|
`)),output.system=system}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;let timer=setTimeout(()=>{for(let task2 of tasks)try{Promise.resolve(task2()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig,regenerateMemoryReflectionForInit=async(directory,config3)=>{let{regenerateMemoryReflection:regenerateMemoryReflection2}=await Promise.resolve().then(() => (init_reflection_service(),exports_reflection_service));return regenerateMemoryReflection2(directory,config3)};function overrideIndexInternalsForTest(overrides){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit,previousRegenerateMemoryReflection=regenerateMemoryReflectionForInit;if(overrides.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides.createRepoGraphBuilderHook;if(overrides.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides.schedulePostResolutionTasks;if(overrides.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides.loadPluginConfigWithMetaAsync;if(overrides.loadSnapshot)loadSnapshotForInit=overrides.loadSnapshot;if(overrides.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides.ensureSwarmGitExcluded;if(overrides.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides.resolveAutoReviewConfig;if(overrides.regenerateMemoryReflection)regenerateMemoryReflectionForInit=overrides.regenerateMemoryReflection;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig,regenerateMemoryReflectionForInit=previousRegenerateMemoryReflection}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var OpenCodeSwarm=async(ctx)=>{let postResolutionTasks=[];try{let hooks=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),hooks}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map;function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")rememberAssistantUsage(part.sessionID,part)}}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(parentSessionID,taskOutput){let sessionIDs=[parentSessionID,...collectSessionIDs(taskOutput)];for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate2=value[key];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings();let __initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(ctx.directory),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=withTimeout(loadSnapshotForInit(ctx.directory),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}),gitExcludeP=withTimeout(ensureSwarmGitExcludedForInit(ctx.directory),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})});await Promise.all([configLoadP,snapshotP,gitExcludeP]);let{config:config3,loadedFromFile}=await configLoadP;if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),setGitBinaryOverride(config3.git?.binary),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:ctx.directory,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),initTelemetry(ctx.directory),startHeartbeatTracking();let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled?repoGraphHookFactory(ctx.directory,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null,repoGraphInitPromise;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphInitPromise=repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient).then((result)=>{if(!result.catalogAvailable)return;let unresolved=result.resolutions.filter((resolution)=>resolution.status==="unresolved");if(unresolved.length===0)return;let lines=unresolved.map((resolution)=>` ${resolution.agent}: ${resolution.model} (${resolution.detail??"does not resolve"})`),msg=`[opencode-swarm] WARNING: ${unresolved.length} configured agent model(s) do not resolve against the provider catalog:
|
|
6995
6995
|
${lines.join(`
|
|
6996
6996
|
`)}
|
|
6997
|
-
Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(()=>{withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:5000,reason:"post-init"})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})})});if(writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key of["message","reason","code","status","statusCode","error","cause","detail","details"])parts.push(...extractBoundedErrorSignal(record3[key],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:ctx.directory}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:2000,reason:"session-close"})},delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback);if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path327.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID);if(backgroundSubagentsEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),(normalizeToolName(input.tool)??input.tool)==="Task"&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,beganDelegation?.taskId||taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};
|
|
6997
|
+
Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(function(){return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:5000,reason:"post-init"})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})});if(writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key of["message","reason","code","status","statusCode","error","cause","detail","details"])parts.push(...extractBoundedErrorSignal(record3[key],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:ctx.directory}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:2000,reason:"session-close"})},delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback);if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path327.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID);if(backgroundSubagentsEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),(normalizeToolName(input.tool)??input.tool)==="Task"&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,beganDelegation?.taskId||taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};
|